From 818678a900b4784890dd218e9831f7666cae44b3 Mon Sep 17 00:00:00 2001 From: "Max F. Albrecht" <1@178.is> Date: Sat, 9 Feb 2019 23:58:57 +0100 Subject: [PATCH] format ruby with prettier-ruby --- app/controllers/attachments_controller.rb | 7 +- .../borrow/application_controller.rb | 39 +- .../borrow/availability_controller.rb | 50 +- .../borrow/categories_controller.rb | 11 +- .../borrow/concerns/create_lines.rb | 32 +- .../borrow/customer_orders_controller.rb | 63 +- app/controllers/borrow/groups_controller.rb | 1 - app/controllers/borrow/holidays_controller.rb | 1 - .../borrow/inventory_pools_controller.rb | 1 - app/controllers/borrow/models_controller.rb | 86 +- .../borrow/reservations_controller.rb | 43 +- app/controllers/borrow/returns_controller.rb | 11 +- app/controllers/borrow/search_controller.rb | 24 +- .../borrow/templates_controller.rb | 155 +- .../borrow/to_pick_up_controller.rb | 10 +- app/controllers/borrow/users_controller.rb | 5 +- app/controllers/borrow/workdays_controller.rb | 1 - app/controllers/categories_controller.rb | 8 +- app/controllers/category_links_controller.rb | 2 - .../concerns/expert_comparators.rb | 367 ++- app/controllers/concerns/expert_export.rb | 18 +- app/controllers/concerns/expert_filter.rb | 25 +- app/controllers/concerns/expert_view.rb | 81 +- app/controllers/concerns/file_storage.rb | 51 +- app/controllers/concerns/main_helpers.rb | 35 +- .../concerns/procurement_access.rb | 5 +- app/controllers/concerns/rooms_diff.rb | 84 +- .../concerns/timeline_availability.rb | 52 +- .../concerns/user_session_controller.rb | 27 +- .../concerns/workaround_rails_bug25198.rb | 7 +- app/controllers/errors_controller.rb | 14 +- app/controllers/images_controller.rb | 7 +- .../manage/access_rights_controller.rb | 16 +- .../manage/application_controller.rb | 59 +- .../manage/availability_controller.rb | 64 +- .../manage/buildings_controller.rb | 10 +- .../manage/categories_controller.rb | 29 +- .../manage/contracts_controller.rb | 68 +- .../manage/entitlement_groups_controller.rb | 73 +- app/controllers/manage/expert_controller.rb | 23 +- app/controllers/manage/fields_controller.rb | 61 +- app/controllers/manage/holidays_controller.rb | 2 - .../manage/inventory_controller.rb | 127 +- .../manage/inventory_pools_controller.rb | 119 +- app/controllers/manage/items_controller.rb | 177 +- .../manage/mail_templates_controller.rb | 37 +- app/controllers/manage/mails_controller.rb | 39 +- .../manage/model_links_controller.rb | 2 - app/controllers/manage/models_controller.rb | 248 +- app/controllers/manage/options_controller.rb | 2 - app/controllers/manage/orders_controller.rb | 59 +- .../manage/partitions_controller.rb | 9 +- .../manage/reservations_controller.rb | 274 +-- app/controllers/manage/rooms_controller.rb | 9 +- app/controllers/manage/search_controller.rb | 21 +- .../manage/suppliers_controller.rb | 8 +- .../manage/templates_controller.rb | 25 +- app/controllers/manage/users_controller.rb | 165 +- app/controllers/manage/visits_controller.rb | 77 +- app/controllers/manage/workdays_controller.rb | 2 - app/controllers/models_controller.rb | 13 +- app/controllers/properties_controller.rb | 2 - app/controllers/release_info_controller.rb | 1 - app/controllers/sessions_controller.rb | 12 +- app/controllers/styleguide_controller.rb | 14 +- app/helpers/barcode_helper.rb | 7 +- app/helpers/date_helper.rb | 2 - app/helpers/linkify_helper.rb | 2 - app/models/access_right.rb | 43 +- app/models/address.rb | 9 +- app/models/attachment.rb | 17 +- app/models/audit.rb | 47 +- app/models/authentication_system.rb | 3 +- app/models/availability/group.rb | 8 +- app/models/availability/inventory_pool.rb | 2 - app/models/availability/main.rb | 115 +- app/models/availability/model.rb | 8 +- app/models/availability/reservation.rb | 64 +- app/models/bread_crumbs.rb | 16 +- app/models/building.rb | 38 +- app/models/category.rb | 13 +- app/models/concerns/default_pagination.rb | 5 +- .../hash_serializer_for_old_yaml_stuff.rb | 1 - app/models/concerns/inventory_code.rb | 59 +- app/models/concerns/item_csv.rb | 41 +- app/models/concerns/log_send_mail_failure.rb | 10 +- app/models/concerns/scope_if_presence.rb | 6 +- app/models/concerns/search.rb | 16 +- .../concerns/serial_number_validation.rb | 18 +- app/models/contract.rb | 285 ++- app/models/delegation/reservation.rb | 8 +- app/models/delegation/user.rb | 57 +- app/models/disabled_field.rb | 1 - app/models/entitlement.rb | 65 +- app/models/entitlement_group.rb | 5 +- app/models/field.rb | 85 +- app/models/hidden_field.rb | 1 - app/models/holiday.rb | 5 +- app/models/image.rb | 8 +- app/models/inventory_pool.rb | 405 ++-- app/models/item.rb | 293 ++- app/models/item_line.rb | 49 +- app/models/language.rb | 17 +- .../line_modules/grouped_and_merged_lines.rb | 69 +- app/models/mail_template.rb | 94 +- app/models/mailer/order.rb | 82 +- app/models/mailer/user.rb | 60 +- app/models/model.rb | 513 ++--- app/models/model_group.rb | 49 +- app/models/model_group_link.rb | 5 +- app/models/model_link.rb | 5 +- app/models/notification.rb | 10 +- app/models/option.rb | 52 +- app/models/option_line.rb | 11 +- app/models/order.rb | 255 +-- app/models/property.rb | 1 - app/models/reservation.rb | 124 +- app/models/room.rb | 20 +- app/models/software.rb | 4 +- app/models/statistics/base.rb | 252 +-- app/models/supplier.rb | 25 +- app/models/template.rb | 27 +- app/models/user.rb | 221 +- app/models/user_session.rb | 23 +- app/models/visit.rb | 147 +- app/models/workday.rb | 24 +- .../application_record_presenter.rb | 2 +- app/presenters/borrow/booking_calendar.rb | 53 +- app/queries/booking_calendar_visits_query.rb | 5 +- app/validators/email_validator.rb | 10 +- cider-ci/bin/check-rails-warnings.rb | 10 +- cider-ci/bin/create-feature-tasks.rb | 40 +- cider-ci/bin/create-scenario-tasks.rb | 154 +- config/application.rb | 2 +- config/environments/development.rb | 2 +- config/environments/migrations.rb | 8 +- config/environments/production.rb | 10 +- config/environments/profiling.rb | 12 +- config/environments/test.rb | 4 +- config/initializers/actionmailer_settings.rb | 49 +- config/initializers/assets.rb | 26 +- config/initializers/error_handling.rb | 4 +- config/initializers/gettext.rb | 7 +- config/initializers/hoptoad.rb | 3 +- config/initializers/languages.rb | 12 +- config/initializers/money.rb | 59 +- config/initializers/react_rails.rb | 22 +- config/initializers/release_info.rb | 51 +- config/initializers/settings.rb | 77 +- config/initializers/string.rb | 6 +- config/initializers/time_formats.rb | 5 +- config/initializers/time_zone.rb | 2 +- config/routes.rb | 380 ++-- doc/add_access_rights_globally.rb | 2 - doc/import_export/csv_export_of_items.rb | 102 +- .../csv_export_of_leihs1_reservations.rb | 68 +- doc/import_export/csv_import_of_items.rb | 35 +- doc/import_export/csv_import_of_models.rb | 9 +- doc/import_export/csv_import_of_options.rb | 18 +- doc/import_export/csv_import_of_users.rb | 75 +- doc/import_export/exeter_import_of_items.rb | 30 +- doc/import_export/hslu_csv_import_of_items.rb | 62 +- doc/import_export/retire_items_from_csv.rb | 4 +- doc/other/adjust_project_numbers.rb | 28 +- doc/other/barcode_maker.rb | 68 +- doc/other/csv_mike_updater.rb | 9 +- doc/other/merge_models.rb | 15 +- .../leihs_admin/admin_controller.rb | 17 +- .../leihs_admin/audits_controller.rb | 31 +- .../leihs_admin/buildings_controller.rb | 12 +- .../leihs_admin/fields_controller.rb | 13 +- .../leihs_admin/fields_editor_controller.rb | 53 +- .../leihs_admin/inventory_controller.rb | 140 +- .../leihs_admin/inventory_pools_controller.rb | 40 +- .../leihs_admin/mail_templates_controller.rb | 34 +- .../leihs_admin/rooms_controller.rb | 19 +- .../leihs_admin/settings_controller.rb | 3 - .../leihs_admin/statistics_controller.rb | 56 +- .../leihs_admin/suppliers_controller.rb | 13 +- .../leihs_admin/users_controller.rb | 8 +- .../helpers/leihs_admin/application_helper.rb | 1 - engines/leihs_admin/config/routes.rb | 36 +- engines/leihs_admin/lib/leihs_admin.rb | 3 +- engines/leihs_admin/lib/leihs_admin/engine.rb | 4 +- .../leihs_admin/spec/steps/audits_steps.rb | 58 +- .../leihs_admin/spec/steps/buildings_steps.rb | 55 +- .../spec/steps/delegation_steps.rb | 17 +- .../leihs_admin/spec/steps/fields_steps.rb | 50 +- .../spec/steps/inventory_csv_steps.rb | 3 +- .../spec/steps/inventory_pools_steps.rb | 257 +-- .../leihs_admin/spec/steps/languages_steps.rb | 5 +- .../spec/steps/maintenance_mode_steps.rb | 94 +- engines/leihs_admin/spec/steps/rooms_steps.rb | 53 +- .../leihs_admin/spec/steps/settings_steps.rb | 50 +- .../spec/steps/shared/common_steps.rb | 8 +- .../spec/steps/shared/personas_dump_steps.rb | 4 +- .../spec/steps/statistics_steps.rb | 76 +- .../leihs_admin/spec/steps/suppliers_steps.rb | 20 +- factories/access_right_factory.rb | 2 - factories/accessory_factory.rb | 2 - factories/authentication_system_factory.rb | 1 - .../authentication_system_user_factory.rb | 1 - factories/building_factory.rb | 2 - factories/category_factory.rb | 8 +- factories/contract_factory.rb | 37 +- factories/group_factory.rb | 1 - factories/image_factory.rb | 14 +- factories/inventory_pool_factory.rb | 13 +- factories/item_factory.rb | 18 +- factories/language_factory.rb | 17 +- factories/model_factory.rb | 12 +- factories/model_group_factory.rb | 1 - factories/model_link_factory.rb | 1 - factories/option_factory.rb | 5 +- factories/order_factory.rb | 2 - factories/package_factory.rb | 18 +- factories/reservation_factory.rb | 36 +- factories/room_factory.rb | 2 - factories/setting_factory.rb | 26 +- factories/supplier_factory.rb | 4 +- factories/template_factory.rb | 7 +- factories/user_factory.rb | 34 +- factories/user_session_factory.rb | 6 +- factories/workday_factory.rb | 2 - .../step_definitions/acknowledge_steps.rb | 26 +- .../automatic_email_delivery_steps.rb | 11 +- .../availability_inventory_pool_steps.rb | 10 +- .../step_definitions/availability_steps.rb | 129 +- .../borrow/availability_steps.rb | 175 +- .../borrow/breadcrumb_navigation_steps.rb | 27 +- .../borrow/calendar2_steps.rb | 174 +- .../step_definitions/borrow/calendar_steps.rb | 142 +- .../borrow/explorative_search_steps.rb | 43 +- .../borrow/language_selection_steps.rb | 8 +- .../borrow/model_overview_steps.rb | 90 +- .../borrow/my_orders_overview_steps.rb | 124 +- .../borrow/navigation_steps.rb | 120 +- .../borrow/order_window_steps.rb | 52 +- .../step_definitions/borrow/orders_steps.rb | 27 +- .../borrow/pickups_returns_steps.rb | 155 +- .../step_definitions/borrow/search_steps.rb | 25 +- .../borrow/start_page_steps.rb | 77 +- .../borrow/templates_steps.rb | 103 +- .../borrow/timeoutpage_steps.rb | 76 +- .../borrow/view_my_user_data_steps.rb | 32 +- features/step_definitions/category_steps.rb | 37 +- .../step_definitions/database_login_steps.rb | 49 +- features/step_definitions/db_steps.rb | 10 +- features/step_definitions/debug_steps.rb | 14 +- features/step_definitions/documents_steps.rb | 118 +- features/step_definitions/group_steps.rb | 95 +- features/step_definitions/hand_over_steps.rb | 30 +- features/step_definitions/inventory_steps.rb | 32 +- features/step_definitions/login_steps.rb | 48 +- .../step_definitions/mail_management_steps.rb | 2 +- .../step_definitions/mail_templates_steps.rb | 239 +- .../manage/acknowledge/add_item_steps.rb | 57 +- .../manage/acknowledge/approve_steps.rb | 42 +- .../manage/acknowledge/delete_lines_steps.rb | 14 +- .../acknowledge/edit_order_line_steps.rb | 105 +- .../manage/acknowledge/edit_purpose_steps.rb | 3 +- .../manage/acknowledge/reject_steps.rb | 24 +- .../step_definitions/manage/add_line_steps.rb | 21 +- .../manage/availability/allocating_steps.rb | 16 +- .../availability_changes_steps.rb | 50 +- .../closed_day_alert_steps.rb | 39 +- .../summary_of_lines_in_calendar_steps.rb | 14 +- .../step_definitions/manage/calendar_steps.rb | 20 +- .../step_definitions/manage/category_steps.rb | 88 +- .../manage/change_orderer2_steps.rb | 11 +- .../manage/change_orderer_steps.rb | 12 +- .../step_definitions/manage/contract_steps.rb | 225 +- .../manage/copy_item_steps.rb | 102 +- .../manage/create_item_steps.rb | 236 +- .../manage/create_software_steps.rb | 32 +- .../manage/daily_view_steps.rb | 15 +- .../manage/delegation_mail_steps.rb | 60 +- .../manage/delegation_steps.rb | 293 +-- .../manage/edit_item_steps.rb | 69 +- .../manage/explorative_search_steps.rb | 50 +- .../step_definitions/manage/groups_steps.rb | 97 +- .../manage/hand_over/add_steps.rb | 142 +- .../manage/hand_over/assign_steps.rb | 57 +- .../manage/hand_over/delete_steps.rb | 33 +- .../manage/hand_over/edit_contract_steps.rb | 31 +- .../manage/hand_over/sign_contract_steps.rb | 235 +- .../manage/hand_over_steps.rb | 154 +- .../manage/inventory_expert_search_steps.rb | 2001 +++++++---------- .../manage/inventory_helper_steps.rb | 277 ++- .../manage/inventory_steps.rb | 596 ++--- .../manage/lending/lending_steps.rb | 214 +- .../manage/lending/tabs_navigation_steps.rb | 18 +- .../step_definitions/manage/lending_steps.rb | 8 +- .../manage/linegroup/selection_steps.rb | 16 +- .../manage/model_properties_steps.rb | 32 +- .../step_definitions/manage/modell_steps.rb | 108 +- .../manage/old_timeline_steps.rb | 23 +- .../step_definitions/manage/orders_steps.rb | 265 ++- .../step_definitions/manage/package_steps.rb | 121 +- .../step_definitions/manage/password_steps.rb | 96 +- .../manage/picking_list_steps.rb | 126 +- .../manage/pool_information_steps.rb | 229 +- .../step_definitions/manage/problems_steps.rb | 258 ++- .../step_definitions/manage/purpose_steps.rb | 83 +- .../manage/retire_item_steps.rb | 80 +- .../step_definitions/manage/search_steps.rb | 182 +- .../step_definitions/manage/software_steps.rb | 670 +++--- .../manage/take_back/close_contract_steps.rb | 51 +- .../edit_take_back_end_date_steps.rb | 31 +- .../manage/take_back_steps.rb | 119 +- .../manage/templates_steps.rb | 89 +- .../step_definitions/manage/timeline_steps.rb | 41 +- .../manage/user_management_steps.rb | 639 +++--- .../manage/value_list_steps.rb | 355 +-- .../manage/verification_steps.rb | 39 +- .../step_definitions/manage/visits_steps.rb | 4 +- features/step_definitions/misc_steps.rb | 4 +- features/step_definitions/package_steps.rb | 15 +- .../performance_stability_steps.rb | 97 +- features/step_definitions/persona_steps.rb | 20 +- features/step_definitions/search_steps.rb | 8 +- features/step_definitions/settings_steps.rb | 14 +- .../support/helper_methods.rb | 28 +- features/step_definitions/take_back_steps.rb | 8 +- .../technical/contract_steps.rb | 11 +- .../technical/eval_helpers.rb | 18 +- .../step_definitions/technical/field_steps.rb | 54 +- .../technical/fields_controller_steps.rb | 9 +- .../technical/inventory_pool_steps.rb | 140 +- .../step_definitions/technical/item_steps.rb | 4 +- .../technical/ldap_hslu_steps.rb | 412 ++-- .../step_definitions/technical/ldap_steps.rb | 28 +- .../technical/mailer_steps.rb | 6 +- .../step_definitions/technical/model_steps.rb | 4 +- .../step_definitions/technical/order_steps.rb | 89 +- .../technical/orders_controller_steps.rb | 10 +- .../technical/shibboleth_steps.rb | 23 +- .../step_definitions/technical/user_steps.rb | 31 +- .../step_definitions/technical/visit_steps.rb | 32 +- .../technical/visits_controller_steps.rb | 81 +- .../step_definitions/user_management_steps.rb | 32 +- features/step_definitions/view_steps.rb | 2 +- features/step_definitions/web_extra_steps.rb | 31 +- features/step_definitions/web_steps.rb | 49 +- features/step_definitions/work_days_steps.rb | 51 +- features/support/common_steps.rb | 29 +- features/support/dataset.rb | 8 +- features/support/env.rb | 21 +- features/support/env_screenshots.rb | 28 +- features/support/helper.rb | 47 +- features/support/leihs_factory.rb | 301 ++- features/support/paths.rb | 24 +- features/support/selectors.rb | 16 +- lib/authenticated_system.rb | 12 +- lib/export.rb | 13 +- lib/leihs/dbio.rb | 12 +- lib/leihs/dbio/import.rb | 214 +- secrets/agw_info_prod.rb | Bin 230 -> 0 bytes secrets/agw_info_test.rb | Bin 233 -> 0 bytes .../integration/sign_in_and_session_spec.rb | 2 +- spec/models/contract_spec.rb | 15 +- spec/models/field_spec.rb | 8 +- spec/models/reservation_spec.rb | 116 +- spec/rails_helper.rb | 5 +- spec/spec_helper.rb | 20 +- spec/steps/borrow/current_order_steps.rb | 10 +- .../borrow/inactive_inventory_pool_steps.rb | 63 +- spec/steps/borrow/inventory_pool_steps.rb | 37 +- spec/steps/borrow/list_of_orders_steps.rb | 20 +- spec/steps/borrow/list_of_pickups_steps.rb | 10 +- spec/steps/borrow/list_of_returns_steps.rb | 7 +- spec/steps/borrow/model_list_steps.rb | 356 ++- spec/steps/borrow/order_mail_steps.rb | 65 +- spec/steps/borrow/submit_order_steps.rb | 16 +- spec/steps/current_order_steps.rb | 10 +- spec/steps/integration/time_zone_steps.rb | 6 +- .../manage/availability_calendar_steps.rb | 108 +- .../case_insensitive_inventory_code_steps.rb | 50 +- spec/steps/manage/category_crud_steps.rb | 7 +- .../manage/create_software_license_steps.rb | 66 +- spec/steps/manage/delegations_steps.rb | 140 +- spec/steps/manage/edit_user_steps.rb | 15 +- spec/steps/manage/global_search_steps.rb | 151 +- spec/steps/manage/hand_over_steps.rb | 90 +- .../manage/inactive_inventory_pools_steps.rb | 51 +- spec/steps/manage/inventory_steps.rb | 68 +- spec/steps/manage/model_crud_steps.rb | 9 +- .../manage/serial_number_validation_steps.rb | 72 +- spec/steps/manage/take_back_steps.rb | 56 +- .../visits_verification_filter_steps.rb | 116 +- spec/steps/shared/common_steps.rb | 22 +- spec/steps/shared/factory_steps.rb | 23 +- spec/steps/shared/login_steps.rb | 25 +- spec/steps/shared/personas_dump_steps.rb | 4 +- spec/turnip_helper.rb | 32 +- 395 files changed, 12215 insertions(+), 13232 deletions(-) diff --git a/app/controllers/attachments_controller.rb b/app/controllers/attachments_controller.rb index a633881f0c..f882b7c34a 100644 --- a/app/controllers/attachments_controller.rb +++ b/app/controllers/attachments_controller.rb @@ -2,11 +2,8 @@ class AttachmentsController < ApplicationController def show attachment = Attachment.find(id_param) if attachment and attachment.content - send_data \ - Base64.decode64(attachment.content), - filename: attachment.filename, - type: attachment.content_type, - disposition: 'inline' + send_data Base64.decode64(attachment.content), + filename: attachment.filename, type: attachment.content_type, disposition: 'inline' else head :not_found and return end diff --git a/app/controllers/borrow/application_controller.rb b/app/controllers/borrow/application_controller.rb index a780b268da..bba475f684 100644 --- a/app/controllers/borrow/application_controller.rb +++ b/app/controllers/borrow/application_controller.rb @@ -1,5 +1,4 @@ class Borrow::ApplicationController < ApplicationController - layout 'borrow' before_action :check_maintenance_mode, except: :maintenance @@ -8,8 +7,7 @@ class Borrow::ApplicationController < ApplicationController def root current_user_categories = current_user.all_categories @categories = (current_user_categories & Category.roots).sort - @child_categories = \ - @categories.map { |c| (current_user_categories & c.children).sort } + @child_categories = @categories.map { |c| (current_user_categories & c.children).sort } @any_template = current_user.templates.any? end @@ -17,14 +15,13 @@ def refresh_timeout # ok, refreshed respond_to do |format| format.html { head :ok } - date = if current_user.reservations.unsubmitted.empty? - Time.zone.now - else - current_user.reservations.unsubmitted.first.updated_at - end - format.json do - render json: { date: date } - end + date = + if current_user.reservations.unsubmitted.empty? + Time.zone.now + else + current_user.reservations.unsubmitted.first.updated_at + end + format.json { render json: { date: date } } end end @@ -39,14 +36,17 @@ def require_customer end def redirect_if_order_timed_out - return if request.format == :json or - [borrow_order_timed_out_path, - borrow_order_delete_unavailables_path, - borrow_order_remove_path, - borrow_order_remove_reservations_path, - borrow_change_time_range_path].include? request.path - if current_user.timeout? \ - and current_user.reservations.unsubmitted.any? { |l| not l.available? } + if request.format == :json or + [ + borrow_order_timed_out_path, + borrow_order_delete_unavailables_path, + borrow_order_remove_path, + borrow_order_remove_reservations_path, + borrow_change_time_range_path + ].include? request.path + return + end + if current_user.timeout? and current_user.reservations.unsubmitted.any? { |l| nl.available? } redirect_to borrow_order_timed_out_path else current_user.reservations.unsubmitted.each &:touch @@ -56,5 +56,4 @@ def redirect_if_order_timed_out def init_breadcrumbs @bread_crumbs = BreadCrumbs.new params.delete('_bc') end - end diff --git a/app/controllers/borrow/availability_controller.rb b/app/controllers/borrow/availability_controller.rb index da5e628b10..38c00973ea 100644 --- a/app/controllers/borrow/availability_controller.rb +++ b/app/controllers/borrow/availability_controller.rb @@ -1,22 +1,17 @@ class Borrow::AvailabilityController < Borrow::ApplicationController - def show model = current_user.models.borrowable.find params[:model_id] inventory_pool = current_user.inventory_pools.find params[:inventory_pool_id] - @availability = - { - id: "#{model.id}-#{current_user.id}-#{inventory_pool.id}", - changes: \ - model.availability_in(inventory_pool).available_total_quantities, - total_borrowable: \ + @availability = { + id: "#{model.id}-#{current_user.id}-#{inventory_pool.id}", + changes: model.availability_in(inventory_pool).available_total_quantities, + total_borrowable: model.total_borrowable_items_for_user_and_pool( - current_user, - inventory_pool, - ensure_non_negative_general: true + current_user, inventory_pool, ensure_non_negative_general: true ), - inventory_pool_id: inventory_pool.id, - model_id: model.id - } + inventory_pool_id: inventory_pool.id, + model_id: model.id + } end def booking_calendar_availability @@ -24,12 +19,8 @@ def booking_calendar_availability ip = InventoryPool.find(inventory_pool_id_param) user = User.find(user_id_param) reservations = Reservation.find(reservation_ids_param) - presenter = Borrow::BookingCalendar.new(ip, - model, - user, - start_date_param, - end_date_param, - reservations) + presenter = + Borrow::BookingCalendar.new(ip, model, user, start_date_param, end_date_param, reservations) respond_with_presenter(presenter) end @@ -37,17 +28,16 @@ def booking_calendar_availability def total_borrowable_quantities model = Model.find(model_id_param) inventory_pools = InventoryPool.find(inventory_pool_ids_param) - result = inventory_pools.map do |inventory_pool| - { - inventory_pool_id: inventory_pool.id, - total_borrowable: \ - model.total_borrowable_items_for_user_and_pool( - current_user, - inventory_pool, - ensure_non_negative_general: true - ) - } - end + result = + inventory_pools.map do |inventory_pool| + { + inventory_pool_id: inventory_pool.id, + total_borrowable: + model.total_borrowable_items_for_user_and_pool( + current_user, inventory_pool, ensure_non_negative_general: true + ) + } + end render(json: result) and return end diff --git a/app/controllers/borrow/categories_controller.rb b/app/controllers/borrow/categories_controller.rb index 2c381a8df3..28d55432ec 100644 --- a/app/controllers/borrow/categories_controller.rb +++ b/app/controllers/borrow/categories_controller.rb @@ -1,16 +1,9 @@ class Borrow::CategoriesController < Borrow::ApplicationController - def index(category_id = params[:category_id]) - categories = \ - (current_user.all_categories & Category.find(category_id).children) - .sort + categories = (current_user.all_categories & Category.find(category_id).children).sort - output = categories.map do |category| - { id: category.id, - name: category.label(category_id) } - end + output = categories.map { |category| { id: category.id, name: category.label(category_id) } } render json: output end - end diff --git a/app/controllers/borrow/concerns/create_lines.rb b/app/controllers/borrow/concerns/create_lines.rb index 887379b893..20a944e9ac 100644 --- a/app/controllers/borrow/concerns/create_lines.rb +++ b/app/controllers/borrow/concerns/create_lines.rb @@ -1,28 +1,20 @@ module Borrow module Concerns module CreateLines - def create_lines(model:, - status:, - quantity:, - inventory_pool:, - start_date: nil, - end_date: nil, - delegated_user_id: nil) - if end_date and start_date and end_date < start_date - end_date = start_date - end + def create_lines(model:, status:, quantity:, inventory_pool:, start_date: nil, end_date: nil, delegated_user_id: nil) + end_date = start_date if end_date and start_date and end_date < start_date - attrs = { inventory_pool: inventory_pool, - status: status, - quantity: 1, - model: model, - start_date: start_date || time_window_min, - end_date: end_date || next_open_date(time_window_max), - delegated_user_id: delegated_user_id } + attrs = { + inventory_pool: inventory_pool, + status: status, + quantity: 1, + model: model, + start_date: start_date || time_window_min, + end_date: end_date || next_open_date(time_window_max), + delegated_user_id: delegated_user_id + } - new_lines = Integer(quantity).times.map do - current_user.item_lines.create(attrs) - end + new_lines = Integer(quantity).times.map { current_user.item_lines.create(attrs) } new_lines end diff --git a/app/controllers/borrow/customer_orders_controller.rb b/app/controllers/borrow/customer_orders_controller.rb index 33972cc2b9..f0b479f44d 100644 --- a/app/controllers/borrow/customer_orders_controller.rb +++ b/app/controllers/borrow/customer_orders_controller.rb @@ -1,17 +1,15 @@ class Borrow::CustomerOrdersController < Borrow::ApplicationController - before_action only: [:current, :timed_out] do - @grouped_and_merged_lines = \ + @grouped_and_merged_lines = Contract.grouped_and_merged_lines(current_user.reservations.unsubmitted) @models = current_user.reservations.unsubmitted.map(&:model).uniq - @inventory_pools = \ - current_user.reservations.unsubmitted.map(&:inventory_pool).uniq + @inventory_pools = current_user.reservations.unsubmitted.map(&:inventory_pool).uniq end def index respond_to do |format| format.html do - @grouped_and_merged_lines = \ + @grouped_and_merged_lines = Contract.grouped_and_merged_lines current_user.reservations.submitted end end @@ -24,27 +22,25 @@ def current def submit Order.transaction do begin - current_user - .reservations - .unsubmitted - .group_by(&:inventory_pool_id) + current_user.reservations.unsubmitted.group_by(&:inventory_pool_id) .each_pair do |inventory_pool_id, reservations| inventory_pool = InventoryPool.find(inventory_pool_id) - order = Order.create!(user: current_user, - inventory_pool: inventory_pool, - purpose: purpose_param, - state: :submitted) + order = + Order.create!( + user: current_user, + inventory_pool: inventory_pool, + purpose: purpose_param, + state: :submitted + ) reservations.each do |reservation| if reservation.user.delegation? - reservation.delegated_user = \ + reservation.delegated_user = reservation.user.delegated_users.find(user_session.user_id) end reservation.order = order reservation.status = :submitted - unless reservation.approvable? - raise reservation.errors.full_messages.uniq.join(', ') - end + raise reservation.errors.full_messages.uniq.join(', ') unless reservation.approvable? reservation.save! end @@ -52,8 +48,11 @@ def submit order.send_submitted_notification order.send_received_notification end - flash[:notice] = _('Your order has been successfully submitted, ' \ - 'but is NOT YET APPROVED.') + flash[:notice] = + _( + 'Your order has been successfully submitted, ' \ + 'but is NOT YET APPROVED.' + ) redirect_to borrow_root_path rescue => e Rails.logger.warn e @@ -76,9 +75,9 @@ def remove_reservations(line_ids = params[:line_ids]) end def timed_out - flash[:error] = \ - _('%d minutes passed. The items are not reserved for you any more!') \ - % app_settings.timeout_minutes + flash[:error] = + _('%d minutes passed. The items are not reserved for you any more!') % + app_settings.timeout_minutes @timed_out = true @inventory_pools_for_calendar = inventory_pools_for_calendar(@inventory_pools) render :current @@ -86,25 +85,29 @@ def timed_out def delete_unavailables current_user.reservations.unsubmitted.each { |l| l.delete unless l.available? } - redirect_to \ - borrow_current_order_path, - flash: { success: _('Your order has been modified. ' \ - 'All reservations are now available.') } + redirect_to borrow_current_order_path, + flash: { + success: + _( + 'Your order has been modified. ' \ + 'All reservations are now available.' + ) + } end private def inventory_pools_for_calendar(inventory_pools) inventory_pools.map do |ip| - { inventory_pool: ip, + { + inventory_pool: ip, workday: ip.workday, - holidays: \ - ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date) } + holidays: ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date) + } end end def purpose_param params.require(:purpose) end - end diff --git a/app/controllers/borrow/groups_controller.rb b/app/controllers/borrow/groups_controller.rb index 8c71578e7f..3cb7e76f22 100644 --- a/app/controllers/borrow/groups_controller.rb +++ b/app/controllers/borrow/groups_controller.rb @@ -1,5 +1,4 @@ class Borrow::GroupsController < Borrow::ApplicationController - def index @groups = current_user.entitlement_groups end diff --git a/app/controllers/borrow/holidays_controller.rb b/app/controllers/borrow/holidays_controller.rb index 0033740b88..1f1caf0a1e 100644 --- a/app/controllers/borrow/holidays_controller.rb +++ b/app/controllers/borrow/holidays_controller.rb @@ -1,5 +1,4 @@ class Borrow::HolidaysController < Borrow::ApplicationController - def index @holidays = current_user.inventory_pools.map(&:holidays).flatten end diff --git a/app/controllers/borrow/inventory_pools_controller.rb b/app/controllers/borrow/inventory_pools_controller.rb index a4a8c639b5..7e0bf9d943 100644 --- a/app/controllers/borrow/inventory_pools_controller.rb +++ b/app/controllers/borrow/inventory_pools_controller.rb @@ -1,5 +1,4 @@ class Borrow::InventoryPoolsController < Borrow::ApplicationController - def index @inventory_pools = current_user.inventory_pools.reorder(:name) end diff --git a/app/controllers/borrow/models_controller.rb b/app/controllers/borrow/models_controller.rb index 816e2adfc4..ebc1204d97 100644 --- a/app/controllers/borrow/models_controller.rb +++ b/app/controllers/borrow/models_controller.rb @@ -1,25 +1,22 @@ class Borrow::ModelsController < Borrow::ApplicationController - def availability models = current_user.models.borrowable.where(id: params[:model_ids]) start_date = Date.parse(params[:start_date]) end_date = Date.parse(params[:end_date]) - inventory_pools = \ - current_user.inventory_pools.where(id: params[:inventory_pool_ids]) - @availability = models.map do |model| - inventory_pools.map do |ip| - { - model_id: model.id, - inventory_pool_id: ip.id, - quantity: \ - model - .availability_in(ip) - .maximum_available_in_period_summed_for_groups( + inventory_pools = current_user.inventory_pools.where(id: params[:inventory_pool_ids]) + @availability = + models.map do |model| + inventory_pools.map do |ip| + { + model_id: model.id, + inventory_pool_id: ip.id, + quantity: + model.availability_in(ip).maximum_available_in_period_summed_for_groups( start_date, end_date, current_user.entitlement_groups.map(&:id) ) - } + } + end end - end @availability.flatten! end @@ -27,56 +24,25 @@ def index @category = Category.find_by_id params[:category_id] @models = Model.filter params, current_user, @category, true set_pagination_header(@models) - respond_to do |format| - format.json - format.html do - @child_categories = @category.children.select do |c| - @models.from_category_and_all_its_descendants(c).exists? - end - @grand_children = {} - @child_categories.each do |category| - @grand_children[category.id] = \ - category.children.select do |c| - @models.from_category_and_all_its_descendants(c).exists? - end - end - @inventory_pools = \ - current_user.inventory_pools.with_borrowable_items.order(:name) - - # used for React booking calendar ######################################### - @inventory_pools_for_calendar = @inventory_pools.map do |ip| - { inventory_pool: ip, - workday: ip.workday, - holidays: \ - ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date) } - end - ########################################################################### - end - end + respond_to(&:json) end def show @model = current_user.models.borrowable.find(params[:id]) - @inventory_pools = current_user.inventory_pools.order(:name).map do |ip| - { - inventory_pool: ip, - workday: ip.workday, - holidays: \ - ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date), - total_borrowable: \ - @model.total_borrowable_items_for_user_and_pool( - current_user, - ip, - ensure_non_negative_general: true - ) - } - end - .select { |ip_context| ip_context[:total_borrowable].positive? } + @inventory_pools = + current_user.inventory_pools.order(:name).map do |ip| + { + inventory_pool: ip, + workday: ip.workday, + holidays: ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date), + total_borrowable: + @model.total_borrowable_items_for_user_and_pool( + current_user, ip, ensure_non_negative_general: true + ) + } + end + .select { |ip_context| ip_context[:total_borrowable].positive? } - respond_to do |format| - format.json - format.html - end + respond_to(&:json) end - end diff --git a/app/controllers/borrow/reservations_controller.rb b/app/controllers/borrow/reservations_controller.rb index 9623580904..56b9dd68e3 100644 --- a/app/controllers/borrow/reservations_controller.rb +++ b/app/controllers/borrow/reservations_controller.rb @@ -10,11 +10,8 @@ class Borrow::ReservationsController < Borrow::ApplicationController unless @inventory_pool.open_on?(@start_date) @errors << _('Inventory pool is closed on start date') end - unless @inventory_pool.open_on?(@end_date) - @errors << _('Inventory pool is closed on end date') - end - if @start_date < \ - Time.zone.today + @inventory_pool.workday.reservation_advance_days.days + @errors << _('Inventory pool is closed on end date') unless @inventory_pool.open_on?(@end_date) + if @start_date < Time.zone.today + @inventory_pool.workday.reservation_advance_days.days @errors << _('No orders are possible on this start date') end if @inventory_pool.workday.reached_max_visits.include? @start_date @@ -35,15 +32,16 @@ def create if @errors.empty? begin ApplicationRecord.transaction do - reservations = create_lines( - model: model, - quantity: quantity_param, - status: :unsubmitted, - inventory_pool: @inventory_pool, - start_date: @start_date, - end_date: @end_date, - delegated_user_id: session[:delegated_user_id] - ) + reservations = + create_lines( + model: model, + quantity: quantity_param, + status: :unsubmitted, + inventory_pool: @inventory_pool, + start_date: @start_date, + end_date: @end_date, + delegated_user_id: session[:delegated_user_id] + ) if reservations and reservations.all?(&:valid?) render status: :ok, json: reservations return @@ -62,11 +60,7 @@ def create def destroy begin ApplicationRecord.transaction do - current_user - .reservations - .unsubmitted - .find(params[:line_ids]) - .map(&:destroy!) + current_user.reservations.unsubmitted.find(params[:line_ids]).map(&:destroy!) end render status: :ok, json: {} rescue => e @@ -98,12 +92,9 @@ def quantity_param end def quantity_available?(model, quantity) - model - .availability_in(@inventory_pool) - .maximum_available_in_period_summed_for_groups( - @start_date, - @end_date, - current_user.entitlement_group_ids) \ - >= quantity + model.availability_in(@inventory_pool).maximum_available_in_period_summed_for_groups( + @start_date, @end_date, current_user.entitlement_group_ids + ) >= + quantity end end diff --git a/app/controllers/borrow/returns_controller.rb b/app/controllers/borrow/returns_controller.rb index cf1ff4ee8a..aaf9f86efa 100644 --- a/app/controllers/borrow/returns_controller.rb +++ b/app/controllers/borrow/returns_controller.rb @@ -1,15 +1,8 @@ class Borrow::ReturnsController < Borrow::ApplicationController - def index - @grouped_lines = \ + @grouped_lines = Hash[ - current_user - .reservations - .signed - .sort - .group_by { |l| [l.end_date, l.inventory_pool] } - .sort + current_user.reservations.signed.sort.group_by { |l| [l.end_date, l.inventory_pool] }.sort ] end - end diff --git a/app/controllers/borrow/search_controller.rb b/app/controllers/borrow/search_controller.rb index 3a15270d4a..b8ccf1e4bd 100644 --- a/app/controllers/borrow/search_controller.rb +++ b/app/controllers/borrow/search_controller.rb @@ -1,33 +1,13 @@ class Borrow::SearchController < Borrow::ApplicationController - def search search_term = params[:search_term] - respond_to do |format| - format.json - format.html do - redirect_to borrow_search_results_path(search_term: search_term) - end - end + respond_to(&:json) end def results @search_term = params[:search_term] @models = Model.filter params, current_user, @category, true set_pagination_header(@models) - respond_to do |format| - format.json - format.html do - # used for React booking calendar ######################################### - @inventory_pools_for_calendar = current_user.inventory_pools.map do |ip| - { inventory_pool: ip, - workday: ip.workday, - holidays: \ - ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date) } - end - ########################################################################### - @inventory_pools = current_user.inventory_pools.order(:name) - end - end + respond_to(&:json) end - end diff --git a/app/controllers/borrow/templates_controller.rb b/app/controllers/borrow/templates_controller.rb index 95ea2ca3d0..a5f931f737 100644 --- a/app/controllers/borrow/templates_controller.rb +++ b/app/controllers/borrow/templates_controller.rb @@ -6,57 +6,57 @@ class Borrow::TemplatesController < Borrow::ApplicationController end def add_to_order - reservations = params[:reservations].map do |line| - { - model: Model.find_by_id(line['model_id']), - quantity: Integer(line['quantity']), - start_date: Date.parse(line['start_date']), - end_date: Date.parse(line['end_date']), - inventory_pool: InventoryPool.find_by_id(line['inventory_pool_id']) - } - end + reservations = + params[:reservations].map do |line| + { + model: Model.find_by_id(line['model_id']), + quantity: Integer(line['quantity']), + start_date: Date.parse(line['start_date']), + end_date: Date.parse(line['end_date']), + inventory_pool: InventoryPool.find_by_id(line['inventory_pool_id']) + } + end - unavailable_lines, available_lines = \ + unavailable_lines, available_lines = reservations.partition do |l| - l[:inventory_pool].blank? or not \ - l[:model] - .availability_in(l[:inventory_pool]) + l[:inventory_pool].blank? or + nl[:model].availability_in(l[:inventory_pool]) .maximum_available_in_period_summed_for_groups( - l[:start_date], - l[:end_date], - current_user.entitlement_groups.map(&:id)) >= l[:quantity] - end + l[:start_date], l[:end_date], current_user.entitlement_groups.map(&:id) + ) >= + l[:quantity] + end - if not unavailable_lines.empty? and params[:force_continue].blank? + if nunavailable_lines.empty? and params[:force_continue].blank? availability and render :availability else available_lines.each do |l| - create_lines(model: l[:model], - quantity: l[:quantity], - status: :unsubmitted, - inventory_pool: l[:inventory_pool], - start_date: l[:start_date], - end_date: l[:end_date], - delegated_user_id: session[:delegated_user_id]) + create_lines( + model: l[:model], + quantity: l[:quantity], + status: :unsubmitted, + inventory_pool: l[:inventory_pool], + start_date: l[:start_date], + end_date: l[:end_date], + delegated_user_id: session[:delegated_user_id] + ) end - redirect_to \ - borrow_current_order_path, - flash: { success: _('The template has been added to your order.') } + redirect_to borrow_current_order_path, + flash: { success: _('The template has been added to your order.') } end end def select_dates model_links = @template.model_links @models = @template.models - @reservations = \ - params[:reservations].delete_if do |l| - Integer(l['quantity'].presence || 0) == 0 - end.map do |line| + @reservations = + params[:reservations].delete_if { |l| Integer(l['quantity'].presence || 0) == 0 } + .map do |line| model = @models.detect { |m| m.id == line['model_id'] } quantity = Integer(line['quantity']) + { - model_link_id: \ - model_links.detect { |link| link.model_id == model.id }.id, + model_link_id: model_links.detect { |link| link.model_id == model.id }.id, template_id: @template.id, model_id: model.id, quantity: quantity @@ -68,58 +68,52 @@ def availability unborrowable_models = @template.unaccomplishable_models current_user, 1 model_links = @template.model_links @models = @template.models - @reservations = \ - params[:reservations] - .delete_if { |l| Integer(l['quantity'].presence || 0) == 0 } + @reservations = + params[:reservations].delete_if { |l| Integer(l['quantity'].presence || 0) == 0 } .map do |line| - model = @models.detect { |m| m.id == line['model_id'] } - quantity = Integer(line['quantity']) - start_date = if line['start_date'] - Date.parse(line['start_date']) - else - Date.parse(params[:start_date]) - end - end_date = if line['end_date'] - Date.parse(line['end_date']) - else - Date.parse(params[:end_date]) - end - inventory_pool = nil - { - model_link_id: \ - model_links.detect { |link| link.model_id == model.id }.id, - template_id: @template.id, - model_id: model.id, - quantity: quantity, - start_date: start_date, - end_date: end_date, - available: \ - (model.inventory_pools & current_user.inventory_pools).any? do |ip| - (model.availability_in(ip) - .maximum_available_in_period_summed_for_groups( - start_date, - end_date, - current_user.entitlement_groups.map(&:id)) >= quantity) and + model = @models.detect { |m| m.id == line['model_id'] } + quantity = Integer(line['quantity']) + start_date = + line['start_date'] ? Date.parse(line['start_date']) : Date.parse(params[:start_date]) + end_date = line['end_date'] ? Date.parse(line['end_date']) : Date.parse(params[:end_date]) + inventory_pool = nil + + { + model_link_id: model_links.detect { |link| link.model_id == model.id }.id, + template_id: @template.id, + model_id: model.id, + quantity: quantity, + start_date: start_date, + end_date: end_date, + available: + (model.inventory_pools & current_user.inventory_pools).any? do |ip| + (model.availability_in(ip).maximum_available_in_period_summed_for_groups( + start_date, end_date, current_user.entitlement_groups.map(&:id) + ) >= + quantity) and ip.open_on?(start_date) and ip.open_on?(end_date) and (inventory_pool = ip) - end, - inventory_pool_id: inventory_pool.try(&:id), - unborrowable: unborrowable_models.include?(model) - } - end - @grouped_and_merged_lines = @reservations.group_by do |l| - { start_date: l[:start_date], - inventory_pool_name: \ - InventoryPool.find_by_id(l[:inventory_pool_id]).try(&:name), - inventory_pool_id: l[:inventory_pool_id] } - end - @inventory_pools_for_calendar = \ + end, + inventory_pool_id: inventory_pool.try(&:id), + unborrowable: unborrowable_models.include?(model) + } + end + @grouped_and_merged_lines = + @reservations.group_by do |l| + { + start_date: l[:start_date], + inventory_pool_name: InventoryPool.find_by_id(l[:inventory_pool_id]).try(&:name), + inventory_pool_id: l[:inventory_pool_id] + } + end + @inventory_pools_for_calendar = @template.inventory_pools.map do |ip| - { inventory_pool: ip, + { + inventory_pool: ip, workday: ip.workday, - holidays: \ - ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date) } + holidays: ip.holidays.where('CURRENT_DATE <= end_date').order(:end_date) + } end end @@ -131,5 +125,4 @@ def show @model_links = @template.model_links.sort_by { |link| link.model.name } @unaccomplishable_models = @template.unaccomplishable_models current_user end - end diff --git a/app/controllers/borrow/to_pick_up_controller.rb b/app/controllers/borrow/to_pick_up_controller.rb index 1a069d1ef0..7ef395d747 100644 --- a/app/controllers/borrow/to_pick_up_controller.rb +++ b/app/controllers/borrow/to_pick_up_controller.rb @@ -1,12 +1,6 @@ class Borrow::ToPickUpController < Borrow::ApplicationController - def index - @grouped_and_merged_lines = \ - Visit.grouped_and_merged_lines \ - current_user \ - .visits - .hand_over - .flat_map(&:reservations) + @grouped_and_merged_lines = + Visit.grouped_and_merged_lines current_user.visits.hand_over.flat_map(&:reservations) end - end diff --git a/app/controllers/borrow/users_controller.rb b/app/controllers/borrow/users_controller.rb index a6d28f1ad3..5cf860c3c7 100644 --- a/app/controllers/borrow/users_controller.rb +++ b/app/controllers/borrow/users_controller.rb @@ -1,9 +1,7 @@ class Borrow::UsersController < Borrow::ApplicationController - def documents @contracts = current_user.contracts - @contracts = \ - @contracts.to_a.sort { |a, b| a.time_window_min <=> b.time_window_min } + @contracts = @contracts.to_a.sort { |a, b| a.time_window_min <=> b.time_window_min } end def delegations @@ -41,5 +39,4 @@ def value_list @inventory_pool = @contract.inventory_pool render 'documents/value_list', layout: 'print' end - end diff --git a/app/controllers/borrow/workdays_controller.rb b/app/controllers/borrow/workdays_controller.rb index 36d0da7f30..48729b72ee 100644 --- a/app/controllers/borrow/workdays_controller.rb +++ b/app/controllers/borrow/workdays_controller.rb @@ -1,5 +1,4 @@ class Borrow::WorkdaysController < Borrow::ApplicationController - def index @workdays = current_user.inventory_pools.map(&:workday) end diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rb index 5d45165b2c..3610a2266f 100644 --- a/app/controllers/categories_controller.rb +++ b/app/controllers/categories_controller.rb @@ -1,14 +1,9 @@ class CategoriesController < ApplicationController - def index @categories = if params[:children] if params[:category_id] - if params[:category_id] == '-1' - [] - else - Category.find(params[:category_id]).children - end + params[:category_id] == '-1' ? [] : Category.find(params[:category_id]).children elsif params[:category_ids] Category.find(params[:category_ids]).map(&:children) end @@ -25,5 +20,4 @@ def image redirect_to get_image_path(category.image.id) end end - end diff --git a/app/controllers/category_links_controller.rb b/app/controllers/category_links_controller.rb index 2167b5bc87..df271b071e 100644 --- a/app/controllers/category_links_controller.rb +++ b/app/controllers/category_links_controller.rb @@ -1,5 +1,4 @@ class CategoryLinksController < ApplicationController - def index @links = if params[:parent_id].presence @@ -8,5 +7,4 @@ def index ModelGroupLink.all end end - end diff --git a/app/controllers/concerns/expert_comparators.rb b/app/controllers/concerns/expert_comparators.rb index 5882f8033b..ed5266dbe8 100644 --- a/app/controllers/concerns/expert_comparators.rb +++ b/app/controllers/concerns/expert_comparators.rb @@ -3,273 +3,202 @@ module ExpertComparators extend ActiveSupport::Concern included do - private def reduce_for_radio(items, filter_value, field_config) selection_id = filter_value['selection'] - if selection_id.nil? - return items - end + return items if selection_id.nil? generic_equal_value(items, selection_id, field_config) end def reduce_for_select(items, field_id, filter_value, field_config) - value = filter_value['selection'] + return items.where(retired: nil) + else + generic_equal_value(items, value, field_config) + end + end - if value.nil? - return items - end + def reduce_for_text(items, filter_value, field_config) + if field_config['currency'] + from_string = filter_value['from'] + to_string = filter_value['to'] - case field_id - when 'retired' + if (from_string == '' || number?(from_string)) && (to_string == '' || number?(to_string)) + from = from_string.to_f if number?(from_string) + to = to_string.to_f if number?(to_string) - if value == true - return items.where.not(retired: nil) - else - return items.where(retired: nil) - end - else - generic_equal_value(items, value, field_config) - end - end + return items if from.nil? && to.nil? - def reduce_for_text(items, filter_value, field_config) - if field_config['currency'] - - from_string = filter_value['from'] - to_string = filter_value['to'] - - if (from_string == '' || number?(from_string)) \ - && (to_string == '' || number?(to_string)) - from = \ - if number?(from_string) - from_string.to_f - end - to = \ - if number?(to_string) - to_string.to_f - end - - if from.nil? && to.nil? - return items - end - - generic_between_value(items, from, to, field_config) - else - items.where('true = false') - end + generic_between_value(items, from, to, field_config) else - text = filter_value['text'] - - if text == '' - return items - end - - generic_ilike(items, text, field_config) + items.where('true = false') end - end - - def reduce_for_textarea(items, filter_value, field_config) + else text = filter_value['text'] - if text == '' - return items - end + return items if text == '' generic_ilike(items, text, field_config) end + end - def reduce_for_date(items, filter_value, field_config) - date = filter_value['date'] + def reduce_for_textarea(items, filter_value, field_config) + text = filter_value['text'] - if date == '' - return items - end + return items if text == '' - from_string = filter_value['from'] - to_string = filter_value['to'] + generic_ilike(items, text, field_config) + end - if (from_string == '' || date?(from_string)) \ - && (to_string == '' || date?(to_string)) - from = \ - if date?(from_string) - Date.parse(from_string) - end - to = \ - if date?(to_string) - Date.parse(to_string) - end - - if from.nil? && to.nil? - return items - end + def reduce_for_date(items, filter_value, field_config) + date = filter_value['date'] - generic_between_value(items, from, to, field_config) - else - items.where('true = false') - end - end + return items if date == '' - def generic_between_value(items, from, to, field_config) - attribute = field_config['attribute'] - - if attribute.is_a?(String) - check_that_item_attribute(attribute) - result = items - result = result.where("items.#{attribute} >= :from", from: from) if from - result = result.where("items.#{attribute} <= :to", to: to) if to - result - elsif attribute.is_a?(Array) - if attribute.length != 2 - throw 'Attribute length must be 2, but is: ' + attribute.to_s - end - if attribute[0] != 'properties' - throw 'We expect properties, but is: ' + attribute.to_s - end - - result = items - if from - result = result.where( - "items.properties ->> '#{attribute[1]}' >= :from", from: from) - end - if to - result = result.where( - "items.properties ->> '#{attribute[1]}' <= :to", to: to) - end - result - else - throw 'Not supported attribute: ' + attribute.to_s - end - end - - def generic_equal_value(items, value, field_config) - attribute = field_config['attribute'] + from_string = filter_value['from'] + to_string = filter_value['to'] - if attribute.is_a?(String) - check_that_item_attribute(attribute) - return items.where(attribute => value) - elsif attribute.is_a?(Array) + if (from_string == '' || date?(from_string)) && (to_string == '' || date?(to_string)) + from = Date.parse(from_string) if date?(from_string) + to = Date.parse(to_string) if date?(to_string) - if attribute.length != 2 - throw 'Attribute length must be 2, but is: ' + attribute.to_s - end - if attribute[0] != 'properties' - throw 'We expect properties, but is: ' + attribute.to_s - end + return items if from.nil? && to.nil? - items.where( - "items.properties ->> '#{attribute[1]}' = :value", - value: value) - else - throw 'Not supported attribute: ' + attribute.to_s - end + generic_between_value(items, from, to, field_config) + else + items.where('true = false') end + end - def generic_ilike(items, value, field_config) - attribute = field_config['attribute'] - - if attribute.is_a?(String) - check_that_item_attribute(attribute) - return items.where( - "items.#{attribute} ILIKE :value", - value: "%#{value}%") - elsif attribute.is_a?(Array) - - if attribute.length != 2 - throw 'Attribute length must be 2, but is: ' + attribute.to_s - end - if attribute[0] != 'properties' - throw 'We expect properties, but is: ' + attribute.to_s - end - - items.where( - "items.properties ->> '#{attribute[1]}' ILIKE :value", - value: "%#{value}%") - else - throw 'Not supported attribute: ' + attribute.to_s - end + def generic_between_value(items, from, to, field_config) + attribute = field_config['attribute'] + + if attribute.is_a?(String) + check_that_item_attribute(attribute) + result = items + result = result.where("items.#{attribute} >= :from", from: from) if from + result = result.where("items.#{attribute} <= :to", to: to) if to + result + elsif attribute.is_a?(Array) + throw 'Attribute length must be 2, but is: ' + attribute.to_s if attribute.length != 2 + throw 'We expect properties, but is: ' + attribute.to_s if attribute[0] != 'properties' + + result = items + result = result.where("items.properties ->> '#{attribute[1]}' >= :from", from: from) if from + result = result.where("items.properties ->> '#{attribute[1]}' <= :to", to: to) if to + result + else + throw 'Not supported attribute: ' + attribute.to_s end + end - def reduce_for_autocomplete(items, field_id, filter_value, field_config) - selection_id = filter_value['id'] + def generic_equal_value(items, value, field_config) + attribute = field_config['attribute'] - if selection_id.nil? - return items - end + if attribute.is_a?(String) + check_that_item_attribute(attribute) + return items.where(attribute => value) + elsif attribute.is_a?(Array) + throw 'Attribute length must be 2, but is: ' + attribute.to_s if attribute.length != 2 + throw 'We expect properties, but is: ' + attribute.to_s if attribute[0] != 'properties' - case field_id - when 'building_id' - items.joins(:room).where( - rooms: { building_id: selection_id }) - when 'inventory_pool_id' - items.joins(:inventory_pool).where( - inventory_pools: { id: selection_id }) - when 'owner_id' - items.joins(:owner).where( - inventory_pools: { id: selection_id }) - when 'supplier_id' - items.joins(:supplier).where( - suppliers: { id: selection_id }) - else - generic_equal_value(items, selection_id, field_config) - end + items.where("items.properties ->> '#{attribute[1]}' = :value", value: value) + else + throw 'Not supported attribute: ' + attribute.to_s end + end - def reduce_for_autocomplete_search(items, field_id, filter_value, field_config) - selection_id = filter_value['id'] + def generic_ilike(items, value, field_config) + attribute = field_config['attribute'] - if selection_id.nil? - return items - end + if attribute.is_a?(String) + check_that_item_attribute(attribute) + return items.where("items.#{attribute} ILIKE :value", value: "%#{value}%") + elsif attribute.is_a?(Array) + throw 'Attribute length must be 2, but is: ' + attribute.to_s if attribute.length != 2 + throw 'We expect properties, but is: ' + attribute.to_s if attribute[0] != 'properties' - case field_id - when 'model_id' - items.joins(:model).where("models.id = '#{selection_id}'") - else - generic_equal_value(items, selection_id, field_config) - end + items.where("items.properties ->> '#{attribute[1]}' ILIKE :value", value: "%#{value}%") + else + throw 'Not supported attribute: ' + attribute.to_s end + end - def valid_attributes - %w( - inventory_code - invoice_date - invoice_number - is_borrowable - is_broken - is_incomplete - is_inventory_relevant - last_check - name - note - price - responsible - retired - retired_reason - room_id - serial_number - shelf - status_note - user_name - ) + def reduce_for_autocomplete(items, field_id, filter_value, field_config) + selection_id = filter_value['id'] + + return items if selection_id.nil? + + case field_id + when 'building_id' + items.joins(:room).where(rooms: { building_id: selection_id }) + when 'inventory_pool_id' + items.joins(:inventory_pool).where(inventory_pools: { id: selection_id }) + when 'owner_id' + items.joins(:owner).where(inventory_pools: { id: selection_id }) + when 'supplier_id' + items.joins(:supplier).where(suppliers: { id: selection_id }) + else + generic_equal_value(items, selection_id, field_config) end + end - def check_that_item_attribute(attribute) - unless valid_attributes.include?(attribute) - throw 'Unexpected attribute: ' + attribute - end + def reduce_for_autocomplete_search(items, field_id, filter_value, field_config) + selection_id = filter_value['id'] + + return items if selection_id.nil? + + case field_id + when 'model_id' + items.joins(:model).where("models.id = '#{selection_id}'") + else + generic_equal_value(items, selection_id, field_config) end + end + + def valid_attributes + %w[ + inventory_code + invoice_date + invoice_number + is_borrowable + is_broken + is_incomplete + is_inventory_relevant + last_check + name + note + price + responsible + retired + retired_reason + room_id + serial_number + shelf + status_note + user_name + ] + end - def number?(string) - true if Float(string) rescue false + def check_that_item_attribute(attribute) + throw 'Unexpected attribute: ' + attribute unless valid_attributes.include?(attribute) + end + + def number?(string) + begin + true if Float(string) + rescue StandardError + false end + end - def date?(string) - true if Date.parse(string) rescue false + def date?(string) + begin + true if Date.parse(string) + rescue StandardError + false end end end -# rubocop:enable Metrics/ModuleLength diff --git a/app/controllers/concerns/expert_export.rb b/app/controllers/concerns/expert_export.rb index b77dc4bd6b..d64e9b2e6b 100644 --- a/app/controllers/concerns/expert_export.rb +++ b/app/controllers/concerns/expert_export.rb @@ -4,7 +4,6 @@ module ExpertExport include ExpertFilter included do - private def items_for_export(inventory_pool, params) @@ -13,28 +12,23 @@ def items_for_export(inventory_pool, params) end def order_items_by_models(items) - items.distinct.select('models.*, items.*').joins(:model) - .reorder('models.product').order('models.version') + items.distinct.select('models.*, items.*').joins(:model).reorder('models.product').order( + 'models.version' + ) end def header_for_export(objects_for_export) - if objects_for_export.empty? - [_('No entries found')] - else - objects_for_export.flat_map(&:keys).uniq - end + objects_for_export.empty? ? [_('No entries found')] : objects_for_export.flat_map(&:keys).uniq end def csv_export_expert(inventory_pool, params) - objects = items_for_export(inventory_pool, params) - .map(&:to_csv_array) + objects = items_for_export(inventory_pool, params).map(&:to_csv_array) header = header_for_export(objects) Export.csv_string(header, objects) end def excel_export_expert(inventory_pool, params) - objects = items_for_export(inventory_pool, params) - .map(&:to_csv_array) + objects = items_for_export(inventory_pool, params).map(&:to_csv_array) header = header_for_export(objects) Export.excel_string(header, objects, worksheet_name: _('Inventory')) end diff --git a/app/controllers/concerns/expert_filter.rb b/app/controllers/concerns/expert_filter.rb index 252a1887b9..381ab13d5f 100644 --- a/app/controllers/concerns/expert_filter.rb +++ b/app/controllers/concerns/expert_filter.rb @@ -4,13 +4,10 @@ module ExpertFilter include ExpertComparators included do - private def reduce_items(items, field_id, filter_value, field_config) - if field_id == 'attachments' - throw 'Attachments are not allowed as filter.' - end + throw 'Attachments are not allowed as filter.' if field_id == 'attachments' case field_config['type'] when 'select' @@ -20,8 +17,7 @@ def reduce_items(items, field_id, filter_value, field_config) when 'autocomplete' reduce_for_autocomplete(items, field_id, filter_value, field_config) when 'autocomplete-search' - reduce_for_autocomplete_search( - items, field_id, filter_value, field_config) + reduce_for_autocomplete_search(items, field_id, filter_value, field_config) when 'date' reduce_for_date(items, filter_value, field_config) when 'text' @@ -42,21 +38,18 @@ def inventory_items(params, inventory_pool) field_filters = JSON.parse(URI.decode(params[:field_filters])) if field_filters.length > 0 + filter_values = field_filters.map { |ff| [ff['id'], ff['value']] }.to_h - filter_values = field_filters.map do |ff| - [ff['id'], ff['value']] - end.to_h - - field_data = field_filters.map do |ff| - f = Field.find(ff['id']) - [ff['id'], f.data] - end.to_h + field_data = + field_filters.map do |ff| + f = Field.find(ff['id']) + [ff['id'], f.data] + end + .to_h field_data.each do |field_id, fd| - items = reduce_items(items, field_id, filter_values[field_id], fd) end - end end diff --git a/app/controllers/concerns/expert_view.rb b/app/controllers/concerns/expert_view.rb index 664228021c..28debf784e 100644 --- a/app/controllers/concerns/expert_view.rb +++ b/app/controllers/concerns/expert_view.rb @@ -5,22 +5,21 @@ module ExpertView include ExpertFilter included do - private def matching_items(inventory_pool, params) items = inventory_items(params, inventory_pool) - items_directly_matching = \ - items.select(:id).where(parent_id: nil) + items_directly_matching = items.select(:id).where(parent_id: nil) - parent_items_containing_matching_child = \ - items.select(:parent_id).where.not(parent_id: nil) + parent_items_containing_matching_child = items.select(:parent_id).where.not(parent_id: nil) Item.distinct.where( <<-SQL - items.id IN (#{items_directly_matching.to_sql}) - or items.id IN (#{parent_items_containing_matching_child.to_sql}) + items.id IN (#{items_directly_matching + .to_sql}) + or items.id IN (#{parent_items_containing_matching_child + .to_sql}) SQL ) end @@ -30,7 +29,7 @@ def items_for_view(inventory_pool, params) reduced = matching_items(inventory_pool, params) query = <<-SQL - + select * from @@ -48,7 +47,9 @@ def items_for_view(inventory_pool, params) from models where - models.id IN (#{reduced.select(:model_id).to_sql}) + models.id IN (#{reduced + .select(:model_id) + .to_sql}) ) union ( @@ -74,41 +75,48 @@ def items_for_view(inventory_pool, params) page_size = (params[:page_size] || 20).to_i start_index = (params[:start_index] || 0).to_i - result_models = InventoryPool.connection.exec_query( - query + " limit #{page_size + 1} offset #{start_index}").to_hash + result_models = + InventoryPool.connection.exec_query(query + " limit #{page_size + 1} offset #{start_index}") + .to_hash - items_in_model_page = reduced.where( - <<-SQL - items.model_id IN ( + items_in_model_page = + reduced.where( + <<-SQL + items.model_id IN ( select id from (#{query} limit #{page_size} offset #{start_index} ) as merged) SQL - ) - items_for_model = Item.distinct.where( - <<-SQL - items.id in ( - #{items_in_model_page.select(:id).to_sql} + ) + items_for_model = + Item.distinct.where( + <<-SQL + items.id in ( + #{items_in_model_page.select(:id) + .to_sql} ) or items.parent_id in ( - #{items_in_model_page.select(:id).to_sql} + #{items_in_model_page + .select(:id) + .to_sql} ) SQL - ) - - result_items = items_for_model.map do |item| - { - id: item.id, - model_id: item.model_id, - inventory_code: item.inventory_code, - current_location: item.current_location, - is_borrowable: item.is_borrowable, - is_broken: item.is_broken, - retired: item.retired, - parent_id: item.parent_id, - to_s: item.to_s, - is_incomplete: item.is_incomplete - } - end + ) + + result_items = + items_for_model.map do |item| + { + id: item.id, + model_id: item.model_id, + inventory_code: item.inventory_code, + current_location: item.current_location, + is_borrowable: item.is_borrowable, + is_broken: item.is_broken, + retired: item.retired, + parent_id: item.parent_id, + to_s: item.to_s, + is_incomplete: item.is_incomplete + } + end has_more = result_models.length > page_size @@ -121,7 +129,6 @@ def items_for_view(inventory_pool, params) } end # rubocop:enable Metrics/MethodLength - end end # rubocop:enable Metrics/ModuleLength diff --git a/app/controllers/concerns/file_storage.rb b/app/controllers/concerns/file_storage.rb index 824289d81b..d01c40376e 100644 --- a/app/controllers/concerns/file_storage.rb +++ b/app/controllers/concerns/file_storage.rb @@ -7,40 +7,43 @@ def store_image_with_thumbnail!(file, model) basename = File.basename(file.original_filename, extension) thumbnail_filepath = FileConversion.create_thumbnail(file.path) thumbnail_file = File.open(thumbnail_filepath) - thumbnail = model.images.build( - content: Base64.encode64(thumbnail_file.read), - filename: "#{basename}_thumb#{extension}", - size: thumbnail_file.size, - thumbnail: true, - metadata: MetadataExtractor.new(thumbnail_filepath).to_hash, - parent_id: image.id, - content_type: file.content_type - ) + thumbnail = + model.images.build( + content: Base64.encode64(thumbnail_file.read), + filename: "#{basename}_thumb#{extension}", + size: thumbnail_file.size, + thumbnail: true, + metadata: MetadataExtractor.new(thumbnail_filepath).to_hash, + parent_id: image.id, + content_type: file.content_type + ) thumbnail.save! end end def store_image!(file, model) - image = model.images.build( - content: Base64.encode64(file.read), - filename: file.original_filename, - size: file.size, - metadata: MetadataExtractor.new(file.tempfile.path).to_hash, - content_type: file.content_type - ) + image = + model.images.build( + content: Base64.encode64(file.read), + filename: file.original_filename, + size: file.size, + metadata: MetadataExtractor.new(file.tempfile.path).to_hash, + content_type: file.content_type + ) image.save! image end def store_attachment!(file, **opts) - attachment = Attachment.new( - content: Base64.encode64(file.read), - filename: file.original_filename, - size: file.size, - metadata: MetadataExtractor.new(file.tempfile.path).to_hash, - content_type: file.content_type, - **opts - ) + attachment = + Attachment.new( + content: Base64.encode64(file.read), + filename: file.original_filename, + size: file.size, + metadata: MetadataExtractor.new(file.tempfile.path).to_hash, + content_type: file.content_type, + **opts + ) attachment.save! end end diff --git a/app/controllers/concerns/main_helpers.rb b/app/controllers/concerns/main_helpers.rb index d420a5e824..83e608edbc 100644 --- a/app/controllers/concerns/main_helpers.rb +++ b/app/controllers/concerns/main_helpers.rb @@ -6,9 +6,7 @@ module MainHelpers include AuthenticatedSystem include AppSettings - helper_method(:current_inventory_pool, - :current_managed_inventory_pools, - :admin?) + helper_method(:current_inventory_pool, :current_managed_inventory_pools, :admin?) # TODO: **20 optimize lib/role_requirement and refactor to backend def current_inventory_pool @@ -28,41 +26,44 @@ def add_visitor(user) def set_gettext_locale language = - # user requested a change of locale if params[:locale] Language.where(locale_name: params[:locale]).first - # user is logged in elsif current_user current_user.language - # user is not logged in elsif session[:locale] Language.where(locale_name: session[:locale]).first - # default case else Language.default_language end + # user requested a change of locale + + # user is logged in + + # user is not logged in + + # default case unless language.nil? - # If user is logged in and he requested a locale change or he does not have - # a language yet, then update his language. if current_user and (params[:locale] or current_user.language_id.nil?) current_user.update_attributes(language_id: language.id) end session[:locale] = language.locale_name I18n.locale = language.locale_name.underscore.to_sym end + # If user is logged in and he requested a locale change or he does not have + # a language yet, then update his language. end - def set_pagination_header(paginated_active_record, - disable_total_count: false, - custom_count: nil) + def set_pagination_header(paginated_active_record, disable_total_count: false, custom_count: nil) headers['X-Pagination'] = { - total_count: total_count(paginated_active_record, - disable: disable_total_count, - custom_count: custom_count), + total_count: + total_count( + paginated_active_record, disable: disable_total_count, custom_count: custom_count + ), per_page: paginated_active_record.per_page, offset: paginated_active_record.offset - }.to_json + } + .to_json end ################################################## @@ -100,7 +101,6 @@ def total_count(paginated_active_record, disable: false, custom_count: nil) paginated_active_record.total_entries end end - end if Rails.env.production? @@ -112,5 +112,4 @@ def sign_out_path '/sign-out' end end - end diff --git a/app/controllers/concerns/procurement_access.rb b/app/controllers/concerns/procurement_access.rb index 3015c6b054..633d08fdd9 100644 --- a/app/controllers/concerns/procurement_access.rb +++ b/app/controllers/concerns/procurement_access.rb @@ -4,8 +4,9 @@ module ProcurementAccess def procurement_access? uuid = UUIDTools::UUID.parse(id) - rows = ApplicationRecord.connection.exec_query <<-SQL - SELECT ( + rows = + ApplicationRecord.connection.exec_query <<-SQL + SELECT ( EXISTS ( SELECT TRUE FROM procurement_requesters_organizations diff --git a/app/controllers/concerns/rooms_diff.rb b/app/controllers/concerns/rooms_diff.rb index 60fe00be76..dc3ff89ebc 100644 --- a/app/controllers/concerns/rooms_diff.rb +++ b/app/controllers/concerns/rooms_diff.rb @@ -1,5 +1,4 @@ module RoomsDiff - def get_rooms_diff # get_rooms_diff.html.haml end @@ -9,11 +8,8 @@ def post_rooms_diff values = [] CSV.foreach( - params[:csv_file].tempfile, - col_sep: ',', - quote_char: "\"", - headers: :first_row) do |row| - + params[:csv_file].tempfile, col_sep: ',', quote_char: '"', headers: :first_row + ) do |row| value = handle_row(row) values << value end @@ -22,16 +18,15 @@ def post_rooms_diff items_with_rooms = Item.connection.exec_query(items_with_rooms_query).to_a - invalid_items_with_rooms = items_with_rooms.select do |i| - building = i['building_name'] - room = i['room_name'] + invalid_items_with_rooms = + items_with_rooms.select do |i| + building = i['building_name'] + room = i['room_name'] - matches = values.select do |v| - v[:liegenschaft] == building && v[:raumnummer] == room - end + matches = values.select { |v| v[:liegenschaft] == building && v[:raumnummer] == room } - matches.empty? - end + matches.empty? + end # invalid_items = Item.find( # invalid_items_with_rooms.map { |i| i['item_id'] } @@ -49,33 +44,28 @@ def post_rooms_diff # disposition: \ # 'filename=room_diff.xlsx' - problematic_rooms = invalid_items_with_rooms.group_by do |i| - [i['building_name'], i['room_name']] - end.map do |k, v| - { - building_name: k[0], - room_name: k[1], - item_count: v.count, - inventory_codes: v.map { |v| v['item_inventory_code'] } - } - end + problematic_rooms = + invalid_items_with_rooms.group_by { |i| [i['building_name'], i['room_name']] }.map do |k, v| + { + building_name: k[0], + room_name: k[1], + item_count: v.count, + inventory_codes: v.map { |v| v['item_inventory_code'] } + } + end - header = ["building_name", "room_name", "item_count", "inventory_codes"] - .join(',') - - data = problematic_rooms.map do |v| - inventory_codes = if v[:inventory_codes].count > 100 - 'more than 100' - else - v[:inventory_codes].join(',') - end - [ - v[:building_name], - v[:room_name], - v[:item_count], - inventory_codes - ].map { |w| "\"#{w}\"" }.join(',') - end + header = ['building_name', 'room_name', 'item_count', 'inventory_codes'].join(',') + + data = + problematic_rooms.map do |v| + inventory_codes = + v[:inventory_codes].count > 100 ? 'more than 100' : v[:inventory_codes].join(',') + + [v[:building_name], v[:room_name], v[:item_count], inventory_codes].map do |w| + "undefined#{w}undefined" + end + .join(',') + end csv_lines = [header].concat(data) @@ -93,11 +83,8 @@ def post_rooms_diff # export = Export.excel_string( # header, problematic_rooms_csv, worksheet_name: 'Problematic Rooms') - send_data \ - csv_lines.join("\n"), - type: 'application/csv', - disposition: \ - 'filename=problematic_rooms.csv' + send_data csv_lines.join('undefined'), + type: 'application/csv', disposition: 'filename=problematic_rooms.csv' # post_rooms_diff.html.haml end @@ -114,7 +101,7 @@ def post_rooms_diff def items_with_rooms_query <<-SQL - select + select items.id as item_id, items.inventory_code as item_inventory_code, buildings.name as building_name, @@ -136,9 +123,6 @@ def handle_row(row) return nil if liegenschaft.blank? return nil if raumnummer.blank? - { - liegenschaft: liegenschaft, - raumnummer: raumnummer - } + { liegenschaft: liegenschaft, raumnummer: raumnummer } end end diff --git a/app/controllers/concerns/timeline_availability.rb b/app/controllers/concerns/timeline_availability.rb index e85b86edaa..320cca398c 100644 --- a/app/controllers/concerns/timeline_availability.rb +++ b/app/controllers/concerns/timeline_availability.rb @@ -3,12 +3,11 @@ module TimelineAvailability extend ActiveSupport::Concern included do - private def running_reservations(inventory_pool_id, model_id) query = <<-SQL - select + select reservations.* from reservations @@ -19,10 +18,15 @@ def running_reservations(inventory_pool_id, model_id) and reservations.type = 'ItemLine' and not ( status = 'unsubmitted' and - updated_at < '#{Time.now.utc - Setting.first.timeout_minutes.minutes}' + updated_at < '#{Time + .now + .utc - + Setting.first.timeout_minutes + .minutes}' ) and not ( - end_date < '#{Time.zone.today}' and + end_date < '#{Time.zone + .today}' and item_id is null ) SQL @@ -36,12 +40,14 @@ def reservation_users(reservations) return [] if user_ids.empty? query = <<-SQL - select + select users.* from users where - users.id in (#{user_ids.map { |id| "'#{id}'" }.join(',')}) + users.id in (#{user_ids + .map { |id| "'#{id}'" } + .join(',')}) SQL ActiveRecord::Base.connection.exec_query(query).to_hash @@ -53,34 +59,37 @@ def entitlement_groups_users(users) return [] if user_ids.empty? query = <<-SQL - select + select entitlement_groups_users.* from entitlement_groups_users where - user_id in (#{user_ids.map { |id| "'#{id}'" }.join(',')}) + user_id in (#{user_ids + .map { |id| "'#{id}'" } + .join(',')}) SQL ActiveRecord::Base.connection.exec_query(query).to_hash end - def entitlement_groups( - entitlements, - entitlement_groups_users, - inventory_pool_id - ) - group_ids = entitlements.map { |e| e['entitlement_group_id'] } \ - + entitlement_groups_users.map { |r| r['entitlement_group_id'] } + def entitlement_groups(entitlements, entitlement_groups_users, inventory_pool_id) + group_ids = + entitlements.map { |e| e['entitlement_group_id'] } + + entitlement_groups_users.map { |r| r['entitlement_group_id'] } return [] if group_ids.empty? query = <<-SQL - select + select entitlement_groups.* from entitlement_groups where - entitlement_groups.id in (#{group_ids.map { |id| "'#{id}'" }.join(',')}) + entitlement_groups.id in (#{group_ids + .map { |id| "'#{id}'" } + .join( + ',' + )}) and entitlement_groups.inventory_pool_id = '#{inventory_pool_id}' SQL @@ -89,7 +98,7 @@ def entitlement_groups( def entitlements(model_id) query = <<-SQL - select + select entitlements.* from entitlements @@ -102,7 +111,7 @@ def entitlements(model_id) def items(inventory_pool_id, model_id) query = <<-SQL - select + select items.* from items @@ -123,9 +132,8 @@ def timeline_availability(model_id, inventory_pool_id, is_lending_manager) entitlements = entitlements(model.id) reservation_users = reservation_users(running_reservations) entitlement_groups_users = entitlement_groups_users(reservation_users) - entitlement_groups = entitlement_groups( - entitlements, entitlement_groups_users, inventory_pool.id - ) + entitlement_groups = + entitlement_groups(entitlements, entitlement_groups_users, inventory_pool.id) items = items(inventory_pool.id, model.id) { diff --git a/app/controllers/concerns/user_session_controller.rb b/app/controllers/concerns/user_session_controller.rb index 20d5f0fe9c..c6e670b7fd 100644 --- a/app/controllers/concerns/user_session_controller.rb +++ b/app/controllers/concerns/user_session_controller.rb @@ -23,11 +23,11 @@ def delete_user_session_cookie def user_by_session if user_session_cookie = cookies[USER_SESSION_COOKIE_NAME].presence begin - session_object = CiderCi::OpenSession::Encryptor.decrypt( - secret_key_base, user_session_cookie - ).deep_symbolize_keys - @user_session = UserSession.find_by! \ - token_hash: Digest::SHA256.hexdigest(session_object[:token]) + session_object = + CiderCi::OpenSession::Encryptor.decrypt(secret_key_base, user_session_cookie) + .deep_symbolize_keys + @user_session = + UserSession.find_by! token_hash: Digest::SHA256.hexdigest(session_object[:token]) validate_lifetime!(@user_session) @user_session.delegation || @user_session.user rescue Exception => e @@ -42,10 +42,8 @@ def user_by_session def create_user_session(user) token = SecureRandom.uuid token_hash = Digest::SHA256.hexdigest token - value = CiderCi::OpenSession::Encryptor.encrypt( - secret_key_base, user_id: user.id, - token: token - ) + value = + CiderCi::OpenSession::Encryptor.encrypt(secret_key_base, user_id: user.id, token: token) cookies[USER_SESSION_COOKIE_NAME] = { expires: 10.years.from_now, value: value, @@ -61,23 +59,18 @@ def create_user_session(user) private def secret_key_base - Rails.application.secrets.secret_key_base.presence \ - || raise('secret_key_base is missing') + Rails.application.secrets.secret_key_base.presence || raise('secret_key_base is missing') end def validate_lifetime_duration!(lifetime, max_lifetime) - if lifetime > max_lifetime - raise 'The session has expired!' - end + raise 'The session has expired!' if lifetime > max_lifetime end def validate_lifetime!(user_session) lifetime = Time.zone.now - user_session.created_at - if lifetime > - (app_settings.try(:sessions_max_lifetime_secs) || (5 * 24 * 60 * 60)) + if lifetime > (app_settings.try(:sessions_max_lifetime_secs) || (5 * 24 * 60 * 60)) raise 'The session has expired!' end end - end end diff --git a/app/controllers/concerns/workaround_rails_bug25198.rb b/app/controllers/concerns/workaround_rails_bug25198.rb index e25bfa75da..47df32b5f6 100644 --- a/app/controllers/concerns/workaround_rails_bug25198.rb +++ b/app/controllers/concerns/workaround_rails_bug25198.rb @@ -6,12 +6,15 @@ def deal_with_destroy_nested_attributes!(entity_params) thumbnails = Image.where(parent_id: image_id) thumbnails.each do |thumbnail| ActiveRecord::Base.connection.exec_delete <<-SQL - DELETE FROM images WHERE id = '#{thumbnail.id}' + DELETE FROM images WHERE id = '#{thumbnail + .id}' SQL end ActiveRecord::Base.connection.exec_delete <<-SQL - DELETE FROM images WHERE id = '#{UUIDTools::UUID.parse(image_id)}' + DELETE FROM images WHERE id = '#{UUIDTools::UUID.parse( + image_id + )}' SQL images_attrs.delete(image_id) diff --git a/app/controllers/errors_controller.rb b/app/controllers/errors_controller.rb index de5280397a..a4b7f33be7 100644 --- a/app/controllers/errors_controller.rb +++ b/app/controllers/errors_controller.rb @@ -5,7 +5,6 @@ # see: # - If an exception happens from here on, a plain text fallback is used! class ErrorsController < ActionController::Base - # skip_before_action :authenticate_user! def show @@ -15,14 +14,15 @@ def show exception = request.env['action_dispatch.exception'] # these fall back to 500/'Internal Server Error' if nothing is specified: status = ActionDispatch::ExceptionWrapper.new(Rails.env, exception).status_code - message = ActionDispatch::ExceptionWrapper - .rescue_responses[exception.class.name] - .to_s.titleize + message = ActionDispatch::ExceptionWrapper.rescue_responses[exception.class.name].to_s.titleize # get some details about the exception, with cleaned up backtrace paths: - details = [flash[:error], - exception.try(:message) || message, exception.try(:cause), - exception.try(:backtrace).try(:first, 5)] + details = [ + flash[:error], + exception.try(:message) || message, + exception.try(:cause), + exception.try(:backtrace).try(:first, 5) + ] details = clean_up_trace(details.flatten.compact.uniq) get = { code: status, message: message, details: details } diff --git a/app/controllers/images_controller.rb b/app/controllers/images_controller.rb index 05025c7033..27980446c0 100644 --- a/app/controllers/images_controller.rb +++ b/app/controllers/images_controller.rb @@ -13,11 +13,8 @@ def thumbnail def send_data_or_render_not_found(image) if image and image.content - send_data \ - Base64.decode64(image.content), - filename: image.filename, - type: image.content_type, - disposition: 'inline' + send_data Base64.decode64(image.content), + filename: image.filename, type: image.content_type, disposition: 'inline' else head :not_found and return end diff --git a/app/controllers/manage/access_rights_controller.rb b/app/controllers/manage/access_rights_controller.rb index 07e72824eb..000ff89a5f 100644 --- a/app/controllers/manage/access_rights_controller.rb +++ b/app/controllers/manage/access_rights_controller.rb @@ -1,14 +1,10 @@ class Manage::AccessRightsController < Manage::ApplicationController - def index - @access_rights = if params[:user_ids] - current_inventory_pool - .access_rights - .active - .where(user_id: params[:user_ids]) - else - raise 'User ids required' - end + @access_rights = + if params[:user_ids] + current_inventory_pool.access_rights.active.where(user_id: params[:user_ids]) + else + raise 'User ids required' + end end - end diff --git a/app/controllers/manage/application_controller.rb b/app/controllers/manage/application_controller.rb index b9ee08b971..c5fdc88816 100644 --- a/app/controllers/manage/application_controller.rb +++ b/app/controllers/manage/application_controller.rb @@ -1,14 +1,14 @@ class Manage::ApplicationController < ApplicationController - layout 'manage' before_action do unless logged_in? store_location - error_response = proc do - flash[:error] = _('You are not logged in.') - head :unauthorized - end + error_response = + proc do + flash[:error] = _('You are not logged in.') + head :unauthorized + end respond_to do |format| format.html { redirect_to root_path } format.json &error_response @@ -35,8 +35,7 @@ def required_role # NOTE this method may be overridden in the sub controllers def required_manager_role open_actions = [:root] - if not open_actions.include?(action_name.to_sym) \ - and (request.post? or not request.format.json?) + if nopen_actions.include?(action_name.to_sym) and (request.post? or nrequest.format.json?) require_role :lending_manager, current_inventory_pool else require_role :group_manager, current_inventory_pool @@ -52,46 +51,42 @@ def root # if start_screen # redirect_to current_user.start_screen - last_ip_id = \ - session[:current_inventory_pool_id] \ - || current_user.latest_inventory_pool_id_before_logout - if last_ip_id - ip = current_user.inventory_pools.managed.detect { |x| x.id == last_ip_id } - end + last_ip_id = + session[:current_inventory_pool_id] || current_user.latest_inventory_pool_id_before_logout + ip = current_user.inventory_pools.managed.detect { |x| x.id == last_ip_id } if last_ip_id role_for_last_ip = current_user.access_right_for(ip).try :role if ip - if [:inventory_manager, nil].include?(role_for_last_ip) \ - and current_user.access_rights.active.where(role: :inventory_manager).exists? + if [:inventory_manager, nil].include?(role_for_last_ip) and + current_user.access_rights.active.where(role: :inventory_manager).exists? ip ||= current_user.inventory_pools.managed(:inventory_manager).first redirect_to manage_inventory_path(ip) - elsif [:lending_manager, nil].include?(role_for_last_ip) \ - and current_user.access_rights.active.where(role: :lending_manager).exists? + elsif [:lending_manager, nil].include?(role_for_last_ip) and + current_user.access_rights.active.where(role: :lending_manager).exists? ip ||= current_user.inventory_pools.managed(:lending_manager).first redirect_to manage_daily_view_path(ip) - elsif [:group_manager, nil].include?(role_for_last_ip) \ - and current_user.access_rights.active.where(role: :group_manager).exists? + elsif [:group_manager, nil].include?(role_for_last_ip) and + current_user.access_rights.active.where(role: :group_manager).exists? ip ||= current_user.inventory_pools.managed(:group_manager).first - redirect_to manage_orders_path(ip, status: [:approved, - :submitted, - :rejected]) + redirect_to manage_orders_path(ip, status: [:approved, :submitted, :rejected]) else head :bad_request end end - def maintenance - end + def maintenance; end ############################################################### protected - helper_method(:owner?, - :privileged_user?, - :super_user?, - :inventory_manager?, - :lending_manager?, - :group_manager?) + helper_method( + :owner?, + :privileged_user?, + :super_user?, + :inventory_manager?, + :lending_manager?, + :group_manager? + ) def current_inventory_pool return @current_inventory_pool if @current_inventory_pool # OPTIMIZE @@ -105,8 +100,7 @@ def current_inventory_pool end if @current_inventory_pool session[:current_inventory_pool_id] = @current_inventory_pool.id - current_user.latest_inventory_pool_id_before_logout = \ - @current_inventory_pool.id + current_user.latest_inventory_pool_id_before_logout = @current_inventory_pool.id current_user.save end @current_inventory_pool @@ -138,5 +132,4 @@ def group_manager? def owner? @item.nil? or (current_inventory_pool.id == @item.owner_id) end - end diff --git a/app/controllers/manage/availability_controller.rb b/app/controllers/manage/availability_controller.rb index dc10682601..4600b6a999 100644 --- a/app/controllers/manage/availability_controller.rb +++ b/app/controllers/manage/availability_controller.rb @@ -1,5 +1,4 @@ class Manage::AvailabilityController < Manage::ApplicationController - before_action :before_action_hook def before_action_hook @@ -11,59 +10,36 @@ def before_action_hook def index user = current_inventory_pool.users.find params[:user_id] @models.each do |model| - @availabilities.push \ - id: "#{model.id}-#{user.id}-#{current_inventory_pool.id}", - changes: \ - model - .availability_in(current_inventory_pool) - .available_total_quantities, - total_rentable: \ - model - .items - .where(inventory_pool_id: current_inventory_pool) - .unretired - .borrowable - .count, - inventory_pool_id: current_inventory_pool.id, - model_id: model.id + @availabilities.push id: "#{model.id}-#{user.id}-#{current_inventory_pool.id}", + changes: model.availability_in(current_inventory_pool).available_total_quantities, + total_rentable: + model.items.where(inventory_pool_id: current_inventory_pool).unretired.borrowable.count, + inventory_pool_id: current_inventory_pool.id, + model_id: model.id end end def in_stock @models.each do |model| - entitled_in_groups = \ - Entitlement - .joins(:entitlement_group) - .where( + entitled_in_groups = + Entitlement.joins(:entitlement_group).where( entitlement_groups: { inventory_pool_id: current_inventory_pool.id } ) - .where(model_id: model.id) - .map(&:quantity) - .reduce(&:+) + .where(model_id: model.id) + .map(&:quantity) + .reduce(&:+) entitled_in_groups ||= 0 - @availabilities.push \ - id: "#{model.id}-#{current_inventory_pool.id}", - total_rentable: \ - model - .items - .where(inventory_pool_id: current_inventory_pool) - .borrowable - .unretired - .count, - in_stock: \ - model - .items - .where(inventory_pool_id: current_inventory_pool) - .borrowable - .unretired - .in_stock - .count, - entitled_in_groups: entitled_in_groups, - inventory_pool_id: current_inventory_pool.id, - model_id: model.id + @availabilities.push id: "#{model.id}-#{current_inventory_pool.id}", + total_rentable: + model.items.where(inventory_pool_id: current_inventory_pool).borrowable.unretired.count, + in_stock: + model.items.where(inventory_pool_id: current_inventory_pool).borrowable.unretired.in_stock + .count, + entitled_in_groups: entitled_in_groups, + inventory_pool_id: current_inventory_pool.id, + model_id: model.id end render :index end - end diff --git a/app/controllers/manage/buildings_controller.rb b/app/controllers/manage/buildings_controller.rb index ac57093536..76039b52fa 100644 --- a/app/controllers/manage/buildings_controller.rb +++ b/app/controllers/manage/buildings_controller.rb @@ -1,5 +1,4 @@ class Manage::BuildingsController < Manage::ApplicationController - before_action only: [:edit, :update, :destroy] do @building = Building.find(params[:id]) end @@ -7,14 +6,10 @@ class Manage::BuildingsController < Manage::ApplicationController def index @buildings = current_inventory_pool.buildings.filter(params) - respond_to do |format| - format.html - format.json - end + respond_to(&:html) end - def edit - end + def edit; end def destroy begin @@ -25,5 +20,4 @@ def destroy end redirect_to action: :index end - end diff --git a/app/controllers/manage/categories_controller.rb b/app/controllers/manage/categories_controller.rb index 67ad145b14..0f0340a653 100644 --- a/app/controllers/manage/categories_controller.rb +++ b/app/controllers/manage/categories_controller.rb @@ -3,18 +3,7 @@ class Manage::CategoriesController < Manage::ApplicationController include WorkaroundRailsBug25198 def index - respond_to do |format| - format.html - format.json do - @categories = Category.filter(params, current_inventory_pool).to_a - if not params[:include] or not params[:include][:used?] - cat = Category.new(name: format('* %s *', _('Not categorized'))) - cat.id = UUIDTools::UUID.parse('00000000-0000-0000-0000-000000000000') - @categories << cat - end - @include_information = params[:include].keys if params[:include] - end - end + respond_to(&:html) end def new @@ -40,26 +29,23 @@ def destroy @parent = Category.find(params[:parent_id]) unless params[:parent_id].blank? if @category and @parent @parent.children.delete(@category) # if @parent.children.include?(@category) - redirect_to \ - manage_inventory_pool_category_parents_path(current_inventory_pool, - @category) + redirect_to manage_inventory_pool_category_parents_path(current_inventory_pool, @category) else if @category.models.empty? @category.destroy respond_to do |format| format.json { head :ok } format.html do - redirect_to \ - manage_categories_path(current_inventory_pool), - notice: _('%s successfully deleted') % _('Category') + redirect_to manage_categories_path(current_inventory_pool), + notice: _('%s successfully deleted') % _('Category') end end else - # TODO: 0607 ajax delete @category.errors.add(:base, _('The Category must be empty')) render action: 'show' # TODO: 24** redirect to the correct tabbed form end end + # TODO: 0607 ajax delete end def upload @@ -83,8 +69,7 @@ def update_category manage_links @category, links render status: :ok, json: { id: @category.id } else - render status: :bad_request, - text: @model.errors.full_messages.uniq.join(', ') + render status: :bad_request, text: @model.errors.full_messages.uniq.join(', ') end end @@ -92,7 +77,7 @@ def manage_links(category, links) return true if links.blank? links.each do |link| parent = @category.parents.find_by_id(links[link]['parent_id']) - if parent # parent exists already + if parent existing_link = ModelGroupLink.find_edge(parent, @category) if links[link]['_destroy'] == '1' existing_link.destroy diff --git a/app/controllers/manage/contracts_controller.rb b/app/controllers/manage/contracts_controller.rb index a9e8ad5cff..6bfa4f96bf 100644 --- a/app/controllers/manage/contracts_controller.rb +++ b/app/controllers/manage/contracts_controller.rb @@ -1,9 +1,6 @@ class Manage::ContractsController < Manage::ApplicationController - before_action do - if params[:id] - @contract = Contract.find(params[:id]) - end + @contract = Contract.find(params[:id]) if params[:id] @user = current_inventory_pool.users.find(params[:user_id]) if params[:user_id] end @@ -24,26 +21,7 @@ def required_manager_role ###################################################################### def index - respond_to do |format| - format.html - format.json do - @contracts = Contract.filter2(params, - nil, - current_inventory_pool, - paginate: false) - count = Contract.from(@contracts).count - @contracts = @contracts.default_paginate(params).order('created_at DESC') - set_pagination_header( - @contracts, - disable_total_count: ( - params[:disable_total_count] == 'true' ? true : false - ), - custom_count: ( - params[:global_contracts_search] == 'true' ? count : nil - ) - ) - end - end + respond_to(&:html) end def show @@ -66,22 +44,21 @@ def picking_list end def create - reservations = \ - @user - .reservations - .approved - .where(inventory_pool: current_inventory_pool) - .find(line_ids_param) + reservations = + @user.reservations.approved.where(inventory_pool: current_inventory_pool).find(line_ids_param) ApplicationRecord.transaction do begin - @contract = Contract.sign!(current_user, - current_inventory_pool, - @user, - reservations, - params[:purpose], - params[:note], - params[:delegated_user_id]) + @contract = + Contract.sign!( + current_user, + current_inventory_pool, + @user, + reservations, + params[:purpose], + params[:note], + params[:delegated_user_id] + ) render json: @contract.to_json rescue => e @@ -93,11 +70,9 @@ def create def swap_user order = current_inventory_pool.orders.find params[:id] user = current_inventory_pool.users.find(params[:user_id]) if params[:user_id] - delegated_user = if params[:delegated_user_id] - current_inventory_pool \ - .users - .find(params[:delegated_user_id]) - end + if params[:delegated_user_id] + delegated_user = current_inventory_pool.users.find(params[:delegated_user_id]) + end reservations = order.reservations ApplicationRecord.transaction do reservations.each do |line| @@ -105,12 +80,9 @@ def swap_user end end if reservations.all?(&:valid?) - render \ - json: \ - user \ - .orders - .find_by(status: order.status, - inventory_pool_id: current_inventory_pool).to_json + render json: + user.orders.find_by(status: order.status, inventory_pool_id: current_inventory_pool) + .to_json else errors = reservations.flat_map { |line| line.errors.full_messages } render status: :bad_request, plain: errors.uniq.join(', ') diff --git a/app/controllers/manage/entitlement_groups_controller.rb b/app/controllers/manage/entitlement_groups_controller.rb index fc89b855b7..85b6723ace 100644 --- a/app/controllers/manage/entitlement_groups_controller.rb +++ b/app/controllers/manage/entitlement_groups_controller.rb @@ -1,30 +1,34 @@ class Manage::EntitlementGroupsController < Manage::ApplicationController - before_action do params[:group_id] ||= params[:id] if params[:id] - if params[:group_id] - @group = current_inventory_pool.entitlement_groups.find(params[:group_id]) - end + @group = current_inventory_pool.entitlement_groups.find(params[:group_id]) if params[:group_id] end def map_params(params) - ActionController::Parameters.new(params[:group].map do |k, v| - case k - when 'partitions_attributes' - [:entitlements_attributes, v.map do |ep| - ActionController::Parameters.new (ep.map do |k, v| - case k - when 'group_id' - [:entitlement_group_id, v] - else - [k, v] + ActionController::Parameters.new( + params[:group].map do |k, v| + case k + when 'partitions_attributes' + [ + :entitlements_attributes, + v.map do |ep| + ActionController::Parameters.new (ep.map do |k, v| + case k + when 'group_id' + [:entitlement_group_id, v] + else + [k, v] + end + end + .to_h) end - end.to_h) - end] - else - [k, v] + ] + else + [k, v] + end end - end.to_h) + .to_h + ) end ###################################################################### @@ -36,18 +40,14 @@ def index @groups = @groups.order(:name) end - def new - end + def new; end - def edit - end + def edit; end def create @group = EntitlementGroup.new name: params[:group][:name] @group.inventory_pool = current_inventory_pool - if params[:group].key?(:users) - update_users(@group, params[:group].delete(:users)) - end + update_users(@group, params[:group].delete(:users)) if params[:group].key?(:users) mapped_params = map_params params mapped_params.permit! mapped_params.delete(:users) @@ -61,18 +61,14 @@ def create end def update - if params[:group].key?(:users) - update_users(@group, params[:group].delete(:users)) - end + update_users(@group, params[:group].delete(:users)) if params[:group].key?(:users) mapped_params = map_params params mapped_params.permit! mapped_params.delete(:users) if @group.update_attributes(mapped_params) - redirect_to manage_inventory_pool_groups_path, - flash: { success: _('%s saved') % _('Group') } + redirect_to manage_inventory_pool_groups_path, flash: { success: _('%s saved') % _('Group') } else - render plain: @group.errors.full_messages.uniq.join(', '), - status: :bad_request + render plain: @group.errors.full_messages.uniq.join(', '), status: :bad_request end end @@ -81,14 +77,12 @@ def destroy format.html do begin @group.destroy - redirect_to \ - manage_inventory_pool_groups_path, - flash: { success: _('%s successfully deleted') % _('Group') } + redirect_to manage_inventory_pool_groups_path, + flash: { success: _('%s successfully deleted') % _('Group') } rescue ActiveRecord::DeleteRestrictionError => e @group.errors.add(:base, e) - redirect_to \ - manage_inventory_pool_groups_path, - flash: { error: @group.errors.full_messages.uniq.join(', ') } + redirect_to manage_inventory_pool_groups_path, + flash: { error: @group.errors.full_messages.uniq.join(', ') } end end end @@ -108,5 +102,4 @@ def update_users(group, users) end group.users end - end diff --git a/app/controllers/manage/expert_controller.rb b/app/controllers/manage/expert_controller.rb index 69a77051e7..2aaf7dd0fe 100644 --- a/app/controllers/manage/expert_controller.rb +++ b/app/controllers/manage/expert_controller.rb @@ -19,26 +19,21 @@ def required_manager_role def index respond_to do |format| - format.json do - @inventory = items_for_view(current_inventory_pool, params) - end + format.json { @inventory = items_for_view(current_inventory_pool, params) } end end def csv_export - send_data \ - csv_export_expert(current_inventory_pool, params), - type: 'text/csv; charset=utf-8; header=present', - disposition: \ - 'attachment; ' \ - "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.csv" + send_data csv_export_expert(current_inventory_pool, params), + type: 'text/csv; charset=utf-8; header=present', + disposition: + 'attachment; ' \ + "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.csv" end def excel_export - send_data \ - excel_export_expert(current_inventory_pool, params), - type: 'application/xlsx', - disposition: \ - "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.xlsx" + send_data excel_export_expert(current_inventory_pool, params), + type: 'application/xlsx', + disposition: "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.xlsx" end end diff --git a/app/controllers/manage/fields_controller.rb b/app/controllers/manage/fields_controller.rb index c141918ef0..f9f5de3e4d 100644 --- a/app/controllers/manage/fields_controller.rb +++ b/app/controllers/manage/fields_controller.rb @@ -1,39 +1,25 @@ class Manage::FieldsController < Manage::ApplicationController - def index - @fields = Field.all.select do |f| - [params[:target_type], nil].include?(f.data['target_type']) \ - and ( - f.accessible_by?(current_user, current_inventory_pool) || - f.id == 'inventory_code' - ) \ - and not DisabledField.find_by( - inventory_pool_id: current_inventory_pool.id, - field_id: f.id - ) - end.sort_by do |f| - [Field::GROUPS_ORDER.index(f.data['group']) || 999, f.position] - end + @fields = + Field.all.select do |f| + [params[:target_type], nil].include?(f.data['target_type']) and + (f.accessible_by?(current_user, current_inventory_pool) || f.id == 'inventory_code') and + nDisabledField.find_by(inventory_pool_id: current_inventory_pool.id, field_id: f.id) + end + .sort_by { |f| [Field::GROUPS_ORDER.index(f.data['group']) || 999, f.position] } end def manage_fields @props = { - fields: Field.all.select do |f| - (f.accessible_by?(current_user, current_inventory_pool) \ - || f.id == 'inventory_code') && !f.data['required'] - # The to_json parameter is very ugly, check field.rb as_json. - end.sort_by do |f| - f.data['label'].downcase - end.map do |f| - { - label: f.data['label'], - id: f.id, - target_type: f.data['target_type'] - } - end, - disabled_fields: DisabledField.where( - inventory_pool_id: current_inventory_pool.id - ), + fields: + Field.all.select do |f| + (f.accessible_by?(current_user, current_inventory_pool) || f.id == 'inventory_code') && + !f.data['required'] + # The to_json parameter is very ugly, check field.rb as_json. + end + .sort_by { |f| f.data['label'].downcase } + .map { |f| { label: f.data['label'], id: f.id, target_type: f.data['target_type'] } }, + disabled_fields: DisabledField.where(inventory_pool_id: current_inventory_pool.id), inventory_pool_id: current_inventory_pool.id } end @@ -43,21 +29,14 @@ def disable_field inventory_pool = InventoryPool.find(params[:inventory_pool_id]) field = Field.find(params[:field_id]) - unless field.accessible_by?(current_user, inventory_pool) - throw 'Not allowed' - end + throw 'Not allowed' unless field.accessible_by?(current_user, inventory_pool) disable = params[:disable] == true - disabled_field = DisabledField.find_by( - inventory_pool_id: inventory_pool.id, - field_id: field.id - ) + disabled_field = + DisabledField.find_by(inventory_pool_id: inventory_pool.id, field_id: field.id) if !disabled_field && disable - disabled_field = DisabledField.new( - inventory_pool_id: inventory_pool.id, - field_id: field.id - ) + disabled_field = DisabledField.new(inventory_pool_id: inventory_pool.id, field_id: field.id) disabled_field.save! elsif disabled_field && !disable disabled_field.destroy diff --git a/app/controllers/manage/holidays_controller.rb b/app/controllers/manage/holidays_controller.rb index cb052a7a39..38e8894478 100644 --- a/app/controllers/manage/holidays_controller.rb +++ b/app/controllers/manage/holidays_controller.rb @@ -1,7 +1,5 @@ class Manage::HolidaysController < Manage::ApplicationController - def index @holidays = current_inventory_pool.holidays end - end diff --git a/app/controllers/manage/inventory_controller.rb b/app/controllers/manage/inventory_controller.rb index 8a9792b632..88bf097b94 100644 --- a/app/controllers/manage/inventory_controller.rb +++ b/app/controllers/manage/inventory_controller.rb @@ -1,5 +1,4 @@ class Manage::InventoryController < Manage::ApplicationController - private # NOTE overriding super controller @@ -17,49 +16,29 @@ def required_manager_role def index respond_to do |format| format.html do - session[:params] = nil if params[:filters] == 'reset' - items = Item.filter(params.clone.merge(paginate: 'false', all: 'true'), - current_inventory_pool) - responsibles = \ - InventoryPool - .distinct - .joins(:items) - .where("items.id IN (#{items.select('items.id').to_sql})") - .where( - InventoryPool - .arel_table[:id] - .eq(Item.arel_table[:inventory_pool_id]) - ) + items = + Item.filter(params.clone.merge(paginate: 'false', all: 'true'), current_inventory_pool) + responsibles = + InventoryPool.distinct.joins(:items).where( + "items.id IN (#{items.select('items.id').to_sql})" + ) + .where(InventoryPool.arel_table[:id].eq(Item.arel_table[:inventory_pool_id])) @props = { - lending_manager: - lending_manager?, - csv_import_url: - "/manage/#{current_inventory_pool.id}/inventory/csv_import", - csv_export_url: - manage_inventory_csv_export_path(current_inventory_pool), - excel_export_url: - manage_inventory_excel_export_path(current_inventory_pool), - create_model_url: - manage_new_model_path(current_inventory_pool), + lending_manager: lending_manager?, + csv_import_url: "/manage/#{current_inventory_pool.id}/inventory/csv_import", + csv_export_url: manage_inventory_csv_export_path(current_inventory_pool), + excel_export_url: manage_inventory_excel_export_path(current_inventory_pool), + create_model_url: manage_new_model_path(current_inventory_pool), create_package_url: - manage_new_item_path( - current_inventory_pool, - type: 'item', - forPackage: true - ), - create_item_url: - manage_new_item_path(current_inventory_pool), - create_option_url: - manage_new_option_path(current_inventory_pool), - create_software_url: - manage_new_model_path(current_inventory_pool, type: 'software'), - create_license_url: - manage_new_item_path(current_inventory_pool, type: 'license'), - responsibles: - responsibles + manage_new_item_path(current_inventory_pool, type: 'item', forPackage: true), + create_item_url: manage_new_item_path(current_inventory_pool), + create_option_url: manage_new_option_path(current_inventory_pool), + create_software_url: manage_new_model_path(current_inventory_pool, type: 'software'), + create_license_url: manage_new_item_path(current_inventory_pool, type: 'license'), + responsibles: responsibles } end format.json do @@ -71,65 +50,61 @@ def index end def show - @record = \ - current_inventory_pool - .items - .find_by('UPPER(inventory_code) = ?', params[:inventory_code].upcase) || \ - current_inventory_pool - .options - .find_by('UPPER(inventory_code) = ?', params[:inventory_code].upcase) - - @record ||= \ + @record = + current_inventory_pool.items.find_by( + 'UPPER(inventory_code) = ?', params[:inventory_code].upcase + ) || + current_inventory_pool.options.find_by( + 'UPPER(inventory_code) = ?', params[:inventory_code].upcase + ) + + @record ||= begin - owned_item = \ - current_inventory_pool - .own_items - .find_by('UPPER(inventory_code) = ?', params[:inventory_code].upcase) + owned_item = + current_inventory_pool.own_items.find_by( + 'UPPER(inventory_code) = ?', params[:inventory_code].upcase + ) if owned_item - { error: _('You do not have the responsibility to lend this item. ' \ - "Responsible for this item is the pool \"%s\".") % \ - owned_item.inventory_pool.name } + { + error: + _( + 'You do not have the responsibility to lend this item. ' \ + 'Responsible for this item is the pool "%s".' + ) % + owned_item.inventory_pool.name + } end end end def helper - @fields = Field.all.select do |f| - f.accessible_by? current_user, current_inventory_pool - end + @fields = Field.all.select { |f| f.accessible_by? current_user, current_inventory_pool } end def helper_react - @props = { - inventory_pool_id: current_inventory_pool.id - } + @props = { inventory_pool_id: current_inventory_pool.id } end def csv_export - send_data \ - InventoryPool.csv_export(current_inventory_pool, params), - type: 'text/csv; charset=utf-8; header=present', - disposition: \ - 'attachment; ' \ - "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.csv" + send_data InventoryPool.csv_export(current_inventory_pool, params), + type: 'text/csv; charset=utf-8; header=present', + disposition: + 'attachment; ' \ + "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.csv" end def excel_export - send_data \ - InventoryPool.excel_export(current_inventory_pool, params), - type: 'application/xlsx', - disposition: \ - "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.xlsx" + send_data InventoryPool.excel_export(current_inventory_pool, params), + type: 'application/xlsx', + disposition: "filename=#{current_inventory_pool.shortname}-#{_('Inventory')}.xlsx" end def csv_import if request.post? - items = current_inventory_pool.csv_import(current_inventory_pool, - params[:csv_file].tempfile) + items = current_inventory_pool.csv_import(current_inventory_pool, params[:csv_file].tempfile) - # &:valid? @valid_items, @invalid_items = items.partition { |item| item.errors.empty? } end + # &:valid? end - end diff --git a/app/controllers/manage/inventory_pools_controller.rb b/app/controllers/manage/inventory_pools_controller.rb index 1ef65c542c..3f3595e991 100644 --- a/app/controllers/manage/inventory_pools_controller.rb +++ b/app/controllers/manage/inventory_pools_controller.rb @@ -1,5 +1,4 @@ class Manage::InventoryPoolsController < Manage::ApplicationController - private # NOTE overriding super controller @@ -18,43 +17,35 @@ def required_manager_role public def daily(date = params[:date]) - if group_manager? and not lending_manager? - redirect_to \ - manage_orders_path(current_inventory_pool, - status: [:approved, :submitted, :rejected]), - flash: params[:flash] and return + if group_manager? and nlending_manager? + redirect_to manage_orders_path( + current_inventory_pool, status: [:approved, :submitted, :rejected] + ), + flash: params[:flash] and + return end @date = date ? Date.parse(date) : Time.zone.today if @date == Time.zone.today - # NOTE count returns a Hash because the group() in default scope - @submitted_reservations_count = \ - current_inventory_pool.orders.submitted.to_a.size - @overdue_hand_overs_count = \ + @submitted_reservations_count = current_inventory_pool.orders.submitted.to_a.size + @overdue_hand_overs_count = current_inventory_pool.visits.hand_over.where('date < ?', @date).to_a.size - @overdue_take_backs_count = \ + @overdue_take_backs_count = current_inventory_pool.visits.take_back.where('date < ?', @date).to_a.size else - if params[:tab] == 'orders' or params[:tab] == 'last_visitors' - params[:tab] = nil - end - end - @hand_overs_count = \ - current_inventory_pool.visits.hand_over.where(date: @date).to_a.size - @take_backs_count = \ - current_inventory_pool.visits.take_back.where(date: @date).to_a.size - if session[:last_visitors] - @last_visitors = session[:last_visitors].reverse.map + params[:tab] = nil if params[:tab] == 'orders' or params[:tab] == 'last_visitors' end + # NOTE count returns a Hash because the group() in default scope + + @hand_overs_count = current_inventory_pool.visits.hand_over.where(date: @date).to_a.size + @take_backs_count = current_inventory_pool.visits.take_back.where(date: @date).to_a.size + @last_visitors = session[:last_visitors].reverse.map if session[:last_visitors] end def edit @inventory_pool = current_inventory_pool - @holidays = \ - @inventory_pool - .holidays - .reject { |h| h.end_date < Time.zone.today } - .sort_by(&:start_date) + @holidays = + @inventory_pool.holidays.reject { |h| h.end_date < Time.zone.today }.sort_by(&:start_date) end # TODO: this mess needs to be untangled and split up @@ -62,9 +53,8 @@ def edit def update @inventory_pool = current_inventory_pool process_params params[:inventory_pool] - @holidays_initial = @inventory_pool.holidays.reject do |h| - h.end_date < Time.zone.today - end.sort_by(&:start_date) + @holidays_initial = + @inventory_pool.holidays.reject { |h| h.end_date < Time.zone.today }.sort_by(&:start_date) if @inventory_pool.update_attributes(params[:inventory_pool]) flash[:notice] = _('Inventory pool successfully updated') @@ -79,52 +69,47 @@ def update def workload(date = params[:date].try { |x| Date.parse(x) }) today_and_next_4_days = [date] 4.times do - today_and_next_4_days << \ + today_and_next_4_days << current_inventory_pool.next_open_date(today_and_next_4_days[-1] + 1.day) end - grouped_visits = \ - current_inventory_pool - .visits - .includes(:user) - .where('date <= ?', today_and_next_4_days.last) + grouped_visits = + current_inventory_pool.visits.includes(:user).where('date <= ?', today_and_next_4_days.last) .group_by { |x| [x.type.to_sym, x.date] } - chart_data = today_and_next_4_days.map do |day| - day_name = (day == Time.zone.today) ? _('Today') : l(day, format: '%a %d.%m') - take_back_visits_on_day = grouped_visits[[:take_back, day]] || [] - take_back_workload = \ - take_back_visits_on_day.size * 4 + take_back_visits_on_day.sum(&:quantity) - hand_over_visits_on_day = grouped_visits[[:hand_over, day]] || [] - hand_over_workload = \ - hand_over_visits_on_day.size * 4 + hand_over_visits_on_day.sum(&:quantity) - [[take_back_workload, hand_over_workload], - { name: day_name, - value: \ - "
" \ - "#{take_back_visits_on_day.size + \ - hand_over_visits_on_day.size} #{_('Visits')}" \ - '
' \ - "
" \ - "#{take_back_visits_on_day.sum(&:quantity) + \ - hand_over_visits_on_day.sum(&:quantity)} #{_('Items')}" \ - '
' }] - end + chart_data = + today_and_next_4_days.map do |day| + day_name = (day == Time.zone.today) ? _('Today') : l(day, format: '%a %d.%m') + take_back_visits_on_day = grouped_visits[[:take_back, day]] || [] + take_back_workload = + take_back_visits_on_day.size * 4 + take_back_visits_on_day.sum(&:quantity) + hand_over_visits_on_day = grouped_visits[[:hand_over, day]] || [] + hand_over_workload = + hand_over_visits_on_day.size * 4 + hand_over_visits_on_day.sum(&:quantity) + + [ + [take_back_workload, hand_over_workload], { + name: day_name, + value: + "
" \ + "#{take_back_visits_on_day.size + hand_over_visits_on_day.size} #{_('Visits')}" \ + '
' \ + "
" \ + "#{take_back_visits_on_day.sum(&:quantity) + + hand_over_visits_on_day.sum(&:quantity)} #{_('Items')}" \ + '
' + } + ] + end - respond_to do |format| - format.json { render json: { data: chart_data } } - end + respond_to { |format| format.json { render json: { data: chart_data } } } end def latest_reminder user = current_inventory_pool.users.find(params[:user_id]) - visit = \ - current_inventory_pool - .visits - .find(params[:visit_id]) + visit = current_inventory_pool.visits.find(params[:visit_id]) - @notifications = \ - user.notifications.where('created_at >= ?', visit.date).limit(10) + @notifications = user.notifications.where('created_at >= ?', visit.date).limit(10) end private @@ -137,9 +122,8 @@ def process_params(ip) def setup_holidays_for_render(holidays_attributes) if holidays_attributes params_holidays = holidays_attributes.values - @holidays = \ - @holidays_initial \ - + params_holidays.reject { |h| h[:id] }.map { |h| Holiday.new h } + @holidays = + @holidays_initial + params_holidays.reject { |h| h[:id] }.map { |h| Holiday.new h } @holidays.select(&:id).each do |holiday| if added_holiday = params_holidays.detect { |h| h[:id] == holiday.id } holiday._destroy = 1 if added_holiday.key? '_destroy' @@ -149,5 +133,4 @@ def setup_holidays_for_render(holidays_attributes) @holidays = [] end end - end diff --git a/app/controllers/manage/items_controller.rb b/app/controllers/manage/items_controller.rb index 0fe6171d85..bbcd85a23e 100644 --- a/app/controllers/manage/items_controller.rb +++ b/app/controllers/manage/items_controller.rb @@ -2,39 +2,30 @@ class Manage::ItemsController < Manage::ApplicationController include FileStorage JSON_SPEC = { - methods: [:current_location, - :unique_serial_number?], + methods: [:current_location, :unique_serial_number?], include: { - inventory_pool: {}, - model: {}, - owner: {}, - supplier: {}, - room: { include: :building } + inventory_pool: {}, model: {}, owner: {}, supplier: {}, room: { include: :building } } } def index - cip = unless params[:current_inventory_pool] == 'false' - current_inventory_pool - end + cip = current_inventory_pool unless params[:current_inventory_pool] == 'false' @items = Item.filter params, cip set_pagination_header(@items) unless params[:paginate] == 'false' end def current_locations - cip = unless params[:current_inventory_pool] == 'false' - current_inventory_pool - end + cip = current_inventory_pool unless params[:current_inventory_pool] == 'false' items = Item.filter params, cip @locations = [] items.each do |item| - @locations.push \ - id: item.id, - location: if current_inventory_pool.owner_or_responsible_for?(item) - item.current_location - else - item.inventory_pool.name - end + @locations.push id: item.id, + location: + if current_inventory_pool.owner_or_responsible_for?(item) + item.current_location + else + item.inventory_pool.name + end end end @@ -62,9 +53,7 @@ def create unless @item.errors.any? @item.attributes = item_params - if item_params[:room_id].blank? and @item.license? - @item.room = Room.general_general - end + @item.room = Room.general_general if item_params[:room_id].blank? and @item.license? saved = @item.save params[:child_items]&.each do |child_id| @@ -79,24 +68,25 @@ def create format.json do if saved if params[:copy] - render(status: :ok, - json: { id: @item.id, - redirect_url: \ - manage_copy_item_path(current_inventory_pool, - @item.id) }) + render( + status: :ok, + json: { + id: @item.id, + redirect_url: manage_copy_item_path(current_inventory_pool, @item.id) + } + ) else json = @item.as_json(JSON_SPEC).to_json render(status: :ok, json: json) end else if @item - render \ - json: { - message: item_errors_full_messages, - can_bypass_unique_serial_number_validation: \ - can_bypass_unique_serial_number_validation?(@item) - }, - status: :bad_request + render json: { + message: item_errors_full_messages, + can_bypass_unique_serial_number_validation: + can_bypass_unique_serial_number_validation?(@item) + }, + status: :bad_request else render json: {}, status: :not_found end @@ -108,7 +98,6 @@ def create def update ApplicationRecord.transaction do - fetch_item_by_id if @item @@ -117,9 +106,8 @@ def update check_fields_for_write_permissions unless @item.errors.any? - # NOTE avoid to lose already stored properties if item_params[:properties] - item_params[:properties] = \ + item_params[:properties] = @item.properties.merge item_params[:properties].to_unsafe_hash end saved = @item.update_attributes(item_params) @@ -136,28 +124,28 @@ def update end end end + # NOTE avoid to lose already stored properties respond_to do |format| format.json do if saved if params[:copy] - render(status: :ok, - json: { redirect_url: \ - manage_copy_item_path(current_inventory_pool, - @item.id) }) + render( + status: :ok, + json: { redirect_url: manage_copy_item_path(current_inventory_pool, @item.id) } + ) else json = @item.as_json(JSON_SPEC).to_json render(status: :ok, json: json) end else if @item - render \ - json: { - message: item_errors_full_messages, - can_bypass_unique_serial_number_validation: \ - can_bypass_unique_serial_number_validation?(@item) - }, - status: :bad_request + render json: { + message: item_errors_full_messages, + can_bypass_unique_serial_number_validation: + can_bypass_unique_serial_number_validation?(@item) + }, + status: :bad_request else render json: {}, status: :not_found end @@ -187,7 +175,6 @@ def copy save_path: manage_create_item_path, store_attachment_path: manage_item_store_attachment_react_path, inventory_path: manage_inventory_path, - item: @item.as_json(Manage::ItemsController::JSON_SPEC), item_type: @item.type.downcase, attachments: [] @@ -225,9 +212,7 @@ def new save_path = manage_create_item_path next_code = Item.proposed_inventory_code(current_inventory_pool) - if params[:forPackage] == 'true' - next_code = 'P-' + next_code - end + next_code = 'P-' + next_code if params[:forPackage] == 'true' @props = { next_code: next_code, lowest_code: Item.proposed_inventory_code(current_inventory_pool, :lowest), @@ -249,39 +234,40 @@ def edit parent = nil if item.parent parent = { - json: item.parent.as_json( - Manage::ItemsController::JSON_SPEC), + json: item.parent.as_json(Manage::ItemsController::JSON_SPEC), edit_path: manage_edit_item_path(current_inventory_pool, item.parent) } end children = nil if item.children && item.children.length > 0 - children = item.children.map do |child| + children = + item.children.map do |child| + { + json: child.as_json(Manage::ItemsController::JSON_SPEC), + edit_path: manage_edit_item_path(current_inventory_pool, child) + } + end + end + + attachments = + @item.attachments.map do |attachment| { - json: child.as_json( - Manage::ItemsController::JSON_SPEC), - edit_path: manage_edit_item_path(current_inventory_pool, child) + id: attachment.id, + filename: attachment.filename, + public_filename: get_attachment_path(attachment.id), + content_type: attachment.content_type } end - end - attachments = @item.attachments.map do |attachment| - { - id: attachment.id, - filename: attachment.filename, - public_filename: get_attachment_path(attachment.id), - content_type: attachment.content_type - } - end - - model_attachments = @item.model.attachments.map do |attachment| - { - id: attachment.id, - filename: attachment.filename, - public_filename: get_attachment_path(attachment.id) - } - end + model_attachments = + @item.model.attachments.map do |attachment| + { + id: attachment.id, + filename: attachment.filename, + public_filename: get_attachment_path(attachment.id) + } + end @props = { edit: true, @@ -300,16 +286,10 @@ def edit } end - Mime::Type.register( - 'application/octet-stream', :plist_binary, [], ['binary.plist']) + Mime::Type.register('application/octet-stream', :plist_binary, [], ['binary.plist']) def store_attachment_react respond_to do |format| - format.plist_binary do - store_attachment!( - params[:data], - item_id: params[:item_id] - ) - end + format.plist_binary { store_attachment!(params[:data], item_id: params[:item_id]) } end end @@ -322,20 +302,14 @@ def fetch_item_by_id def check_keys_in_hash_recursive(keys, hash) return false if keys.length == 0 if hash.key?(keys.first) - if keys.length == 1 - true - else - check_keys_in_hash_recursive(keys.from(1), hash[keys.first]) - end + keys.length == 1 ? true : check_keys_in_hash_recursive(keys.from(1), hash[keys.first]) else false end end def field_data_in_params?(field, params) - if field.id == 'attachments' - return false - end + return false if field.id == 'attachments' if field.data['attribute'].is_a? Array check_keys_in_hash_recursive(field.data['attribute'], params) else @@ -348,26 +322,21 @@ def check_fields_for_write_permissions next unless field.data['permissions'] next unless field_data_in_params?(field, item_params) next if field.editable(current_user, current_inventory_pool, @item) - @item - .errors - .add(:base, - _('You are not the owner of this item') \ - + ', ' \ - + _('therefore you may not be able to change some of these fields')) + @item.errors.add( + :base, + _('You are not the owner of this item') + ', ' + + _('therefore you may not be able to change some of these fields') + ) end end def skip_serial_number_validation_param ssnv = params.require(:item).delete(:skip_serial_number_validation) - if ssnv.try(:==, 'true') - true - else - false - end + ssnv.try(:==, 'true') ? true : false end def can_bypass_unique_serial_number_validation?(item) - not item.unique_serial_number? and item.errors.size == 1 + nitem.unique_serial_number? and item.errors.size == 1 end def item_errors_full_messages diff --git a/app/controllers/manage/mail_templates_controller.rb b/app/controllers/manage/mail_templates_controller.rb index 71533ac668..6cf7b9ea51 100644 --- a/app/controllers/manage/mail_templates_controller.rb +++ b/app/controllers/manage/mail_templates_controller.rb @@ -1,5 +1,4 @@ class Manage::MailTemplatesController < Manage::ApplicationController - private # NOTE overriding super controller @@ -10,10 +9,10 @@ def required_manager_role public def index - @template_types = \ - MailTemplate::TEMPLATE_TYPES - .to_a - .sort { |x, y| "#{x.second}#{x.first}" <=> "#{y.second}#{y.first}" } + @template_types = + MailTemplate::TEMPLATE_TYPES.to_a.sort do |x, y| + "#{x.second}#{x.first}" <=> "#{y.second}#{y.first}" + end end def edit @@ -21,10 +20,13 @@ def edit Language.unscoped.each do |language| ['text'].each do |format| - mt = MailTemplate.find_by!(inventory_pool_id: current_inventory_pool.id, - name: params[:name], - language_id: language.id, - format: format) + mt = + MailTemplate.find_by!( + inventory_pool_id: current_inventory_pool.id, + name: params[:name], + language_id: language.id, + format: format + ) @mail_templates << mt end end @@ -35,15 +37,15 @@ def update errors = [] params[:mail_templates].each do |p| - mt = MailTemplate.find_by!( - inventory_pool_id: current_inventory_pool.id, - name: p[:name], - language: Language.find_by(locale_name: p[:language]), - format: p[:format]) + mt = + MailTemplate.find_by!( + inventory_pool_id: current_inventory_pool.id, + name: p[:name], + language: Language.find_by(locale_name: p[:language]), + format: p[:format] + ) @mail_templates << mt - unless mt.update_attributes(body: p[:body]) - errors << mt.errors.full_messages - end + errors << mt.errors.full_messages unless mt.update_attributes(body: p[:body]) end if errors.empty? @@ -53,5 +55,4 @@ def update render :edit end end - end diff --git a/app/controllers/manage/mails_controller.rb b/app/controllers/manage/mails_controller.rb index 336075eb69..86746e78f4 100644 --- a/app/controllers/manage/mails_controller.rb +++ b/app/controllers/manage/mails_controller.rb @@ -1,5 +1,4 @@ class Manage::MailsController < Manage::ApplicationController - before_action do @user = User.find params[:user_id] @@ -11,31 +10,33 @@ class Manage::MailsController < Manage::ApplicationController def new if @user.email.blank? flash[:error] = _('The user does not have an email address') - # TODO + redirect else - # instead of sanitizing the user's name (see to_full_email_address - # below, we use her email address only - @to = @user.email - @from = if current_inventory_pool - to_full_email_address(current_inventory_pool.name, - (if current_inventory_pool.email.blank? - app_settings.default_email - else - current_inventory_pool.email - end)) - else - app_settings.default_email - end + @to = @user.email + @from = + if current_inventory_pool + to_full_email_address( + current_inventory_pool.name, + (if current_inventory_pool.email.blank? + app_settings.default_email + else + current_inventory_pool.email + end) + ) + else + app_settings.default_email + end @source_path = params[:source_path] end + # TODO + + # instead of sanitizing the user's name (see to_full_email_address + # below, we use her email address only end def create - Notification.user_email(params[:from], - params[:to], - params[:subject], - params[:body]) + Notification.user_email(params[:from], params[:to], params[:subject], params[:body]) flash[:notice] = _('The mail was sent') redirect_to params[:source_path] end diff --git a/app/controllers/manage/model_links_controller.rb b/app/controllers/manage/model_links_controller.rb index 59d05bde50..33bf86a805 100644 --- a/app/controllers/manage/model_links_controller.rb +++ b/app/controllers/manage/model_links_controller.rb @@ -1,7 +1,5 @@ class Manage::ModelLinksController < Manage::ApplicationController - def index @model_links = Template.find(params[:template_id]).model_links end - end diff --git a/app/controllers/manage/models_controller.rb b/app/controllers/manage/models_controller.rb index 8009aad3c8..628df30091 100644 --- a/app/controllers/manage/models_controller.rb +++ b/app/controllers/manage/models_controller.rb @@ -7,8 +7,7 @@ class Manage::ModelsController < Manage::ApplicationController # NOTE overriding super controller def required_manager_role open_actions = [:timeline, :old_timeline] - if not open_actions.include?(action_name.to_sym) \ - and (request.post? or not request.format.json?) + if nopen_actions.include?(action_name.to_sym) and (request.post? or nrequest.format.json?) super else require_role :group_manager, current_inventory_pool @@ -28,27 +27,22 @@ def show def new_old not_authorized! unless privileged_user? - @model = if params[:type] == 'package' - Model.new - else - (params[:type].try(:humanize) || 'Model').constantize.new - end + @model = + if params[:type] == 'package' + Model.new + else + (params[:type].try(:humanize) || 'Model').constantize.new + end end def new not_authorized! unless privileged_user? - manufacturers = \ - if params[:type] == 'software' - Software.manufacturers - else - Model.manufacturers - end + manufacturers = params[:type] == 'software' ? Software.manufacturers : Model.manufacturers @props = { inventory_pool_id: current_inventory_pool.id, - create_model_path: manage_create_model_path, - # TODO: #{Kernel.const_get(@model.type || 'Model').manufacturers.to_json} + create_model_path: manage_create_model_path, # TODO: #{Kernel.const_get(@model.type || 'Model').manufacturers.to_json} manufacturers: manufacturers.map(&:to_s), store_attachment_path: manage_model_store_attachment_react_path, store_image_path: manage_model_store_image_react_path, @@ -57,30 +51,17 @@ def new } end - Mime::Type.register( - 'application/octet-stream', - :plist_binary, - [], - ['binary.plist'] - ) + Mime::Type.register('application/octet-stream', :plist_binary, [], ['binary.plist']) def store_attachment_react respond_to do |format| - format.plist_binary do - store_attachment!( - params[:data], - model_id: params[:model_id] - ) - end + format.plist_binary { store_attachment!(params[:data], model_id: params[:model_id]) } end end def store_image_react respond_to do |format| format.plist_binary do - store_image_with_thumbnail!( - params[:data], - Model.find(params[:model_id]) - ) + store_image_with_thumbnail!(params[:data], Model.find(params[:model_id])) end end end @@ -89,17 +70,16 @@ def create not_authorized! unless privileged_user? created = false ApplicationRecord.transaction do - @model = case params[:model][:type] - when 'software' - Software - else - Model - end.create(product: params[:model][:product], - version: params[:model][:version]) + @model = + case params[:model][:type] + when 'software' + Software + else + Model + end + .create(product: params[:model][:product], version: params[:model][:version]) - if params[:model][:is_package] - @model.is_package = true - end + @model.is_package = true if params[:model][:is_package] save_model(@model) if !@model.persisted? or @model.errors.any? raise ActiveRecord::Rollback @@ -109,8 +89,7 @@ def create end unless created - render status: :bad_request, - plain: @model.errors.full_messages.uniq.join(', ') + render status: :bad_request, plain: @model.errors.full_messages.uniq.join(', ') else render status: :ok, json: { id: @model.id } end @@ -124,25 +103,17 @@ def edit_old def edit model = fetch_model - manufacturers = \ - if model.type == 'Software' - Software.manufacturers - else - Model.manufacturers - end + manufacturers = model.type == 'Software' ? Software.manufacturers : Model.manufacturers max_borrowable_quantity = nil if model.persisted? - max_borrowable_quantity = \ - model.borrowable_items.where( - inventory_pool_id: current_inventory_pool - ).count + max_borrowable_quantity = + model.borrowable_items.where(inventory_pool_id: current_inventory_pool).count end @props = { inventory_pool_id: current_inventory_pool.id, - create_model_path: manage_create_model_path, - # TODO: #{Kernel.const_get(@model.type || 'Model').manufacturers.to_json} + create_model_path: manage_create_model_path, # TODO: #{Kernel.const_get(@model.type || 'Model').manufacturers.to_json} manufacturers: manufacturers.map(&:to_s), store_attachment_path: manage_model_store_attachment_react_path, store_image_path: manage_model_store_image_react_path, @@ -151,52 +122,27 @@ def edit edit_data: { model: model, max_borrowable_quantity: max_borrowable_quantity, - allocations: model.entitlements.map do |e| - { - id: e.id, - group_id: e.entitlement_group_id, - quantity: e.quantity, - label: e.entitlement_group.name - } - end, - categories: model.categories.map do |c| - { - id: c.id, - label: c.name - } - end, - accessories: model.accessories.map do |a| - { - id: a.id, - name: a.name, - inventory_pool_ids: a.inventory_pool_ids - } - end, - compatibles: model.compatibles.map do |c| - { - id: c.id, - label: c.product + (c.version ? ' ' + c.version : '') - } - end, - properties: model.properties.map do |p| - { - id: p.id, - key: p.key, - value: p.value - } - end, - images: model.images.map do |i| - { - id: i.id, - filename: i.filename - } - end, - attachments: model.attachments.map do |i| - { - id: i.id, - filename: i.filename - } - end + allocations: + model.entitlements.map do |e| + { + id: e.id, + group_id: e.entitlement_group_id, + quantity: e.quantity, + label: e.entitlement_group.name + } + end, + categories: model.categories.map { |c| { id: c.id, label: c.name } }, + accessories: + model.accessories.map do |a| + { id: a.id, name: a.name, inventory_pool_ids: a.inventory_pool_ids } + end, + compatibles: + model.compatibles.map do |c| + { id: c.id, label: c.product + (c.version ? ' ' + c.version : '') } + end, + properties: model.properties.map { |p| { id: p.id, key: p.key, value: p.value } }, + images: model.images.map { |i| { id: i.id, filename: i.filename } }, + attachments: model.attachments.map { |i| { id: i.id, filename: i.filename } } } } end @@ -209,8 +155,7 @@ def update if save_model @model render status: :ok, json: { id: @model.id } else - render status: :bad_request, - plain: @model.errors.full_messages.uniq.join(', ') + render status: :bad_request, plain: @model.errors.full_messages.uniq.join(', ') end end end @@ -229,30 +174,30 @@ def upload def destroy @model = fetch_model + begin @model.destroy respond_to do |format| format.json { render json: true, status: :ok } format.html do - redirect_to \ - manage_inventory_path(current_inventory_pool), - flash: { success: _('%s successfully deleted') % _('Model') } + redirect_to manage_inventory_path(current_inventory_pool), + flash: { success: _('%s successfully deleted') % _('Model') } end end rescue => e - @model.errors.add(:base, - if e.class == ActiveRecord::DeleteRestrictionError - :restrict_with_exception_dependent_delete - else - e - end) + @model.errors.add( + :base, + if e.class == ActiveRecord::DeleteRestrictionError + :restrict_with_exception_dependent_delete + else + e + end + ) text = @model.errors.full_messages.uniq.join(', ') respond_to do |format| format.json { render plain: text, status: :forbidden } format.html do - redirect_to \ - manage_inventory_path(current_inventory_pool), - flash: { error: text } + redirect_to manage_inventory_path(current_inventory_pool), flash: { error: text } end end end @@ -260,21 +205,16 @@ def destroy def old_timeline @model = fetch_model - respond_to do |format| - format.html { render layout: false } - end + respond_to { |format| format.html { render layout: false } } end include TimelineAvailability def timeline @props = { - timeline_availability: timeline_availability( - fetch_model.id, current_inventory_pool.id, lending_manager? - ) + timeline_availability: + timeline_availability(fetch_model.id, current_inventory_pool.id, lending_manager?) } - respond_to do |format| - format.html { render layout: false } - end + respond_to { |format| format.html { render layout: false } } end private @@ -290,10 +230,8 @@ def update_packages(packages) if package['id'].blank? ApplicationRecord.transaction do item = Item.new - data = package.merge owner_id: current_inventory_pool.id, - model: @model - data[:inventory_code] ||= \ - "P-#{Item.proposed_inventory_code(current_inventory_pool)}" + data = package.merge owner_id: current_inventory_pool.id, model: @model + data[:inventory_code] ||= "P-#{Item.proposed_inventory_code(current_inventory_pool)}" item.update_attributes data children['id'].each do |child_id| child = Item.find(child_id) @@ -335,8 +273,7 @@ def update_packages(packages) private def inherit_attributes_from_package!(package, item) - item.update_attributes!(room_id: package.room_id, - shelf: package.shelf) + item.update_attributes!(room_id: package.room_id, shelf: package.shelf) end def save_model(model) @@ -356,25 +293,40 @@ def save_model(model) # TODO: # Rails bug: https://github.com/rails/rails/issues/25198 deal_with_destroy_nested_attributes!(params[:model]) ############################################################################### - p = ActionController::Parameters.new(params[:model].map do |k, v| - case k - when 'partitions_attributes' - [:entitlements_attributes, ActionController::Parameters.new(v.map do |k, v| - [k, ActionController::Parameters.new(v.map do |k, v| - case k - when 'group_id' - [:entitlement_group_id, v] - else - [k, v] - end - end.to_h)] - end.to_h)] - else - [k, v] - end - end.to_h) + p = + ActionController::Parameters.new( + params[:model].map do |k, v| + case k + when 'partitions_attributes' + [ + :entitlements_attributes, + ActionController::Parameters.new( + v.map do |k, v| + [ + k, + ActionController::Parameters.new( + v.map do |k, v| + case k + when 'group_id' + [:entitlement_group_id, v] + else + [k, v] + end + end + .to_h + ) + ] + end + .to_h + ) + ] + else + [k, v] + end + end + .to_h + ) p.permit! model.update_attributes(p) and model.save end - end diff --git a/app/controllers/manage/options_controller.rb b/app/controllers/manage/options_controller.rb index 2bb2b8553c..e8a85f0ab9 100644 --- a/app/controllers/manage/options_controller.rb +++ b/app/controllers/manage/options_controller.rb @@ -1,5 +1,4 @@ class Manage::OptionsController < Manage::ApplicationController - def index @options = Option.filter params, current_inventory_pool set_pagination_header(@options) unless params[:paginate] == 'false' @@ -34,5 +33,4 @@ def update def edit @option ||= current_inventory_pool.options.find params[:id] end - end diff --git a/app/controllers/manage/orders_controller.rb b/app/controllers/manage/orders_controller.rb index c990e96942..5142c478d2 100644 --- a/app/controllers/manage/orders_controller.rb +++ b/app/controllers/manage/orders_controller.rb @@ -1,31 +1,11 @@ class Manage::OrdersController < Manage::ApplicationController - # NOTE overriding super controller private def required_manager_role - require_role :group_manager, current_inventory_pool - end + require_role :group_manager, current_inventory_pool + end def index - respond_to do |format| - format.html - format.json do - @orders = Order.filter2(params, nil, current_inventory_pool) - - if params[:order_by_created_at_group_by_user] - @orders = @orders.select('orders.*').select( - <<-SQL - first_value(orders.created_at) - over (partition by orders.user_id order by orders.created_at desc) - as newest_created_at_per_user - SQL - ).reorder('newest_created_at_per_user desc, user_id, created_at desc') - end - - set_pagination_header @orders, disable_total_count: ( - params[:disable_total_count] == 'true' ? true : false - ) - end - end + respond_to(&:html) end def edit @@ -36,14 +16,10 @@ def edit @reservations = @order.reservations @models = @reservations.map(&:model).select { |m| m.type == 'Model' }.uniq @software = @reservations.map(&:model).select { |m| m.type == 'Software' }.uniq - @items = \ - @reservations.where.not(item_id: nil) - .map(&:item) - .select { |i| i.type == 'Item' } + @items = @reservations.where.not(item_id: nil).map(&:item).select { |i| i.type == 'Item' } @grouped_lines = @reservations.group_by { |g| [g.start_date, g.end_date] } @grouped_lines.each_pair do |k, reservations| - @grouped_lines[k] = \ - reservations.sort_by { |line| line.model.name }.group_by(&:model) + @grouped_lines[k] = reservations.sort_by { |line| line.model.name }.group_by(&:model) end @start_date = @order.min_date @end_date = @order.max_date @@ -51,6 +27,7 @@ def edit def update @order = Order.find(id_param) + begin @order.update_attributes!(purpose: purpose_param) render json: @order, status: 200 @@ -66,8 +43,7 @@ def swap_user @order.update_attributes!(user_id: user_id_param) @order.reservations.each do |reservation| reservation.update_attributes!( - user_id: user_id_param, - delegated_user_id: delegated_user_id_param + user_id: user_id_param, delegated_user_id: delegated_user_id_param ) end head :ok @@ -81,32 +57,23 @@ def approve @order = Order.find(id_param) if @order.approve(params[:comment], true, current_user, force_param) - respond_to do |format| - format.json { render json: true, status: 200 } - end + respond_to { |format| format.json { render json: true, status: 200 } } else - errors = @order.errors.full_messages.uniq.join("\n") - respond_to do |format| - format.json { render plain: errors, status: 500 } - end + errors = @order.errors.full_messages.uniq.join('undefined') + respond_to { |format| format.json { render plain: errors, status: 500 } } end end def reject @order = Order.find(id_param) - if request.post? \ - and params[:comment] \ - and @order.reject(params[:comment], current_user) + if request.post? and params[:comment] and @order.reject(params[:comment], current_user) respond_to do |format| format.json { render json: true, status: 200 } - format.html do - redirect_to manage_daily_view_path, - flash: { success: _('Order rejected') } - end + format.html { redirect_to manage_daily_view_path, flash: { success: _('Order rejected') } } end else - errors = @order.errors.full_messages.uniq.join("\n") + errors = @order.errors.full_messages.uniq.join('undefined') respond_to do |format| format.json { render plain: errors, status: 500 } format.html { render :edit } diff --git a/app/controllers/manage/partitions_controller.rb b/app/controllers/manage/partitions_controller.rb index 2b8a0e01b3..5d4fae5675 100644 --- a/app/controllers/manage/partitions_controller.rb +++ b/app/controllers/manage/partitions_controller.rb @@ -1,11 +1,10 @@ class Manage::PartitionsController < Manage::ApplicationController - def index - @partitions = \ + @partitions = Entitlement.with_generals( - model_ids: params[:model_ids], - inventory_pool_id: current_inventory_pool.id - ).map do |e| + model_ids: params[:model_ids], inventory_pool_id: current_inventory_pool.id + ) + .map do |e| e.attributes.transform_keys do |k| case k when 'entitlement_group_id' diff --git a/app/controllers/manage/reservations_controller.rb b/app/controllers/manage/reservations_controller.rb index 34ca68f413..e95fd39820 100644 --- a/app/controllers/manage/reservations_controller.rb +++ b/app/controllers/manage/reservations_controller.rb @@ -1,5 +1,4 @@ class Manage::ReservationsController < Manage::ApplicationController - private # NOTE overriding super controller @@ -25,8 +24,7 @@ def update @reservation = current_inventory_pool.reservations.find(params[:line_id]) unless @reservation.update_attributes(params[:reservation]) - render status: :bad_request, - text: @reservation.errors.full_messages.uniq.join(', ') + render status: :bad_request, text: @reservation.errors.full_messages.uniq.join(', ') end end @@ -36,21 +34,25 @@ def create begin Order.transaction do - record = if params[:model_id] - current_inventory_pool.models.find(params[:model_id]) - else - current_inventory_pool.options.find(params[:option_id]) - end + record = + if params[:model_id] + current_inventory_pool.models.find(params[:model_id]) + else + current_inventory_pool.options.find(params[:option_id]) + end # accomodate hand over and edit order order = Order.find_by(id: params[:order_id]) - @reservation = create_reservation(user, - order.try(&:id), - inventory_pool, - (order.try(&:state) or :approved), - record, - 1, - params[:start_date], - params[:end_date]) + @reservation = + create_reservation( + user, + order.try(&:id), + inventory_pool, + (order.try(&:state) or :approved), + record, + 1, + params[:start_date], + params[:end_date] + ) end rescue => e render status: :bad_request, plain: e @@ -67,29 +69,27 @@ def create_for_template template.model_links.each do |link| next unless current_inventory_pool.models.exists?(id: link.model_id) link.quantity.times do - @reservations.push \ - create_reservation(user, - order.try(&:id), - current_inventory_pool, - (order.try(&:state) or :approved), - current_inventory_pool.models.find(link.model_id), - 1, - params[:start_date], - params[:end_date]) + @reservations.push create_reservation( + user, + order.try(&:id), + current_inventory_pool, + (order.try(&:state) or :approved), + current_inventory_pool.models.find(link.model_id), + 1, + params[:start_date], + params[:end_date] + ) end end end if @reservations.empty? - render json: 'No available models for this template and inventory pool!', - status: :bad_request + render json: 'No available models for this template and inventory pool!', status: :bad_request end end def destroy begin - current_inventory_pool - .reservations - .where(id: (params[:line_id] || params[:line_ids])) + current_inventory_pool.reservations.where(id: (params[:line_id] || params[:line_ids])) .destroy_all rescue => e Rails.logger.error e @@ -98,16 +98,14 @@ def destroy end end - def change_time_range( - reservations = current_inventory_pool.reservations.find(params[:line_ids]), - start_date = params[:start_date].try { |x| Date.parse(x) }, - end_date = params[:end_date].try { |x| Date.parse(x) } || Date.tomorrow) + def change_time_range(reservations = current_inventory_pool.reservations.find( + params[:line_ids] + ), start_date = params[:start_date].try { |x| Date.parse(x) }, end_date = params[:end_date] + .try { |x| Date.parse(x) } || + Date.tomorrow) begin reservations.each do |line| - line.update_time_line \ - (start_date || line.start_date), - end_date, - current_user + line.update_time_line (start_date || line.start_date), end_date, current_user end render status: :ok, json: reservations rescue => e @@ -116,10 +114,10 @@ def change_time_range( end def assign - item = \ - current_inventory_pool - .items - .find_by('UPPER(inventory_code) = ?', params[:inventory_code].upcase) + item = + current_inventory_pool.items.find_by( + 'UPPER(inventory_code) = ?', params[:inventory_code].upcase + ) line = current_inventory_pool.reservations.approved.find params[:id] if item and line and line.model_id == item.model_id @@ -130,13 +128,15 @@ def assign unless params[:inventory_code].blank? @error = if item and line and line.model_id != item.model_id - { message: \ - _('The inventory code %s is not valid for this model') % \ - params[:inventory_code] } + { + message: + _('The inventory code %s is not valid for this model') % params[:inventory_code] + } elsif line - { message: \ - _("The item with the inventory code '%s' was not found") % \ - params[:inventory_code] } + { + message: + _("The item with the inventory code '%s' was not found") % params[:inventory_code] + } elsif item { message: _('The line was not found') } else @@ -157,19 +157,12 @@ def assign def assign_or_create @user = current_inventory_pool.users.find(params[:user_id]) - item = \ - current_inventory_pool - .items - .where('UPPER(inventory_code) = ?', code_param.upcase) - .first + item = current_inventory_pool.items.where('UPPER(inventory_code) = ?', code_param.upcase).first model = find_model(item) option = find_option unless model - line, error = create_new_line_or_assign(@user, - model, - item, - option) + line, error = create_new_line_or_assign(@user, model, item, option) if error.blank? render status: :ok, json: line @@ -202,12 +195,9 @@ def take_back end reservations.each do |l| - l.update_attributes!(returned_date: Time.zone.today, - returned_to_user_id: current_user.id) + l.update_attributes!(returned_date: Time.zone.today, returned_to_user_id: current_user.id) - if l.last_closed_reservation_of_contract? - l.contract.update_attributes!(state: :closed) - end + l.contract.update_attributes!(state: :closed) if l.last_closed_reservation_of_contract? end head :ok @@ -221,37 +211,39 @@ def take_back def swap_user user = current_inventory_pool.users.find params[:user_id] reservations = current_inventory_pool.reservations.where(id: params[:line_ids]) + begin ApplicationRecord.transaction do reservations.group_by(&:order).each_pair do |order, lines| - #################################################################### - # create a new order with the same purpose and pool, - # but with a different user in order to maintain the # integrity with the rest of the order's reservations if order - new_order = Order.create!(user: user, - inventory_pool: order.inventory_pool, - state: order.state, - purpose: order.purpose) + new_order = + Order.create!( + user: user, + inventory_pool: order.inventory_pool, + state: order.state, + purpose: order.purpose + ) end #################################################################### lines.each do |line| - delegated_user = if user.delegation? - if user.delegated_users.include? line.delegated_user - line.delegated_user - else - user.delegator_user - end - end - line.update_attributes!(user: user, - delegated_user: delegated_user, - order: new_order || nil) + delegated_user = + if user.delegation? + if user.delegated_users.include? line.delegated_user + line.delegated_user + else + user.delegator_user + end + end + line.update_attributes!( + user: user, delegated_user: delegated_user, order: new_order || nil + ) end end head :ok end - rescue + rescue StandardError head :bad_request end end @@ -260,9 +252,7 @@ def swap_model reservations = current_inventory_pool.reservations.where(id: params[:line_ids]) model = Model.find(params[:model_id]) ApplicationRecord.transaction do - reservations.each do |line| - line.update_attributes(model: model, item_id: nil) - end + reservations.each { |line| line.update_attributes(model: model, item_id: nil) } end if reservations.all?(&:valid?) render json: reservations @@ -319,35 +309,22 @@ def line_ids_param end def find_model(item) - if not code_param.blank? + if ncode_param.blank? item.model if item elsif model_group_id_param - # TODO: scope current_inventory_pool ?_param Template.find(model_group_id_param) elsif model_id_param current_inventory_pool.models.find(model_id_param) end + # TODO: scope current_inventory_pool ?_param end def find_option - if option_id_param - option = current_inventory_pool.options.find(option_id_param) - end - option || \ - current_inventory_pool - .options - .where(inventory_code: code_param) - .first + option = current_inventory_pool.options.find(option_id_param) if option_id_param + option || current_inventory_pool.options.where(inventory_code: code_param).first end - def create_reservation(user, - order_id, - inventory_pool, - status, - record, - quantity, - start_date, - end_date) + def create_reservation(user, order_id, inventory_pool, status, record, quantity, start_date, end_date) if record.is_a? Model reservation = user.item_lines.new(model: record) elsif record.is_a? Option @@ -357,8 +334,7 @@ def create_reservation(user, reservation.inventory_pool = inventory_pool reservation.status = status reservation.quantity = Integer(quantity) - reservation.start_date = \ - start_date.try { |x| Date.parse(x) } || Time.zone.today + reservation.start_date = start_date.try { |x| Date.parse(x) } || Time.zone.today reservation.end_date = end_date.try { |x| Date.parse(x) } || Date.tomorrow # NOTE we need to store because the availability reads the persisted @@ -366,7 +342,7 @@ def create_reservation(user, # then we rollback on failing conditions Reservation.transaction do reservation.save! - if (group_manager? and not lending_manager?) and not reservation.available? + if (group_manager? and nlending_manager?) and nreservation.available? raise _('Not available') else reservation @@ -380,42 +356,42 @@ def create_new_line_or_assign(user, model, item, option) line = nil ApplicationRecord.transaction do + # error if item already assigned to some approved reservation of the user + + # create new line or assign + + # try to assign for (selected)line_ids first + + # try to assign to approved reservations of the customer + + # add new line + begin - # error if item already assigned to some approved reservation of the user - if item && line = \ - user - .reservations - .where(inventory_pool: current_inventory_pool) - .approved - .find_by(item_id: item.id) - error = \ - _('%s is already assigned to this contract') % item.inventory_code - # create new line or assign + if item && + line = + user.reservations.where(inventory_pool: current_inventory_pool).approved.find_by( + item_id: item.id + ) + error = _('%s is already assigned to this contract') % item.inventory_code elsif model - # try to assign for (selected)line_ids first if line_ids_param and code_param - line = \ - user - .reservations - .where(inventory_pool: current_inventory_pool) - .approved - .where(id: line_ids_param, - model_id: item.model.id, - item_id: nil).first + line = + user.reservations.where(inventory_pool: current_inventory_pool).approved.where( + id: line_ids_param, model_id: item.model.id, item_id: nil + ) + .first end - # try to assign to approved reservations of the customer + if code_param - line ||= \ - user - .reservations - .approved - .where(inventory_pool: current_inventory_pool) - .where(model_id: model.id, item_id: nil) + line ||= + user.reservations.approved.where(inventory_pool: current_inventory_pool).where( + model_id: model.id, item_id: nil + ) .order(:id) .first end - # add new line - line ||= \ + + line ||= ItemLine.create( status: :approved, user: user, @@ -424,24 +400,18 @@ def create_new_line_or_assign(user, model, item, option) start_date: start_date_param, end_date: end_date_param ) - if model_group_id_param.nil? \ - and item \ - and line \ - and not line.update_attributes!(item: item) + if model_group_id_param.nil? and item and line and nline.update_attributes!(item: item) error = line.errors.values.join end elsif option - if line = \ - user - .reservations - .approved - .where(inventory_pool: current_inventory_pool) - .where(option_id: option.id, - start_date: start_date_param, - end_date: end_date_param).first + if line = + user.reservations.approved.where(inventory_pool: current_inventory_pool).where( + option_id: option.id, start_date: start_date_param, end_date: end_date_param + ) + .first line.quantity += quantity_param line.save - elsif not line = \ + elsif nline = OptionLine.create( user: user, status: :approved, @@ -456,15 +426,15 @@ def create_new_line_or_assign(user, model, item, option) else error = if code - _('A model for the Inventory Code / ' \ - "Serial Number '%s' was not found") % \ - code_param + _( + 'A model for the Inventory Code / ' \ + "Serial Number '%s' was not found" + ) % + code_param elsif model_id_param - _("A model with the ID '%s' was not found") % \ - model_id_param + _("A model with the ID '%s' was not found") % model_id_param elsif model_group_id_param - _("A template with the ID '%s' was not found") % \ - model_group_id_param + _("A template with the ID '%s' was not found") % model_group_id_param end end rescue => e diff --git a/app/controllers/manage/rooms_controller.rb b/app/controllers/manage/rooms_controller.rb index cca7ac5bad..9ac9597ce8 100644 --- a/app/controllers/manage/rooms_controller.rb +++ b/app/controllers/manage/rooms_controller.rb @@ -1,14 +1,10 @@ class Manage::RoomsController < Manage::ApplicationController - include RoomsDiff def index - @rooms = \ - Room.where(building_id: building_id_param).order(:name) + @rooms = Room.where(building_id: building_id_param).order(:name) - respond_to do |format| - format.json - end + respond_to(&:json) end private @@ -16,5 +12,4 @@ def index def building_id_param params.require(:building_id) end - end diff --git a/app/controllers/manage/search_controller.rb b/app/controllers/manage/search_controller.rb index f879353a0e..7934f3cbbe 100644 --- a/app/controllers/manage/search_controller.rb +++ b/app/controllers/manage/search_controller.rb @@ -1,24 +1,13 @@ class Manage::SearchController < Manage::ApplicationController - before_action except: [:search] do - @search_term = CGI::unescape params[:search_term] + @search_term = CGI.unescape params[:search_term] end def search - search_term = CGI::escape params[:search_term] - redirect_to manage_search_results_path(current_inventory_pool, - search_term: search_term) + search_term = CGI.escape params[:search_term] + redirect_to manage_search_results_path(current_inventory_pool, search_term: search_term) end - [:results, - :models, - :software, - :items, - :licenses, - :users, - :contracts, - :orders, - :options] - .each { |action| define_method(action) {} } - + [:results, :models, :software, :items, :licenses, :users, :contracts, :orders, :options] + .each { |action| define_method(action) { } } end diff --git a/app/controllers/manage/suppliers_controller.rb b/app/controllers/manage/suppliers_controller.rb index c84be4f26b..5c7169199a 100644 --- a/app/controllers/manage/suppliers_controller.rb +++ b/app/controllers/manage/suppliers_controller.rb @@ -1,5 +1,4 @@ class Manage::SuppliersController < Manage::ApplicationController - before_action only: [:show, :update, :destroy] do @supplier = Supplier.find(params[:id]) end @@ -9,10 +8,8 @@ def index end def show - @items = \ - @supplier - .items - .where("'#{current_inventory_pool.id}' IN (inventory_pool_id, owner_id)") + @items = + @supplier.items.where("'#{current_inventory_pool.id}' IN (inventory_pool_id, owner_id)") .includes(:model, :inventory_pool) end @@ -25,5 +22,4 @@ def destroy end redirect_to action: :index end - end diff --git a/app/controllers/manage/templates_controller.rb b/app/controllers/manage/templates_controller.rb index 52af738276..cc06ec052a 100644 --- a/app/controllers/manage/templates_controller.rb +++ b/app/controllers/manage/templates_controller.rb @@ -1,8 +1,5 @@ class Manage::TemplatesController < Manage::ApplicationController - - before_action do - @template = current_inventory_pool.templates.find(params[:id]) if params[:id] - end + before_action { @template = current_inventory_pool.templates.find(params[:id]) if params[:id] } ###################################################################### @@ -10,9 +7,11 @@ def index if request.format.html? @templates = current_inventory_pool.templates unless @templates.select { |t| !t.accomplishable? }.empty? - @unaccomplishable_templates_error = \ - _('The highlighted entries are not accomplishable ' \ - 'for the intended quantity.') + @unaccomplishable_templates_error = + _( + 'The highlighted entries are not accomplishable ' \ + 'for the intended quantity.' + ) end else @templates = Template.filter params, current_inventory_pool @@ -25,8 +24,8 @@ def new end def create + # Is the 'template' variable really never used? begin - # Is the 'template' variable really never used? current_inventory_pool.templates.create! params[:template] flash[:notice] = _('%s created successfully') % _('Template') redirect_to action: :index @@ -36,8 +35,7 @@ def create end end - def edit - end + def edit; end def update begin @@ -54,14 +52,11 @@ def destroy respond_to do |format| format.html do if @template.destroy and @template.destroyed? - redirect_to manage_templates_path, - notice: _('%s successfully deleted') % _('Template') + redirect_to manage_templates_path, notice: _('%s successfully deleted') % _('Template') else - redirect_to manage_templates_path, - error: @template.errors.full_messages.uniq.join(', ') + redirect_to manage_templates_path, error: @template.errors.full_messages.uniq.join(', ') end end end end - end diff --git a/app/controllers/manage/users_controller.rb b/app/controllers/manage/users_controller.rb index cadfd92cd7..e0c31e26e0 100644 --- a/app/controllers/manage/users_controller.rb +++ b/app/controllers/manage/users_controller.rb @@ -1,31 +1,25 @@ class Manage::UsersController < Manage::ApplicationController - before_action do not_authorized! unless group_manager? if params[:access_right] - @ip_id = if params[:access_right][:inventory_pool_id] and admin? - params[:access_right][:inventory_pool_id] - else - current_inventory_pool.id - end + @ip_id = + if params[:access_right][:inventory_pool_id] and admin? + params[:access_right][:inventory_pool_id] + else + current_inventory_pool.id + end end end - before_action only: [:edit, - :update, - :destroy, - :set_start_screen, - :hand_over, - :take_back] do + before_action only: [:edit, :update, :destroy, :set_start_screen, :hand_over, :take_back] do # @user = current_inventory_pool.users.find(params[:id]) @user = User.find(params[:id]) end before_action only: [:hand_over, :take_back] do unless @user.access_right_for(current_inventory_pool) - redirect_to manage_inventory_pool_users_path, - flash: { error: _('No access') } + redirect_to manage_inventory_pool_users_path, flash: { error: _('No access') } end end @@ -34,8 +28,7 @@ class Manage::UsersController < Manage::ApplicationController # NOTE overriding super controller def required_manager_role open_actions = [:hand_over] - if not open_actions.include?(action_name.to_sym) \ - and (request.post? or not request.format.json?) + if nopen_actions.include?(action_name.to_sym) and (request.post? or nrequest.format.json?) super else require_role :group_manager, current_inventory_pool @@ -56,21 +49,16 @@ def new @delegation_type = true if params[:type] == 'delegation' @user = User.new @accessible_roles = get_accessible_roles_for_current_user - @access_right = \ - @user.access_rights.new inventory_pool_id: current_inventory_pool.id, - role: :customer + @access_right = + @user.access_rights.new inventory_pool_id: current_inventory_pool.id, role: :customer end def create groups = params[:user].delete(:groups) if params[:user].key?(:groups) - if users = params[:user].delete(:users) - delegated_user_ids = users.map { |h| h['id'] } - end + delegated_user_ids = users.map { |h| h['id'] } if users = params[:user].delete(:users) @user = User.new(params[:user]) - if groups - @user.entitlement_groups = groups.map { |g| EntitlementGroup.find g['id'] } - end + @user.entitlement_groups = groups.map { |g| EntitlementGroup.find g['id'] } if groups begin User.transaction do @@ -83,20 +71,14 @@ def create raise 'password mismatch' if password != password_confirmation if password.present? AuthenticationSystemUser.create!( - user: @user, - authentication_system_id: 'password', - data: get_pw_hash(password) + user: @user, authentication_system_id: 'password', data: get_pw_hash(password) ) end end unless params[:access_right][:role].to_sym == :no_access - ar = \ - @user - .access_rights - .find_or_initialize_by(inventory_pool: @current_inventory_pool) - ar.update_attributes!(role: params[:access_right][:role], - deleted_at: nil) + ar = @user.access_rights.find_or_initialize_by(inventory_pool: @current_inventory_pool) + ar.update_attributes!(role: params[:access_right][:role], deleted_at: nil) end respond_to do |format| @@ -146,18 +128,16 @@ def update if password.present? password_confirmation = params[:db_auth][:password_confirmation] raise 'password mismatch' if password != password_confirmation - dbauth = AuthenticationSystemUser.find_or_create_by!( - user_id: @user.id, - authentication_system_id: 'password' - ) + dbauth = + AuthenticationSystemUser.find_or_create_by!( + user_id: @user.id, authentication_system_id: 'password' + ) dbauth.update_attributes!(data: get_pw_hash(password)) end end - @access_right = \ - AccessRight.find_or_initialize_by(user_id: @user.id, - inventory_pool_id: @ip_id) - unless @access_right.new_record? \ - and params[:access_right][:role].to_sym == :no_access + @access_right = + AccessRight.find_or_initialize_by(user_id: @user.id, inventory_pool_id: @ip_id) + unless @access_right.new_record? and params[:access_right][:role].to_sym == :no_access @access_right.update_attributes! params[:access_right] end @@ -166,9 +146,7 @@ def update flash[:notice] = _('User details were updated successfully.') redirect_to manage_inventory_pool_users_path end - format.json do - render plain: _('User details were updated successfully.') - end + format.json { render plain: _('User details were updated successfully.') } end end rescue => e @@ -198,14 +176,16 @@ def get_accessible_roles_for_current_user accessible_roles = [[_('No access'), :no_access], [_('Customer'), :customer]] unless @delegation_type accessible_roles += - if @current_user.is_admin \ - or @current_user.has_role? :inventory_manager, @current_inventory_pool - [[_('Group manager'), :group_manager], - [_('Lending manager'), :lending_manager], - [_('Inventory manager'), :inventory_manager]] + if @current_user.is_admin or + @current_user.has_role? :inventory_manager, @current_inventory_pool + [ + [_('Group manager'), :group_manager], [_('Lending manager'), :lending_manager], [ + _('Inventory manager'), + :inventory_manager + ] + ] elsif @current_user.has_role? :lending_manager, @current_inventory_pool - [[_('Group manager'), :group_manager], - [_('Lending manager'), :lending_manager]] + [[_('Group manager'), :group_manager], [_('Lending manager'), :lending_manager]] else [] end @@ -215,49 +195,30 @@ def get_accessible_roles_for_current_user def hand_over set_shared_visit_variables 0 do - @reservations = \ - @user - .reservations - .where(status: :approved, inventory_pool: current_inventory_pool) + @reservations = + @user.reservations.where(status: :approved, inventory_pool: current_inventory_pool) @orders = @reservations.map(&:order) @models = @reservations.map(&:model).select { |m| m.type == 'Model' }.uniq - @software = \ - @reservations.map(&:model).select { |m| m.type == 'Software' }.uniq - @options = \ - @reservations.where.not(option_id: nil).map(&:option).uniq - @items = \ - @reservations.where.not(item_id: nil) - .map(&:item) - .select { |i| i.type == 'Item' } - @licenses = \ - @reservations.where.not(item_id: nil) - .map(&:item) - .select { |i| i.type == 'License' } + @software = @reservations.map(&:model).select { |m| m.type == 'Software' }.uniq + @options = @reservations.where.not(option_id: nil).map(&:option).uniq + @items = @reservations.where.not(item_id: nil).map(&:item).select { |i| i.type == 'Item' } + @licenses = + @reservations.where.not(item_id: nil).map(&:item).select { |i| i.type == 'License' } end - @start_date, @end_date = \ - @grouped_lines.keys.sort.first || [Time.zone.today, Time.zone.today] + @start_date, @end_date = @grouped_lines.keys.sort.first || [Time.zone.today, Time.zone.today] add_visitor(@user) end def take_back set_shared_visit_variables 1 do - @reservations = \ - @user - .reservations - .signed - .where(inventory_pool_id: current_inventory_pool) - .includes([:model, :item, :order]) - @contracts = \ - @user - .contracts - .open - .where(inventory_pool_id: current_inventory_pool) + @reservations = + @user.reservations.signed.where(inventory_pool_id: current_inventory_pool).includes( + [:model, :item, :order] + ) + @contracts = @user.contracts.open.where(inventory_pool_id: current_inventory_pool) @models = @reservations.map(&:model).uniq - @options = \ - @reservations.where.not(option_id: nil).map(&:option).uniq - @items = \ - @reservations.where.not(item_id: nil) - .map(&:item) + @options = @reservations.where.not(option_id: nil).map(&:option).uniq + @items = @reservations.where.not(item_id: nil).map(&:item) end @start_date = @reservations.map(&:start_date).min || Time.zone.today @end_date = @reservations.map(&:end_date).max || Time.zone.today @@ -272,19 +233,14 @@ def set_shared_visit_variables(date_index) yield @grouped_lines = @reservations.group_by { |g| [g.start_date, g.end_date] } @grouped_lines.each_pair do |k, reservations| - @grouped_lines[k] = \ - reservations.sort_by { |line| [line.model.name, line.id] } + @grouped_lines[k] = reservations.sort_by { |line| [line.model.name, line.id] } end - @count_today = \ - @grouped_lines.keys.count { |range| range[date_index] == Time.zone.today } - @count_future = \ - @grouped_lines.keys.count { |range| range[date_index] > Time.zone.today } - @count_overdue = \ - @grouped_lines.keys.count { |range| range[date_index] < Time.zone.today } + @count_today = @grouped_lines.keys.count { |range| range[date_index] == Time.zone.today } + @count_future = @grouped_lines.keys.count { |range| range[date_index] > Time.zone.today } + @count_overdue = @grouped_lines.keys.count { |range| range[date_index] < Time.zone.today } @grouped_lines_by_date = [] @grouped_lines.each_pair do |range, reservations| - @grouped_lines_by_date - .push(date: range[date_index], grouped_lines: { range => reservations }) + @grouped_lines_by_date.push(date: range[date_index], grouped_lines: { range => reservations }) end @grouped_lines_by_date = @grouped_lines_by_date.sort_by { |g| g[:date] } end @@ -297,12 +253,19 @@ def get_delegated_users_ids(params) end def get_pw_hash(password) - ActiveRecord::Base.connection.execute(<<-SQL.strip_heredoc) - SELECT crypt( - #{ActiveRecord::Base.sanitize(password)}, + ActiveRecord::Base.connection.execute( + <<-SQL + SELECT crypt( + #{ActiveRecord::Base.sanitize( + password + )}, gen_salt('bf',10) ) AS pw_hash SQL - .first['pw_hash'] + .strip_heredoc + ) + .first[ + 'pw_hash' + ] end end diff --git a/app/controllers/manage/visits_controller.rb b/app/controllers/manage/visits_controller.rb index 68d2d1a551..47af4cd913 100644 --- a/app/controllers/manage/visits_controller.rb +++ b/app/controllers/manage/visits_controller.rb @@ -1,29 +1,26 @@ class Manage::VisitsController < Manage::ApplicationController - def index respond_to do |format| format.html do - @props = { inventory_pool_id: current_inventory_pool.id, - start_date: params[:start_date], - end_date: params[:end_date], - tab: params[:tab] } + @props = { + inventory_pool_id: current_inventory_pool.id, + start_date: params[:start_date], + end_date: params[:end_date], + tab: params[:tab] + } end format.json do visits = Visit.filter2(params, current_inventory_pool) if params[:paginate] == 'false' - visits = \ - current_inventory_pool - .visits - .filter2(params) - .includes(user: :notifications) - .where(type: type_param) - .where(is_approved: true) - .offset(offset_param) - .limit(limit_param) - - visits_json = visits.as_json( - include: [{ user: { methods: :image_url } }, :reservations] - ) + visits = + current_inventory_pool.visits.filter2(params).includes(user: :notifications).where( + type: type_param + ) + .where(is_approved: true) + .offset(offset_param) + .limit(limit_param) + + visits_json = visits.as_json(include: [{ user: { methods: :image_url } }, :reservations]) visits_json.each do |v| user = User.find(v['user_id']) @@ -35,58 +32,47 @@ def index v['user']['extended_info'] = nil v['reservations'].each do |r| - object = \ - Model.find_by_id(r['model_id']) || - Option.find_by_id(r['option_id']) + object = Model.find_by_id(r['model_id']) || Option.find_by_id(r['option_id']) r['model_name'] = object.name end - v['notifications'] = \ - user.notifications.where('created_at >= ?', v['date']).limit(10) + v['notifications'] = user.notifications.where('created_at >= ?', v['date']).limit(10) end render json: visits_json and return else @visits = visits.default_paginate(params) - # NOTE: `total_entries` from will_paginate gem does not - # work with our custom `Visit.default_scope`, thus we - # use our own `Visit.total_count_for_paginate` + headers['X-Pagination'] = { total_count: visits.total_count_for_paginate, per_page: @visits.per_page, offset: @visits.offset - }.to_json + } + .to_json end + # NOTE: `total_entries` from will_paginate gem does not + # work with our custom `Visit.default_scope`, thus we + # use our own `Visit.total_count_for_paginate` end end end def destroy - visit = \ - current_inventory_pool - .visits - .hand_over - .find(params[:visit_id]) - - ActiveRecord::Base.transaction do - visit.reservations.each(&:destroy!) - end + visit = current_inventory_pool.visits.hand_over.find(params[:visit_id]) + + ActiveRecord::Base.transaction { visit.reservations.each(&:destroy!) } head :ok end def remind - visit = \ - current_inventory_pool - .visits - .take_back - .find(params[:visit_id]) + visit = current_inventory_pool.visits.take_back.find(params[:visit_id]) # TODO: dry with User.remind_and_suspend_all - grouped_reservations = visit.reservations.group_by do |vl| - { inventory_pool: vl.inventory_pool, - user_id: (vl.delegated_user_id || vl.user_id) } - end + grouped_reservations = + visit.reservations.group_by do |vl| + { inventory_pool: vl.inventory_pool, user_id: (vl.delegated_user_id || vl.user_id) } + end grouped_reservations.each_pair do |k, reservations| user = User.find(k[:user_id]) user.remind(reservations) @@ -110,5 +96,4 @@ def limit_param p = params.require(:limit) p.match?(/\d*/) ? p : raise(ActionController::UnpermittedParameters) end - end diff --git a/app/controllers/manage/workdays_controller.rb b/app/controllers/manage/workdays_controller.rb index 742c5b1edb..b43f68dad4 100644 --- a/app/controllers/manage/workdays_controller.rb +++ b/app/controllers/manage/workdays_controller.rb @@ -1,5 +1,4 @@ class Manage::WorkdaysController < Manage::ApplicationController - before_action do @workday = current_inventory_pool.workday @holidays = current_inventory_pool.holidays.future @@ -9,5 +8,4 @@ class Manage::WorkdaysController < Manage::ApplicationController def index @workday = current_inventory_pool.workday end - end diff --git a/app/controllers/models_controller.rb b/app/controllers/models_controller.rb index 44ae80db23..8c93f5689f 100644 --- a/app/controllers/models_controller.rb +++ b/app/controllers/models_controller.rb @@ -1,8 +1,5 @@ class ModelsController < ApplicationController - - before_action do - require_role :customer - end + before_action { require_role :customer } def image image = Model.find(id_param).image(params[:offset]) @@ -12,11 +9,8 @@ def image elsif image redirect_to get_image_path(image.id) else - empty_gif_pixel = \ - "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==\n" - send_data(Base64.decode64(empty_gif_pixel), - type: 'image/gif', - disposition: 'inline') + empty_gif_pixel = 'R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==undefined' + send_data(Base64.decode64(empty_gif_pixel), type: 'image/gif', disposition: 'inline') end end @@ -25,5 +19,4 @@ def image def id_param params.require(:id) end - end diff --git a/app/controllers/properties_controller.rb b/app/controllers/properties_controller.rb index f300d11410..d3f1d0ab3a 100644 --- a/app/controllers/properties_controller.rb +++ b/app/controllers/properties_controller.rb @@ -1,7 +1,5 @@ class PropertiesController < ApplicationController - def index @properties = Property.where(model_id: params[:model_ids]) end - end diff --git a/app/controllers/release_info_controller.rb b/app/controllers/release_info_controller.rb index 6ccd5bf6cc..fc4bfbe60d 100644 --- a/app/controllers/release_info_controller.rb +++ b/app/controllers/release_info_controller.rb @@ -6,5 +6,4 @@ class ReleaseInfoController < ActionController::Base def index @get = RELEASE_INFO end - end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 90bf7b4dc2..51f765274e 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,23 +1,20 @@ class SessionsController < ApplicationController - def authenticate(id = params[:id]) @selected_system = AuthenticationSystem.active_systems.find(id) if id @selected_system ||= AuthenticationSystem.default_system.first sys = "Authenticator::#{@selected_system.class_name}Controller".constantize.new redirect_to sys.login_form_path - rescue + rescue StandardError logger.error($!) unless AuthenticationSystem.default_system.first raise 'No default authentication system selected.' end raise 'No system selected.' unless @selected_system - raise 'Class not found or missing login_form_path method: ' \ - + @selected_system.class_name + raise 'Class not found or missing login_form_path method: ' + @selected_system.class_name end def authenticate_as - if Rails.env.development? \ - and self.current_user = User.find(params[:id]) + if Rails.env.development? and self.current_user = User.find(params[:id]) redirect_back_or_default('/') flash[:notice] = _('Logged in successfully') end @@ -26,8 +23,7 @@ def authenticate_as def destroy # store last inventory pool to the settings column if current_user - current_user.latest_inventory_pool_id_before_logout = \ - session[:current_inventory_pool_id] + current_user.latest_inventory_pool_id_before_logout = session[:current_inventory_pool_id] current_user.save end # delete cookie and reset session diff --git a/app/controllers/styleguide_controller.rb b/app/controllers/styleguide_controller.rb index 80854cf6ca..cfe5ca4d7c 100644 --- a/app/controllers/styleguide_controller.rb +++ b/app/controllers/styleguide_controller.rb @@ -1,14 +1,14 @@ class StyleguideController < ActionController::Base - before_action do @sections = {} - Dir.entries(Rails.root.join('app', 'views', 'styleguide')) - .reject { |p| p.match(/[_\.]/) }.each do |section| - @sections[section] = \ - Dir.entries(Rails.root.join('app', 'views', 'styleguide', section)) - .reject { |p| p.match(/^_/).nil? }.map { |p| p[/(?<=_)\w*?(?=\.)/] } + Dir.entries(Rails.root.join('app', 'views', 'styleguide')).reject { |p| p.match(/[_\.]/) } + .each do |section| + @sections[section] = + Dir.entries(Rails.root.join('app', 'views', 'styleguide', section)).reject do |p| + p.match(/^_/).nil? + end + .map { |p| p[/(?<=_)\w*?(?=\.)/] } end @current_section = (params[:section] ? params[:section] : 'general') end - end diff --git a/app/helpers/barcode_helper.rb b/app/helpers/barcode_helper.rb index 831989b122..7befe79146 100644 --- a/app/helpers/barcode_helper.rb +++ b/app/helpers/barcode_helper.rb @@ -1,14 +1,9 @@ module BarcodeHelper - def barcode_for_contract(contract, height = 25) require 'barby' require 'barby/barcode/code_128' require 'barby/outputter/png_outputter' - png = \ - Barby::Code128B - .new(" C #{contract.compact_id}") - .to_png(height: Integer(height)) + png = Barby::Code128B.new(" C #{contract.compact_id}").to_png(height: Integer(height)) "data:image/png;base64,#{Base64.encode64(png)}" end - end diff --git a/app/helpers/date_helper.rb b/app/helpers/date_helper.rb index 4f815e70b8..fe47807cb9 100644 --- a/app/helpers/date_helper.rb +++ b/app/helpers/date_helper.rb @@ -1,8 +1,6 @@ module DateHelper - def interval(start_date, end_date) interval = Integer(end_date - start_date).abs + 1 pluralize(interval, _('Day'), _('Days')) end - end diff --git a/app/helpers/linkify_helper.rb b/app/helpers/linkify_helper.rb index b74f4b6f4e..ef8461ef72 100644 --- a/app/helpers/linkify_helper.rb +++ b/app/helpers/linkify_helper.rb @@ -1,9 +1,7 @@ module LinkifyHelper - def linkify_text(string) require 'rinku' tag_attrs = tag_options(target: :_blank, rel: :noopener, class: :autolinkified) Rinku.auto_link(string, :all, tag_attrs).html_safe end - end diff --git a/app/models/access_right.rb b/app/models/access_right.rb index 469483493e..d0381e73ee 100644 --- a/app/models/access_right.rb +++ b/app/models/access_right.rb @@ -7,10 +7,7 @@ class AccessRight < ApplicationRecord #################################################################### # NOTE the elements have to be sorted in ascending order - ROLES_HIERARCHY = [:customer, - :group_manager, - :lending_manager, - :inventory_manager] + ROLES_HIERARCHY = [:customer, :group_manager, :lending_manager, :inventory_manager] AVAILABLE_ROLES = ROLES_HIERARCHY AUTOMATIC_SUSPENSION_DATE = Date.new(2099, 1, 1) @@ -26,9 +23,9 @@ def role=(v) when :customer, :group_manager, :lending_manager, :inventory_manager write_attribute(:role, v) when :no_access - # keep the existing role, just flag as deleted self.deleted_at = Time.zone.today end + # keep the existing role, just flag as deleted # assigning a new role, reactivate (ensure is not deleted) if role_changed? @@ -46,17 +43,14 @@ def role=(v) validates_uniqueness_of :inventory_pool_id, scope: :user_id validate do errors.add(:base, _('Inventory Pool is missing')) if inventory_pool.nil? - if deleted_at - check_for_existing_reservations - end + check_for_existing_reservations if deleted_at end before_validation(on: :create) do if user unless user.access_rights.active.empty? if inventory_pool - old_ar = \ - user.access_rights.active.find_by(inventory_pool_id: inventory_pool.id) + old_ar = user.access_rights.active.find_by(inventory_pool_id: inventory_pool.id) end user.access_rights.delete(old_ar) if old_ar end @@ -70,22 +64,24 @@ def role=(v) #################################################################### - scope :active, (lambda do - joins(<<-SQL) - LEFT JOIN inventory_pools + scope :active, + (lambda do + joins( + <<-SQL + LEFT JOIN inventory_pools ON inventory_pools.id = access_rights.inventory_pool_id SQL - .where(<<-SQL) - access_rights.deleted_at IS NULL + ) + .where( + <<-SQL + access_rights.deleted_at IS NULL AND inventory_pools.is_active = 't' SQL - end) + ) + end) - scope :suspended, (lambda do - where - .not(suspended_until: nil) - .where('suspended_until >= ?', Time.zone.today) - end) + scope :suspended, + (lambda { where.not(suspended_until: nil).where('suspended_until >= ?', Time.zone.today) }) #################################################################### @@ -113,10 +109,7 @@ def check_for_existing_reservations if reservations.submitted.exists? or reservations.approved.exists? errors.add(:base, _('Currently has open orders')) end - if reservations.signed.exists? - errors.add(:base, _('Currently has items to return')) - end + errors.add(:base, _('Currently has items to return')) if reservations.signed.exists? end end - end diff --git a/app/models/address.rb b/app/models/address.rb index 89c717619b..986546da03 100644 --- a/app/models/address.rb +++ b/app/models/address.rb @@ -19,7 +19,7 @@ def label_for_audits end def to_multiline_s - [street, zip_code, city, country].compact.join('\r\n') + [street, zip_code, city, country].compact.join('undefinedundefined') end def country @@ -28,11 +28,6 @@ def country end def coordinates - if latitude.nil? or longitude.nil? - geocode - else - [latitude, longitude] - end + latitude.nil? or longitude.nil? ? geocode : [latitude, longitude] end - end diff --git a/app/models/attachment.rb b/app/models/attachment.rb index 32d8e36420..aa64ca0895 100644 --- a/app/models/attachment.rb +++ b/app/models/attachment.rb @@ -5,26 +5,16 @@ class Attachment < ApplicationRecord belongs_to :item, inverse_of: :attachments validate do - if size >= 100_000_000 - errors.add(:base, _('Uploaded file must be less than 100MB')) - end + errors.add(:base, _('Uploaded file must be less than 100MB')) if size >= 100_000_000 unless content_type.match? %r{^(image\/(png|gif|jpeg)|application\/pdf)} errors.add(:base, _('Unallowed content type')) end end validate do - unless model or item - errors.add \ - :base, - _('Attachment must be belong to model or item') - end + errors.add :base, _('Attachment must be belong to model or item') unless model or item - if model and item - errors.add \ - :base, - _('Attachment can\'t belong to model and item') - end + errors.add :base, _("Attachment can't belong to model and item") if model and item end def to_s @@ -34,5 +24,4 @@ def to_s def label_for_audits filename end - end diff --git a/app/models/audit.rb b/app/models/audit.rb index d1da69013e..fc24c7df4d 100644 --- a/app/models/audit.rb +++ b/app/models/audit.rb @@ -1,31 +1,19 @@ class Audit < Audited::Audit include Concerns::ScopeIfPresence - def self.filter(start_date: nil, - end_date: nil, - auditable_id: nil, - auditable_type: nil, - search_term: nil, - user_id: nil) - Audit - .scope_if_presence(auditable_type) do |audits, auditable_type| - audits.where(auditable_type: auditable_type) - end - .scope_if_presence(auditable_id) do |audits, auditable_id| - audits.where(auditable_id: auditable_id) - end - .scope_if_presence(start_date) do |audits, start_date| - audits.filter_since_start_date(start_date) - end - .scope_if_presence(end_date) do |audits, end_date| - audits.filter_before_end_date(end_date) - end - .scope_if_presence(search_term) do |audits, search_term| - audits.filter_by_term(search_term) - end - .scope_if_presence(user_id) do |audits, user_id| - audits.where(user_id: user_id) - end + def self.filter(start_date: nil, end_date: nil, auditable_id: nil, auditable_type: nil, search_term: nil, user_id: nil) + Audit.scope_if_presence(auditable_type) do |audits, auditable_type| + audits.where(auditable_type: auditable_type) + end + .scope_if_presence(auditable_id) do |audits, auditable_id| + audits.where(auditable_id: auditable_id) + end + .scope_if_presence(start_date) do |audits, start_date| + audits.filter_since_start_date(start_date) + end + .scope_if_presence(end_date) { |audits, end_date| audits.filter_before_end_date(end_date) } + .scope_if_presence(search_term) { |audits, search_term| audits.filter_by_term(search_term) } + .scope_if_presence(user_id) { |audits, user_id| audits.where(user_id: user_id) } end def self.filter_since_start_date(start_date) @@ -37,8 +25,9 @@ def self.filter_before_end_date(end_date) end def self.filter_by_term(term) - where(<<-SQL, ilike_term: "%#{term}%") - audited_changes ILIKE :ilike_term + where( + <<-SQL + audited_changes ILIKE :ilike_term OR EXISTS (SELECT 1 FROM users @@ -59,6 +48,8 @@ def self.filter_by_term(term) FROM models WHERE models.id = audits.auditable_id AND models.product ILIKE :ilike_term) - SQL + SQL, + ilike_term: "%#{term}%" + ) end end diff --git a/app/models/authentication_system.rb b/app/models/authentication_system.rb index b206ff7573..f10c307887 100644 --- a/app/models/authentication_system.rb +++ b/app/models/authentication_system.rb @@ -1,2 +1 @@ -class AuthenticationSystem < ApplicationRecord -end +class AuthenticationSystem < ApplicationRecord; end diff --git a/app/models/availability/group.rb b/app/models/availability/group.rb index 862ce29c3c..39de00848a 100644 --- a/app/models/availability/group.rb +++ b/app/models/availability/group.rb @@ -1,7 +1,5 @@ module Availability - module Group - - GENERAL_GROUP_ID = nil - - end + module Group + GENERAL_GROUP_ID = nil + end end diff --git a/app/models/availability/inventory_pool.rb b/app/models/availability/inventory_pool.rb index 3834aba7c9..e37b12d9b7 100644 --- a/app/models/availability/inventory_pool.rb +++ b/app/models/availability/inventory_pool.rb @@ -1,7 +1,5 @@ module Availability module InventoryPool - attr_accessor :loaded_group_ids - end end diff --git a/app/models/availability/main.rb b/app/models/availability/main.rb index 398f5cc169..721b219940 100644 --- a/app/models/availability/main.rb +++ b/app/models/availability/main.rb @@ -1,9 +1,7 @@ module Availability - ETERNITY = Date.parse('3000-01-01') class Changes < Hash - def between(start_date, end_date) # start from most recent entry we have, which is the last before start_date start_date = most_recent_before_or_equal(start_date) || start_date @@ -20,11 +18,12 @@ def end_date_of(date) # same quantities associated as the change preceding it. def insert_changes_and_get_inner(start_date, end_date) [start_date, end_date.tomorrow].each do |new_date| - self[new_date] ||= begin - change = self[most_recent_before_or_equal(new_date)] - # NOTE we copy values (we don't want references with .dup) - Marshal.load(Marshal.dump(change)) - end + self[new_date] ||= + begin + change = self[most_recent_before_or_equal(new_date)] + # NOTE we copy values (we don't want references with .dup) + Marshal.load(Marshal.dump(change)) + end end between(start_date, end_date) end @@ -41,50 +40,39 @@ def most_recent_before_or_equal(date) def first_after(date) keys.select { |x| x > date }.min end - end ######################################################### class Main - attr_reader(:running_reservations, - :entitlements, - :changes, - :inventory_pool_and_model_group_ids) + attr_reader(:running_reservations, :entitlements, :changes, :inventory_pool_and_model_group_ids) # exclude_reservations are used in borrow for dealing with the self-blocking # aspect of the reservations (context: change quantity for a model # in current order) def initialize(model:, inventory_pool:, exclude_reservations: []) - @model = model + @model = model @inventory_pool = inventory_pool - @running_reservations = \ - @inventory_pool - .running_reservations - .where(model_id: @model.id) - .where.not(id: exclude_reservations) - .order(:start_date, :end_date) + @running_reservations = + @inventory_pool.running_reservations.where(model_id: @model.id).where.not( + id: exclude_reservations + ) + .order(:start_date, :end_date) @entitlements = Entitlement.hash_with_generals(@inventory_pool, @model) @inventory_pool.loaded_group_ids ||= @inventory_pool.entitlement_group_ids - @inventory_pool_and_model_group_ids = \ - @inventory_pool.loaded_group_ids & @entitlements.keys # set intersection + @inventory_pool_and_model_group_ids = @inventory_pool.loaded_group_ids & @entitlements.keys # set intersection initial_change = {} @entitlements.each_pair do |group_id, quantity| - initial_change[group_id] = { in_quantity: quantity, - running_reservations: [] } + initial_change[group_id] = { in_quantity: quantity, running_reservations: [] } end @changes = Changes[Time.zone.today => initial_change] @running_reservations.each do |reservation| - reservation_group_ids = \ - reservation - .concat_group_ids - .to_s - .split(',') + reservation_group_ids = reservation.concat_group_ids.to_s.split(',') ######################### EXTEND END DATE ################################# # if overdue, extend end_date to today @@ -97,23 +85,17 @@ def initialize(model:, inventory_pool:, exclude_reservations: []) # - if today is the 29th of next month, # thus the item is available again from the 30th of next month # the replacement_interval is 1 month - unavailable_until = \ - [ - (reservation.late? ? Time.zone.today + 1.month : reservation.end_date), - Time.zone.today - ].max + @model.maintenance_period.day + unavailable_until = + [(reservation.late? ? Time.zone.today + 1.month : reservation.end_date), Time.zone.today] + .max + + @model.maintenance_period.day ##################### DON'T RECALCULATE PAST ############################## - unavailable_from = if reservation.item_id - Time.zone.today - else - [reservation.start_date, Time.zone.today].max - end + unavailable_from = + reservation.item_id ? Time.zone.today : [reservation.start_date, Time.zone.today].max ########################################################################### - inner_changes = \ - @changes.insert_changes_and_get_inner(unavailable_from, - unavailable_until) + inner_changes = @changes.insert_changes_and_get_inner(unavailable_from, unavailable_until) ###################### GROUP ALLOCATIONS ################################## # this is the order on the groups we check on: @@ -121,18 +103,18 @@ def initialize(model:, inventory_pool:, exclude_reservations: []) # TODO: sort groups by quantity desc ?? # 2. general group # 3. groups which the user is not even member - groups_to_check = \ - (reservation_group_ids & @inventory_pool_and_model_group_ids) \ - + [EntitlementGroup::GENERAL_GROUP_ID] \ - + (@inventory_pool_and_model_group_ids - reservation_group_ids) + groups_to_check = + (reservation_group_ids & @inventory_pool_and_model_group_ids) + + [EntitlementGroup::GENERAL_GROUP_ID] + + (@inventory_pool_and_model_group_ids - reservation_group_ids) max_possible_quantities_for_groups_and_changes = min_quantities_among_groups_and_changes(groups_to_check, inner_changes) - reservation.allocated_group_id = groups_to_check.detect do |group_id| - max_possible_quantities_for_groups_and_changes[group_id] \ - >= reservation.quantity - end + reservation.allocated_group_id = + groups_to_check.detect do |group_id| + max_possible_quantities_for_groups_and_changes[group_id] >= reservation.quantity + end # if still no group has enough available quantity, # we allocate to general as fallback @@ -148,30 +130,27 @@ def initialize(model:, inventory_pool:, exclude_reservations: []) def maximum_available_in_period_for_groups(start_date, end_date, group_ids) min_quantities_among_groups_and_changes( - [EntitlementGroup::GENERAL_GROUP_ID] + \ - (group_ids & @inventory_pool_and_model_group_ids), + [EntitlementGroup::GENERAL_GROUP_ID] + (group_ids & @inventory_pool_and_model_group_ids), @changes.between(start_date, end_date) - ).values.max + ) + .values + .max end - def maximum_available_in_period_summed_for_groups(start_date, - end_date, - group_ids = nil) + def maximum_available_in_period_summed_for_groups(start_date, end_date, group_ids = nil) group_ids ||= @inventory_pool_and_model_group_ids summed_quantities_for_groups_and_changes( - [EntitlementGroup::GENERAL_GROUP_ID] + \ - (group_ids & @inventory_pool_and_model_group_ids), + [EntitlementGroup::GENERAL_GROUP_ID] + (group_ids & @inventory_pool_and_model_group_ids), @changes.between(start_date, end_date) - ).min + ) + .min end def available_total_quantities # sort by date !!! Hash[@changes.sort].map do |date, change| total = change.values.sum { |val| val[:in_quantity] } - groups = change.map do |g, q| - q.merge(group_id: g) - end + groups = change.map { |g, q| q.merge(group_id: g) } [date, total, groups] end end @@ -181,9 +160,7 @@ def available_total_quantities # returns a Hash {group_id => quantity} def summed_quantities_for_groups_and_changes(group_ids, inner_changes) inner_changes.map do |date, change| - change - .select { |group_id, _| group_ids.include?(group_id) } - .values + change.select { |group_id, _| group_ids.include?(group_id) }.values .map { |stock_information| stock_information[:in_quantity] } .sum end @@ -194,15 +171,13 @@ def min_quantities_among_groups_and_changes(group_ids, inner_changes = nil) inner_changes ||= @changes result = {} group_ids.each do |group_id| - values = inner_changes.values.map do |inner_change| - Integer( - inner_change[group_id].try(:fetch, :in_quantity).presence || 0 - ) - end + values = + inner_changes.values.map do |inner_change| + Integer(inner_change[group_id].try(:fetch, :in_quantity).presence || 0) + end result[group_id] = values.min end result end - end end diff --git a/app/models/availability/model.rb b/app/models/availability/model.rb index 9c5b85146d..73ba994c88 100644 --- a/app/models/availability/model.rb +++ b/app/models/availability/model.rb @@ -1,11 +1,9 @@ module Availability module Model - def availability_in(inventory_pool, exclude_reservations: []) - Availability::Main.new(model: self, - inventory_pool: inventory_pool, - exclude_reservations: exclude_reservations) + Availability::Main.new( + model: self, inventory_pool: inventory_pool, exclude_reservations: exclude_reservations + ) end - end end diff --git a/app/models/availability/reservation.rb b/app/models/availability/reservation.rb index 031db1ce33..e7f4efbc8b 100644 --- a/app/models/availability/reservation.rb +++ b/app/models/availability/reservation.rb @@ -1,6 +1,5 @@ module Availability module Reservation - attr_accessor :allocated_group_id ################################# @@ -12,66 +11,59 @@ def timeout? def available? b = - if [:rejected, :closed].include?(status) \ - or (item_id.nil? and end_date < Time.zone.today) + if [:rejected, :closed].include?(status) or (item_id.nil? and end_date < Time.zone.today) false elsif is_a?(OptionLine) true elsif status == :unsubmitted if timeout? - customer_order_same_line_quantity = \ - user \ - .reservations - .where(inventory_pool_id: inventory_pool_id, - status: status, - model_id: model_id) + customer_order_same_line_quantity = + user.reservations.where( + inventory_pool_id: inventory_pool_id, status: status, model_id: model_id + ) .where('start_date <= ? AND end_date >= ?', end_date, start_date) .sum(:quantity) (maximum_available_quantity >= customer_order_same_line_quantity) else - # the unsubmitted reservations are also considered as - # running_reservations for the availability, then we sum up again - # the current reservation quantity (preventing self-blocking problem) (maximum_available_quantity + quantity >= quantity) end else - # if an item is already assigned, but the start_date is in the future, - # we only consider the real start-end range dates a = model.availability_in(inventory_pool) - # NOTE doesn't work self.allocated_group_id because - # is not a running_reservation - group_id = \ - a.running_reservations.detect { |x| x == self }.allocated_group_id - # first we check if the user is member of the - # allocated group (if false, then it's a soft-overbooking) + group_id = a.running_reservations.detect { |x| x == self }.allocated_group_id + (group_id.nil? or self.user.entitlement_group_ids.include?(group_id)) and - # then we check if all changes related to the time range - # and allocated group are non-negative (then it's a real-overbooking) - a.changes.between(start_date, end_date) - .all? { |k, v| v[group_id][:in_quantity] >= 0 } + a.changes.between(start_date, end_date).all? { |k, v| v[group_id][:in_quantity] >= 0 } end + # the unsubmitted reservations are also considered as + # running_reservations for the availability, then we sum up again + # the current reservation quantity (preventing self-blocking problem) + + # if an item is already assigned, but the start_date is in the future, + # we only consider the real start-end range dates + + # NOTE doesn't work self.allocated_group_id because + # is not a running_reservation + + # first we check if the user is member of the + # allocated group (if false, then it's a soft-overbooking) + + # then we check if all changes related to the time range + # and allocated group are non-negative (then it's a real-overbooking) # OPTIMIZE if b and [:unsubmitted].include? status - b = \ - (b \ - and inventory_pool.open_on?(start_date) \ - and inventory_pool.open_on?(end_date)) - b = \ - (b and not user.access_right_for(inventory_pool).suspended?) + b = (b and inventory_pool.open_on?(start_date) and inventory_pool.open_on?(end_date)) + b = (b and nuser.access_right_for(inventory_pool).suspended?) end b end def maximum_available_quantity - model - .availability_in(inventory_pool) - .maximum_available_in_period_for_groups(start_date, - end_date, - entitlement_group_ids) + model.availability_in(inventory_pool).maximum_available_in_period_for_groups( + start_date, end_date, entitlement_group_ids + ) end - end end diff --git a/app/models/bread_crumbs.rb b/app/models/bread_crumbs.rb index 8fd2a09560..6d6abb48b9 100644 --- a/app/models/bread_crumbs.rb +++ b/app/models/bread_crumbs.rb @@ -1,7 +1,6 @@ # NOTE: currently only works for category_ids class BreadCrumbs - def initialize(bread_crumbs_as_params) @crumbs = bread_crumbs_as_params @crumbs ||= [] @@ -12,14 +11,8 @@ def get @crumbs.each_with_index do |category_id, i| category = Category.find category_id category_ids = @crumbs[0..i] - url_helper = \ - Rails \ - .application - .routes - .url_helpers - .borrow_models_path(category_id: category_id) - crumbs.push [path_for(url_helper, category_ids, false), - category.name] + url_helper = Rails.application.routes.url_helpers.borrow_models_path(category_id: category_id) + crumbs.push [path_for(url_helper, category_ids, false), category.name] end crumbs end @@ -39,10 +32,7 @@ def path_for(path, category_ids = [], append_to_current = true) def as_params(category_ids = []) crumbs = [] - category_ids.each do |category_id| - crumbs.push(category_id) unless crumbs.include? category_id - end + category_ids.each { |category_id| crumbs.push(category_id) unless crumbs.include? category_id } { '_bc' => crumbs } end - end diff --git a/app/models/building.rb b/app/models/building.rb index 7713bab104..01b2e89683 100644 --- a/app/models/building.rb +++ b/app/models/building.rb @@ -10,11 +10,7 @@ class Building < ApplicationRecord ######################################################## - after_create do - Room.create!(name: 'general room', - building_id: id, - general: true) - end + after_create { Room.create!(name: 'general room', building_id: id, general: true) } ######################################################## @@ -31,11 +27,7 @@ def can_destroy? end def to_s - if code.presence - "#{name} (#{code})" - else - name - end + code.presence ? "#{name} (#{code})" : name end def label_for_audits @@ -48,19 +40,15 @@ def self.filter(params) buildings end - scope :search, lambda { |query| - sql = all - return sql if query.blank? - - query.split.each do |q| - q = "%#{q}%" - sql = \ - sql - .where( - arel_table[:name].matches(q) - .or(arel_table[:code].matches(q))) - end - sql - } - + scope :search, + lambda do |query| + sql = all + return sql if query.blank? + + query.split.each do |q| + q = "%#{q}%" + sql = sql.where(arel_table[:name].matches(q).or(arel_table[:code].matches(q))) + end + sql + end end diff --git a/app/models/category.rb b/app/models/category.rb index 0bbfd95f99..2b90b6eeed 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -1,20 +1,14 @@ class Category < ModelGroup - has_many :templates, -> { distinct }, through: :models - has_many :images, - -> { where(thumbnail: false) }, - as: :target, - dependent: :destroy + has_many :images, -> { where(thumbnail: false) }, as: :target, dependent: :destroy accepts_nested_attributes_for :images, allow_destroy: true def used? - not (models.empty? and children.empty?) + n(models.empty? and children.empty?) end - default_scope do - order(:name, :created_at, :id) - end + default_scope { order(:name, :created_at, :id) } def self.filter(params, _inventory_pool = nil) categories = all @@ -22,5 +16,4 @@ def self.filter(params, _inventory_pool = nil) categories = categories.order('name ASC') categories end - end diff --git a/app/models/concerns/default_pagination.rb b/app/models/concerns/default_pagination.rb index ff14efcd5e..28e8c186eb 100644 --- a/app/models/concerns/default_pagination.rb +++ b/app/models/concerns/default_pagination.rb @@ -9,8 +9,5 @@ def default_paginate(params, **options) end end - included do - extend Collection - end - + included { extend Collection } end diff --git a/app/models/concerns/hash_serializer_for_old_yaml_stuff.rb b/app/models/concerns/hash_serializer_for_old_yaml_stuff.rb index 78f35e63ce..304d9bd222 100644 --- a/app/models/concerns/hash_serializer_for_old_yaml_stuff.rb +++ b/app/models/concerns/hash_serializer_for_old_yaml_stuff.rb @@ -1,6 +1,5 @@ module Concerns class HashSerializerForOldYamlStuff - def self.dump(hash) YAML.dump(hash || {}) end diff --git a/app/models/concerns/inventory_code.rb b/app/models/concerns/inventory_code.rb index 9e438b72ca..64df842158 100644 --- a/app/models/concerns/inventory_code.rb +++ b/app/models/concerns/inventory_code.rb @@ -15,7 +15,6 @@ def highest_proposed_inventory_code #################################################################### module ClassMethods - # extract *last* number sequence in string def last_number(inventory_code) inventory_code ||= '' @@ -26,24 +25,20 @@ def last_number(inventory_code) # tries to take the next free inventory code # after the previously created Item def proposed_inventory_code(inventory_pool, type = :last) - latest_inventory_code = \ - Item - .where(owner_id: inventory_pool) - .order('created_at DESC') - .first - .try(:inventory_code) + latest_inventory_code = + Item.where(owner_id: inventory_pool).order('created_at DESC').first.try(:inventory_code) - next_num = case type - when :lowest - free_inventory_code_ranges(from: 0).first.first - when :highest - free_inventory_code_ranges(from: 0).last.first - else # :last - latest_number = last_number(latest_inventory_code) - free_inventory_code_ranges(from: latest_number) - .first - .first - end + next_num = + case type + when :lowest + free_inventory_code_ranges(from: 0).first.first + when :highest + free_inventory_code_ranges(from: 0).last.first + else + latest_number = last_number(latest_inventory_code) + free_inventory_code_ranges(from: latest_number).first.first + end + # :last "#{inventory_pool.shortname}#{next_num}" end @@ -64,17 +59,16 @@ def proposed_inventory_code(inventory_pool, type = :last) # def allocated_inventory_code_numbers(with_allocated_codes = false) h = {} - inventory_codes = \ - ApplicationRecord - .connection - .select_values('SELECT inventory_code FROM items') + inventory_codes = + ApplicationRecord.connection.select_values('SELECT inventory_code FROM items') inventory_codes.each do |code| num = last_number(code) - h[num] = if with_allocated_codes - (h[num].nil? ? code : Array(h[num]) << code) - else - Integer(h[num].presence || 0) + 1 - end + h[num] = + if with_allocated_codes + (h[num].nil? ? code : Array(h[num]) << code) + else + Integer(h[num].presence || 0) + 1 + end end h end @@ -100,15 +94,10 @@ def free_inventory_code_ranges(params) ranges = [] last_n = from - 1 - sorted_numbers = \ - allocated_inventory_code_numbers - .keys - .select { |n| n >= from and n <= to } - .sort + sorted_numbers = + allocated_inventory_code_numbers.keys.select { |n| n >= from and n <= to }.sort sorted_numbers.each do |n| - if n - 1 != last_n and (n - 1 - last_n >= min_gap) - ranges << [last_n + 1, n - 1] - end + ranges << [last_n + 1, n - 1] if n - 1 != last_n and (n - 1 - last_n >= min_gap) last_n = n end ranges << [last_n + 1, to] if last_n + 1 <= to and (to - last_n >= min_gap) diff --git a/app/models/concerns/item_csv.rb b/app/models/concerns/item_csv.rb index 2f0ae737c1..37696f2b58 100644 --- a/app/models/concerns/item_csv.rb +++ b/app/models/concerns/item_csv.rb @@ -37,45 +37,42 @@ def to_csv_array(options = { global: false }) } if type == 'Item' h1.merge!( - # FIXME: using model.try because database inconsistency - _('Description') => model.try(:description) + _( + # FIXME: using model.try because database inconsistency + 'Description' + ) => + model.try(:description) ) end h1.merge!( - # FIXME: using model.try because database inconsistency - case model.try(:type) + case # FIXME: using model.try because database inconsistency + model + .try(:type) when 'Software' _('Software Information') else _('Technical Details') - end => model.try(:technical_detail) + end => + model.try(:technical_detail) ) if type == 'Item' - # FIXME: using model.try because database inconsistency h1.merge!( + # investment: investment _('Internal Description') => model.try(:internal_description), _('Important notes for hand over') => model.try(:hand_over_note), _('Categories') => categories.join('; '), - _('Accessories') => \ - (model ? model.accessories.map(&:to_s) : []).join('; '), - _('Compatibles') => \ - (model ? model.compatibles.map(&:to_s) : []).join('; '), - _('Properties') => \ - (model ? model.properties.map(&:to_s) : []).join('; '), - # part_of_package: part_of_package, - # needs_permission: "#{self.needs_permission}", - # responsible: "#{self.responsible}", - # location: "#{self.location}", - # invoice: invoice, - # investment: investment + _('Accessories') => (model ? model.accessories.map(&:to_s) : []).join('; '), + _('Compatibles') => (model ? model.compatibles.map(&:to_s) : []).join('; '), + _('Properties') => (model ? model.properties.map(&:to_s) : []).join('; ') ) end + # FIXME: using model.try because database inconsistency fields = get_fields h2 = {} fields.each do |field| - next if %w(attachments building_id room_id shelf).include? field.id + next if %w[attachments building_id room_id shelf].include? field.id h2[_(field.data['label'])] = field.value(self) end h1.merge! h2 @@ -86,9 +83,9 @@ def to_csv_array(options = { global: false }) _('Shelf') => shelf, "#{_('Borrower')} #{_('First name')}" => current_borrower.try(:firstname), "#{_('Borrower')} #{_('Last name')}" => current_borrower.try(:lastname), - "#{_('Borrower')} #{_('Personal ID')}" => \ - current_borrower.try(:extended_info).try(:fetch, 'id', nil) \ - || current_borrower.try(:org_id), + "#{_('Borrower')} #{_('Personal ID')}" => + current_borrower.try(:extended_info).try(:fetch, 'id', nil) || + current_borrower.try(:org_id), "#{_('Borrowed until')}" => "#{current_reservation.try(:end_date)}" ) h1 diff --git a/app/models/concerns/log_send_mail_failure.rb b/app/models/concerns/log_send_mail_failure.rb index 6ba1a21536..a4116b79e3 100644 --- a/app/models/concerns/log_send_mail_failure.rb +++ b/app/models/concerns/log_send_mail_failure.rb @@ -2,13 +2,15 @@ module LogSendMailFailure def with_logging_send_mail_failure begin yield - rescue Exception => exception + # archive problem in the log, so the admin/developper # can look up what happened - logger.error "#{exception}\n #{exception.backtrace.join("\n ")}" + rescue Exception => exception + logger.error "#{exception}undefined #{exception.backtrace.join('undefined ')}" message = <<-MSG - The following error happened while sending a notification email to - #{target_user.email}: #{exception}. + The following error happened while sending a notification email to + #{target_user + .email}: #{exception}. That means that the user probably did not get the mail and you need to contact him/her in a different way. MSG diff --git a/app/models/concerns/scope_if_presence.rb b/app/models/concerns/scope_if_presence.rb index c184761cc4..5b704d1792 100644 --- a/app/models/concerns/scope_if_presence.rb +++ b/app/models/concerns/scope_if_presence.rb @@ -45,8 +45,10 @@ module ClassMethods def scope_if_presence(arg, &block) if arg.presence case block.arity - when -1, 1 then block.call(all) - when 2 then block.call(all, arg) + when -1, 1 + block.call(all) + when 2 + block.call(all, arg) else raise 'unallowed block arity' end diff --git a/app/models/concerns/search.rb b/app/models/concerns/search.rb index 46269db1ed..05c0c5baf0 100644 --- a/app/models/concerns/search.rb +++ b/app/models/concerns/search.rb @@ -1,19 +1,15 @@ module Search - module Name extend ActiveSupport::Concern included do + scope :search, + lambda do |query| + return all if query.blank? - scope :search, lambda { |query| - return all if query.blank? - - q = query.split.map { |s| "%#{s}%" } - where(arel_table[:name].matches_all(q)) - } - + q = query.split.map { |s| "%#{s}%" } + where(arel_table[:name].matches_all(q)) + end end - end - end diff --git a/app/models/concerns/serial_number_validation.rb b/app/models/concerns/serial_number_validation.rb index e4a652580e..c0e5984463 100644 --- a/app/models/concerns/serial_number_validation.rb +++ b/app/models/concerns/serial_number_validation.rb @@ -6,28 +6,20 @@ module SerialNumberValidation validate :validates_serial_number, unless: :skip_serial_number_validation def unique_serial_number? - not \ - Item - .where.not(id: id) - .where( - "lower(replace(serial_number, ' ', '')) = lower(replace(?, ' ', ''))", - serial_number - ) + nItem.where.not(id: id).where( + "lower(replace(serial_number, ' ', '')) = lower(replace(?, ' ', ''))", serial_number + ) .exists? end attr_accessor :skip_serial_number_validation - after_initialize do - @skip_serial_number_validation = false - end + after_initialize { @skip_serial_number_validation = false } private def validates_serial_number - if serial_number and \ - not skip_serial_number_validation and \ - not unique_serial_number? + if serial_number and nskip_serial_number_validation and nunique_serial_number? errors.add(:base, _('Same or similar serial number already exists.')) end end diff --git a/app/models/contract.rb b/app/models/contract.rb index a5e9f8e5a7..1d2a1a6ddb 100644 --- a/app/models/contract.rb +++ b/app/models/contract.rb @@ -9,26 +9,23 @@ class Contract < ApplicationRecord id = UUIDTools::UUID.random_create self.id = id b32 = Base32::Crockford.encode(id.to_i) - self.compact_id ||= (3..26).lazy.map { |i| b32[0..i] } \ - .map { |c_id| !Contract.find_by(compact_id: c_id) && c_id } \ - .find(&:itself) + self.compact_id ||= + (3..26).lazy.map { |i| b32[0..i] }.map { |c_id| !Contract.find_by(compact_id: c_id) && c_id } + .find(&:itself) end - ORDER_BY = lambda do - order('reservations.start_date ASC, ' \ + ORDER_BY = + lambda do + order( + 'reservations.start_date ASC, ' \ 'reservations.end_date ASC, ' \ - 'reservations.created_at ASC') - end + 'reservations.created_at ASC' + ) + end - has_many :reservations, - ORDER_BY, - dependent: :destroy - has_many :item_lines, - ORDER_BY, - dependent: :destroy - has_many :option_lines, - ORDER_BY, - dependent: :destroy + has_many :reservations, ORDER_BY, dependent: :destroy + has_many :item_lines, ORDER_BY, dependent: :destroy + has_many :option_lines, ORDER_BY, dependent: :destroy has_many :items, through: :item_lines has_many :options, -> { distinct }, through: :option_lines @@ -72,29 +69,38 @@ def models validate do if reservations.empty? - errors.add(:base, - _('This contract is not signable because ' \ - "it doesn't have any contract reservations.")) + errors.add( + :base, + _( + 'This contract is not signable because ' \ + "it doesn't have any contract reservations." + ) + ) else - if reservations.any? { |line| not [:signed, :closed].include?(line.status) } - errors.add(:base, _('The assigned contract reservations have to be ' \ - 'marked either as signed or as closed')) + if reservations.any? { |line| n[:signed, :closed].include?(line.status) } + errors.add( + :base, + _( + 'The assigned contract reservations have to be ' \ + 'marked either as signed or as closed' + ) + ) end if reservations.map(&:start_date).uniq.size != 1 errors.add(:base, _('The start_date is not unique')) end unless reservations.all? &:item - errors.add(:base, _('This contract is not signable because ' \ - 'some reservations are not assigned.')) - end - if reservations - .where(status: :signed) - .any? { |l| l.end_date < Time.zone.today } errors.add( :base, - _('End date of a take back line can not be in the past.') + _( + 'This contract is not signable because ' \ + 'some reservations are not assigned.' + ) ) end + if reservations.where(status: :signed).any? { |l| l.end_date < Time.zone.today } + errors.add(:base, _('End date of a take back line can not be in the past.')) + end if reservations.map(&:delegated_user).uniq.count > 1 errors.add(:base, _("Contract can't have multiple delegated users.")) end @@ -106,9 +112,10 @@ def models ################################################################################# - scope :with_verifiable_user, (lambda do - where <<-SQL - EXISTS ( + scope :with_verifiable_user, + (lambda do + where <<-SQL + EXISTS ( SELECT 1 FROM entitlement_groups_users INNER JOIN entitlement_groups @@ -118,93 +125,77 @@ def models AND entitlement_groups.inventory_pool_id = contracts.inventory_pool_id ) SQL - end) + end) # NOTE: assumes `joins(:reservations)` - scope :with_verifiable_user_and_model, (lambda do - joins(<<-SQL) - INNER JOIN entitlements + scope :with_verifiable_user_and_model, + (lambda do + joins( + <<-SQL + INNER JOIN entitlements ON entitlements.model_id = reservations.model_id INNER JOIN entitlement_groups ON entitlements.entitlement_group_id = entitlement_groups.id INNER JOIN entitlement_groups_users ON entitlement_groups.id = entitlement_groups_users.entitlement_group_id SQL - .where(<<-SQL) - entitlement_groups.is_verification_required IS TRUE + ) + .where( + <<-SQL + entitlement_groups.is_verification_required IS TRUE AND entitlement_groups_users.user_id = reservations.user_id AND entitlement_groups.inventory_pool_id = reservations.inventory_pool_id SQL - .distinct - end) - - scope :no_verification_required, (lambda do - where.not( - id: \ - Contract - .unscoped # have to be used here, `Contract` uses current scope (WTF) !!! - .joins(:reservations) - .with_verifiable_user_and_model - .select(:id) - ) - end) + ) + .distinct + end) + + scope :no_verification_required, + (lambda do + where.not( + id: Contract.unscoped.joins(:reservations).with_verifiable_user_and_model.select(:id) # have to be used here, `Contract` uses current scope (WTF) !!! + ) + end) def to_be_verified? - Contract - .joins(:reservations) - .with_verifiable_user_and_model - .where(id: id) - .exists? + Contract.joins(:reservations).with_verifiable_user_and_model.where(id: id).exists? end ######################################################################### scope :filter2, (lambda do |params, user = nil, inventory_pool = nil, paginate: true| - contracts = if user - user.contracts - elsif inventory_pool - inventory_pool.contracts - else - all - end - - contracts = \ - contracts - .joins(:reservations) - .scope_if_presence(params[:status]) do |contracts, states| - contracts.where(state: states) - end - .scope_if_presence(params[:search_term]) do |contracts, search_term| - contracts.search(params[:search_term]) - end - .scope_if_presence(params[:id]) do |contracts, ids| - contracts.where(id: ids) - end - .scope_if_presence(params[:no_verification_required], - &:no_verification_required) - .scope_if_presence(params[:to_be_verified], - &:with_verifiable_user_and_model) - .scope_if_presence(params[:from_verifiable_users], - &:with_verifiable_user) - .scope_if_presence(params[:range].try(:[], :start_date)) \ - do |contracts, start_date| - contracts.where('contracts.created_at >= ?', start_date) - end - .scope_if_presence(params[:range].try(:[], :end_date)) \ - do |contracts, end_date| - contracts.where('contracts.created_at <= ?', end_date) - end - .scope_if_presence(params[:global_contracts_search], - &:sort_for_global_search) - .distinct - - if paginate - contracts.default_paginate(params) - else - contracts - end - end) + contracts = + if user + user.contracts + elsif inventory_pool + inventory_pool.contracts + else + all + end + + contracts = + contracts.joins(:reservations).scope_if_presence( + params[:status] + ) { |contracts, states| contracts.where(state: states) } + .scope_if_presence(params[:search_term]) do |contracts, search_term| + contracts.search(params[:search_term]) + end + .scope_if_presence(params[:id]) { |contracts, ids| contracts.where(id: ids) } + .scope_if_presence(params[:no_verification_required], &:no_verification_required) + .scope_if_presence(params[:to_be_verified], &:with_verifiable_user_and_model) + .scope_if_presence(params[:from_verifiable_users], &:with_verifiable_user) + .scope_if_presence(params[:range].try(:[], :start_date)) do |contracts, start_date| + contracts.where('contracts.created_at >= ?', start_date) + end + .scope_if_presence(params[:range].try(:[], :end_date)) do |contracts, end_date| + contracts.where('contracts.created_at <= ?', end_date) + end + .scope_if_presence(params[:global_contracts_search], &:sort_for_global_search) + .distinct + + paginate ? contracts.default_paginate(params) : contracts + end) ######################################################################### @@ -212,45 +203,48 @@ def to_be_verified? def self.search(query) return all if query.blank? - sql = distinct \ - .joins('INNER JOIN users ON users.id = reservations.user_id') - .joins(<<-SQL) - LEFT JOIN users delegated_users + sql = + distinct.joins('INNER JOIN users ON users.id = reservations.user_id').joins( + <<-SQL + LEFT JOIN users delegated_users ON delegated_users.id = reservations.delegated_user_id SQL - .joins('LEFT JOIN orders ON reservations.order_id = orders.id') - .joins('LEFT JOIN options ON options.id = reservations.option_id') - .joins('LEFT JOIN models ON models.id = reservations.model_id') - .joins('LEFT JOIN items ON items.id = reservations.item_id') + ) + .joins('LEFT JOIN orders ON reservations.order_id = orders.id') + .joins('LEFT JOIN options ON options.id = reservations.option_id') + .joins('LEFT JOIN models ON models.id = reservations.model_id') + .joins('LEFT JOIN items ON items.id = reservations.item_id') query.split.map(&:strip).each do |q| qq = "%#{q}%" - sql = sql.where( - self.arel_table[:compact_id].matches(qq) - .or(User.arel_table[:login].matches(qq)) - .or(User.arel_table[:firstname].matches(qq)) - .or(User.arel_table[:lastname].matches(qq)) - .or(User.arel_table[:badge_id].matches(qq)) - .or(Arel::Table.new('delegated_users')[:login].matches(qq)) - .or(Arel::Table.new('delegated_users')[:firstname].matches(qq)) - .or(Arel::Table.new('delegated_users')[:lastname].matches(qq)) - .or(Arel::Table.new('delegated_users')[:badge_id].matches(qq)) - .or(Model.arel_table[:manufacturer].matches(qq)) - .or(Model.arel_table[:product].matches(qq)) - .or(Model.arel_table[:version].matches(qq)) - .or(Option.arel_table[:product].matches(qq)) - .or(Option.arel_table[:version].matches(qq)) - .or(Item.arel_table[:inventory_code].matches(qq)) - .or(Order.arel_table[:purpose].matches(qq)) - .or(Contract.arel_table[:purpose].matches(qq)) - ) + sql = + sql.where( + self.arel_table[:compact_id].matches(qq).or(User.arel_table[:login].matches(qq)).or( + User.arel_table[:firstname].matches(qq) + ) + .or(User.arel_table[:lastname].matches(qq)) + .or(User.arel_table[:badge_id].matches(qq)) + .or(Arel::Table.new('delegated_users')[:login].matches(qq)) + .or(Arel::Table.new('delegated_users')[:firstname].matches(qq)) + .or(Arel::Table.new('delegated_users')[:lastname].matches(qq)) + .or(Arel::Table.new('delegated_users')[:badge_id].matches(qq)) + .or(Model.arel_table[:manufacturer].matches(qq)) + .or(Model.arel_table[:product].matches(qq)) + .or(Model.arel_table[:version].matches(qq)) + .or(Option.arel_table[:product].matches(qq)) + .or(Option.arel_table[:version].matches(qq)) + .or(Item.arel_table[:inventory_code].matches(qq)) + .or(Order.arel_table[:purpose].matches(qq)) + .or(Contract.arel_table[:purpose].matches(qq)) + ) end sql end def self.sort_for_global_search - select(<<-SQL) - contracts.*, + select( + <<-SQL + contracts.*, CASE WHEN contracts.state = 'closed' THEN contracts.created_at ELSE NULL @@ -258,12 +252,15 @@ def self.sort_for_global_search users.firstname, bool_and(reservations.delegated_user_id IS NULL) AS not_for_delegation SQL - .group(<<-SQL) - contracts.id, + ) + .group( + <<-SQL + contracts.id, reservations.contract_id, reservations.id, users.firstname SQL + ) .order('contracts.state DESC') .order('custom_created_at DESC') .order('not_for_delegation DESC') @@ -287,31 +284,20 @@ def label_for_audits ######################################################################### - def self.sign!(current_user, - current_inventory_pool, - user, - selected_lines, - purpose, - note = nil, - delegated_user_id = nil) + def self.sign!(current_user, current_inventory_pool, user, selected_lines, purpose, note = nil, delegated_user_id = nil) transaction do - contract = Contract.new(state: :open, - purpose: purpose, - user: user, - inventory_pool: current_inventory_pool) + contract = + Contract.new( + state: :open, purpose: purpose, user: user, inventory_pool: current_inventory_pool + ) contract.note = note selected_lines.each do |cl| attrs = { - contract: contract, - status: :signed, - user: user, - handed_over_by_user_id: current_user.id + contract: contract, status: :signed, user: user, handed_over_by_user_id: current_user.id } - if delegated_user_id - attrs[:delegated_user] = user.delegated_users.find(delegated_user_id) - end + attrs[:delegated_user] = user.delegated_users.find(delegated_user_id) if delegated_user_id # Forces handover date to be today. attrs[:start_date] = Time.zone.today if cl.start_date != Time.zone.today @@ -324,5 +310,4 @@ def self.sign!(current_user, contract end end - end diff --git a/app/models/delegation/reservation.rb b/app/models/delegation/reservation.rb index 2b33407871..c45d536238 100644 --- a/app/models/delegation/reservation.rb +++ b/app/models/delegation/reservation.rb @@ -1,11 +1,5 @@ module Delegation::Reservation - def self.included(base) - base.class_eval do - - belongs_to :delegated_user, class_name: 'User' - - end + base.class_eval { belongs_to :delegated_user, class_name: 'User' } end - end diff --git a/app/models/delegation/user.rb b/app/models/delegation/user.rb index dc47e90a40..5afdb54628 100644 --- a/app/models/delegation/user.rb +++ b/app/models/delegation/user.rb @@ -1,9 +1,7 @@ module Delegation::User - # rubocop:disable Metrics/MethodLength def self.included(base) base.class_eval do - belongs_to :delegator_user, class_name: 'User' # NOTE this method is called from a normal user perspective @@ -29,40 +27,32 @@ def self.included(base) attr_reader :old_delegated_user_ids after_initialize do if delegation? - @old_delegated_user_ids = \ - ::DelegationUser.where(delegation_id: id).map(&:user_id) + @old_delegated_user_ids = ::DelegationUser.where(delegation_id: id).map(&:user_id) end end before_update do if delegation? - # fallback to [] because of factory removed_user_ids = (old_delegated_user_ids or []) - delegated_user_ids unless removed_user_ids.empty? - ####################################################################### - # Raise if one tries to remove a delegation member, who still has open - # reservations done in the name of this delegation. user_ids_with_open_reservations = [] removed_user_ids.each do |user_id| - open_reservations_of_user = \ - ::Reservation - .where(user_id: self.id, delegated_user_id: user_id) - .where(status: [:submitted, :approved, :signed]) + open_reservations_of_user = + ::Reservation.where(user_id: self.id, delegated_user_id: user_id).where( + status: [:submitted, :approved, :signed] + ) - if open_reservations_of_user.exists? - user_ids_with_open_reservations.push(user_id) - end + user_ids_with_open_reservations.push(user_id) if open_reservations_of_user.exists? end unless user_ids_with_open_reservations.empty? - users_with_open_reservations = \ - ::User.find(user_ids_with_open_reservations) - raise \ - _('There are open reservations for delegated users: ' \ - "#{users_with_open_reservations.map(&:name).join(', ')}.") + users_with_open_reservations = ::User.find(user_ids_with_open_reservations) + raise _( + 'There are open reservations for delegated users: ' \ + "#{users_with_open_reservations.map(&:name).join(', ')}." + ) end - ####################################################################### removed_user_ids.each do |user_id| # destroy sessions @@ -71,41 +61,42 @@ def self.included(base) .each(&:destroy!) # destroy unsubmitted reservations - ::Reservation - .where(user_id: self.id, delegated_user_id: user_id) - .where(status: :unsubmitted) + ::Reservation.where(user_id: self.id, delegated_user_id: user_id).where( + status: :unsubmitted + ) .each(&:destroy!) end end end + # fallback to [] because of factory + + ####################################################################### + # Raise if one tries to remove a delegation member, who still has open + # reservations done in the name of this delegation. + + ####################################################################### end ############################################################################# ############################################################################# before_validation do if delegation? - unless delegated_users.include? delegator_user - delegated_users << delegator_user - end + delegated_users << delegator_user unless delegated_users.include? delegator_user end end validate do if delegation? unless delegated_users.include? delegator_user - errors.add \ - :base, - _('The responsible user has to be member of the delegation') + errors.add :base, _('The responsible user has to be member of the delegation') end end end - end end # rubocop:enable Metrics/MethodLength def delegation? - not delegator_user_id.nil? + ndelegator_user_id.nil? end - end diff --git a/app/models/disabled_field.rb b/app/models/disabled_field.rb index a4eb2c50e6..fd74736f3c 100644 --- a/app/models/disabled_field.rb +++ b/app/models/disabled_field.rb @@ -7,5 +7,4 @@ class DisabledField < ApplicationRecord def label_for_audits "#{field_id} - #{inventory_pool_id}" end - end diff --git a/app/models/entitlement.rb b/app/models/entitlement.rb index b6b945be32..24b60aa4d5 100644 --- a/app/models/entitlement.rb +++ b/app/models/entitlement.rb @@ -9,41 +9,38 @@ class Entitlement < ApplicationRecord validates_numericality_of :quantity, only_integer: true, greater_than: 0 validates_uniqueness_of :entitlement_group_id, scope: :model_id - scope :with_generals, lambda {|model_ids: nil, inventory_pool_id: nil| - find_by_sql query(model_ids: model_ids, - inventory_pool_id: inventory_pool_id) - } + scope :with_generals, + lambda do |model_ids: nil, inventory_pool_id: nil| + find_by_sql query(model_ids: model_ids, inventory_pool_id: inventory_pool_id) + end # returns a hash as {entitlement_group_id => quantity} # like {nil => 10, 41 => 3, 42 => 6, ...} - def self.hash_with_generals(inventory_pool, - model, - entitlement_groups = nil, - ensure_non_negative_general: false) - # NOTE: `ensure_non_negative_general` is necessary for the borrow - # booking calendar. Negative quantity makes no sense there and leads to buggy - # behaviour. How does the negative value come to existence and if it is a - # desired feature remains questionable. - entitlements = with_generals(model_ids: [model.id], - inventory_pool_id: inventory_pool.id) + def self.hash_with_generals(inventory_pool, model, entitlement_groups = nil, ensure_non_negative_general: false) + entitlements = with_generals(model_ids: [model.id], inventory_pool_id: inventory_pool.id) if entitlement_groups entitlement_group_ids = entitlement_groups.map { |eg| eg.try(:id) } - entitlements = entitlements.select do |entitlement| - entitlement_group_ids.include? entitlement.entitlement_group_id - end + entitlements = + entitlements.select do |entitlement| + entitlement_group_ids.include? entitlement.entitlement_group_id + end end result = Hash[entitlements.map { |e| [e.entitlement_group_id, e.quantity] }] if missing_general_group_id?(result) or - (negative_general_quantity?(result) and ensure_non_negative_general) + (negative_general_quantity?(result) and ensure_non_negative_general) result[EntitlementGroup::GENERAL_GROUP_ID] = 0 end result end + # NOTE: `ensure_non_negative_general` is necessary for the borrow + # booking calendar. Negative quantity makes no sense there and leads to buggy + # behaviour. How does the negative value come to existence and if it is a + # desired feature remains questionable. def self.missing_general_group_id?(h) - h.empty? or not h.key?(EntitlementGroup::GENERAL_GROUP_ID) + h.empty? or nh.key?(EntitlementGroup::GENERAL_GROUP_ID) end def self.negative_general_quantity?(h) @@ -52,7 +49,7 @@ def self.negative_general_quantity?(h) def self.query(model_ids: nil, inventory_pool_id: nil) <<-SQL - SELECT model_id, + SELECT model_id, entitlement_groups.inventory_pool_id, entitlement_group_id, quantity @@ -60,8 +57,12 @@ def self.query(model_ids: nil, inventory_pool_id: nil) INNER JOIN entitlement_groups ON entitlements.entitlement_group_id = entitlement_groups.id WHERE TRUE - #{"AND model_id IN ('#{model_ids.join('\', \'')}') " if model_ids} - #{"AND entitlement_groups.inventory_pool_id = \'#{inventory_pool_id}\' " if inventory_pool_id} + #{if model_ids + "AND model_id IN ('#{model_ids.join("', '")}') " + end} + #{if inventory_pool_id + "AND entitlement_groups.inventory_pool_id = '#{inventory_pool_id}' " + end} UNION @@ -81,27 +82,23 @@ def self.query(model_ids: nil, inventory_pool_id: nil) FROM items AS i WHERE i.retired IS NULL AND i.is_borrowable = true AND i.parent_id IS NULL - #{"AND i.model_id IN ('#{model_ids.join('\', \'')}') " if model_ids} - #{"AND i.inventory_pool_id = \'#{inventory_pool_id}\' " if inventory_pool_id} + #{if model_ids + "AND i.model_id IN ('#{model_ids.join("', '")}') " + end} + #{if inventory_pool_id + "AND i.inventory_pool_id = '#{inventory_pool_id}' " + end} GROUP BY i.inventory_pool_id, i.model_id SQL end def entitled_quantity_in_other_groups - qty = \ - Entitlement - .where(model_id: model.id) - .where.not(id: id) - .map(&:quantity) - .reduce(&:+) + qty = Entitlement.where(model_id: model.id).where.not(id: id).map(&:quantity).reduce(&:+) qty || 0 end def max_possible_quantity - model - .borrowable_items - .where(inventory_pool_id: entitlement_group.inventory_pool.id) - .size + model.borrowable_items.where(inventory_pool_id: entitlement_group.inventory_pool.id).size end def max_possible_unentitled_quantity diff --git a/app/models/entitlement_group.rb b/app/models/entitlement_group.rb index f8031736be..269f394453 100644 --- a/app/models/entitlement_group.rb +++ b/app/models/entitlement_group.rb @@ -9,10 +9,7 @@ class EntitlementGroup < ApplicationRecord has_many :entitlements, dependent: :restrict_with_exception accepts_nested_attributes_for :entitlements, allow_destroy: true - has_many(:models, - -> { distinct }, - through: :entitlements, - dependent: :restrict_with_exception) + has_many(:models, -> { distinct }, through: :entitlements, dependent: :restrict_with_exception) validates_presence_of :inventory_pool_id # tmp#2 validates_presence_of :name diff --git a/app/models/field.rb b/app/models/field.rb index cbfe63bff5..865deac3b8 100644 --- a/app/models/field.rb +++ b/app/models/field.rb @@ -5,15 +5,17 @@ class Field < ApplicationRecord #################################### - GROUPS_ORDER = [nil, - 'General Information', - 'Status', - 'Location', - 'Inventory', - 'Invoice Information', - 'Umzug', - 'Toni Ankunftskontrolle', - 'Maintenance'] + GROUPS_ORDER = [ + nil, + 'General Information', + 'Status', + 'Location', + 'Inventory', + 'Invoice Information', + 'Umzug', + 'Toni Ankunftskontrolle', + 'Maintenance' + ] default_scope { where(active: true).order(:position) } @@ -21,15 +23,7 @@ class Field < ApplicationRecord def value(item) Array(data['attribute']).inject(item) do |r, m| - if r.is_a?(Hash) - r[m] - else - if m == 'id' - r - else - r.try(:send, m) - end - end + r.is_a?(Hash) ? r[m] : m == 'id' ? r : r.try(:send, m) end end @@ -40,17 +34,9 @@ def set_default_value(item) attrs = Array(data['attribute']) attrs.inject(item) do |r, m| if m == attrs[-1] - if r.is_a?(Hash) - r[m] = default - else - r.send "#{m}=", default - end + r.is_a?(Hash) ? r[m] = default : r.send "#{m}=", default else - if r.is_a?(Hash) - r[m] - else - r.send m - end + r.is_a?(Hash) ? r[m] : r.send m end end end @@ -64,8 +50,9 @@ def values when 'all_suppliers' Supplier.order(:name).map { |x| { value: x.id, label: x.name } }.as_json when 'all_currencies' - Money::Currency.all.map(&:iso_code).uniq \ - .sort.map { |iso_code| { label: iso_code, value: iso_code } } + Money::Currency.all.map(&:iso_code).uniq.sort.map do |iso_code| + { label: iso_code, value: iso_code } + end else data['values'] end @@ -83,17 +70,11 @@ def default def search_path(inventory_pool) case data['search_path'] when 'models' - Rails - .application - .routes - .url_helpers - .manage_models_path(inventory_pool, all: true) + Rails.application.routes.url_helpers.manage_models_path(inventory_pool, all: true) when 'software' - Rails - .application - .routes - .url_helpers - .manage_models_path(inventory_pool, all: true, type: :software) + Rails.application.routes.url_helpers.manage_models_path( + inventory_pool, all: true, type: :software + ) else data['search_path'] end @@ -112,14 +93,10 @@ def as_json(options = {}) def get_value_from_params(params) if data['attribute'].is_a? Array begin - data['attribute'].inject(params) do|params, attr| - if params.is_a? Hash - params[attr.to_sym] - else - params.send attr - end + data['attribute'].inject(params) do |params, attr| + params.is_a? Hash ? params[attr.to_sym] : params.send attr end - rescue + rescue StandardError nil end else @@ -130,13 +107,10 @@ def get_value_from_params(params) def editable(user, inventory_pool, item) return true unless data['permissions'] - if data['permissions']['role'] \ - and not user.has_role? data['permissions']['role'], inventory_pool - return false - end - if data['permissions']['owner'] and item.owner != inventory_pool + if data['permissions']['role'] and nuser.has_role? data['permissions']['role'], inventory_pool return false end + return false if data['permissions']['owner'] and item.owner != inventory_pool true end @@ -144,15 +118,10 @@ def editable(user, inventory_pool, item) ######## def accessible_by?(user, inventory_pool) - if data['permissions'] - user.has_role? data['permissions']['role'], inventory_pool - else - true - end + data['permissions'] ? user.has_role? data['permissions']['role'], inventory_pool : true end def label_for_audits id end - end diff --git a/app/models/hidden_field.rb b/app/models/hidden_field.rb index 032cef76d7..a39839220e 100644 --- a/app/models/hidden_field.rb +++ b/app/models/hidden_field.rb @@ -6,5 +6,4 @@ class HiddenField < ApplicationRecord def label_for_audits field_id end - end diff --git a/app/models/holiday.rb b/app/models/holiday.rb index dea68f0c1a..f9f9146a15 100644 --- a/app/models/holiday.rb +++ b/app/models/holiday.rb @@ -6,12 +6,9 @@ class Holiday < ApplicationRecord scope :future, -> { where(['end_date >= ?', Time.zone.today]) } - before_save do - self.end_date = self.start_date if self.end_date < self.start_date - end + before_save { self.end_date = self.start_date if self.end_date < self.start_date } def label_for_audits name end - end diff --git a/app/models/image.rb b/app/models/image.rb index 0a28bb29c3..851af97840 100644 --- a/app/models/image.rb +++ b/app/models/image.rb @@ -14,17 +14,14 @@ class Image < ApplicationRecord validates_presence_of :target, if: ->(image) { image.parent_id.nil? } validate do - if size >= 8_000_000 - errors.add(:base, _('Uploaded file must be less than 8MB')) - end + errors.add(:base, _('Uploaded file must be less than 8MB')) if size >= 8_000_000 unless content_type.match? %r{^image\/(png|gif|jpeg)} errors.add(:base, _('Unallowed content type')) end end validate do - if not thumbnail \ - and Image.where(target_id: target_id, target_type: 'ModelGroup').exists? + if nthumbnail and Image.where(target_id: target_id, target_type: 'ModelGroup').exists? errors.add(:base, _('Category can have only one image.')) end end @@ -32,5 +29,4 @@ class Image < ApplicationRecord def label_for_audits filename end - end diff --git a/app/models/inventory_pool.rb b/app/models/inventory_pool.rb index a4ea317677..066703420c 100644 --- a/app/models/inventory_pool.rb +++ b/app/models/inventory_pool.rb @@ -7,16 +7,10 @@ class InventoryPool < ApplicationRecord audited ################################################################################# - default_scope do - where(is_active: true) - end + default_scope { where(is_active: true) } ################################################################################# - after_save do - unless is_active? - reservations.unsubmitted.destroy_all - end - end + after_save { reservations.unsubmitted.destroy_all unless is_active? } belongs_to :address @@ -24,35 +18,35 @@ class InventoryPool < ApplicationRecord accepts_nested_attributes_for :workday has_many :holidays, dependent: :delete_all - accepts_nested_attributes_for(:holidays, - allow_destroy: true, - reject_if: proc { |holiday| holiday[:id] }) + accepts_nested_attributes_for( + :holidays, allow_destroy: true, reject_if: proc { |holiday| holiday[:id] } + ) has_many :access_rights, dependent: :delete_all - has_many(:users, - -> { where(access_rights: { deleted_at: nil }).distinct }, - through: :access_rights) - has_many(:suspended_users, - (lambda do - where(access_rights: { deleted_at: nil }) - .where - .not(access_rights: { suspended_until: nil }) - .where('access_rights.suspended_until >= ?', Time.zone.today) - .distinct - end), - through: :access_rights, source: :user) + has_many( + :users, -> { where(access_rights: { deleted_at: nil }).distinct }, through: :access_rights + ) + has_many( + :suspended_users, + (lambda do + where(access_rights: { deleted_at: nil }).where.not(access_rights: { suspended_until: nil }) + .where('access_rights.suspended_until >= ?', Time.zone.today) + .distinct + end), + through: :access_rights, source: :user + ) has_many :rooms, -> { distinct }, through: :items has_many :items, dependent: :restrict_with_exception - has_many(:own_items, - class_name: 'Item', - foreign_key: 'owner_id', - dependent: :restrict_with_exception) + has_many( + :own_items, class_name: 'Item', foreign_key: 'owner_id', dependent: :restrict_with_exception + ) has_many :models, -> { distinct }, through: :items has_many :options has_and_belongs_to_many :model_groups - has_and_belongs_to_many :templates, -> { where(type: 'Template') }, + has_and_belongs_to_many :templates, + -> { where(type: 'Template') }, join_table: 'inventory_pools_model_groups', association_foreign_key: 'model_group_id' @@ -73,16 +67,12 @@ def with_general has_many :mail_templates, dependent: :delete_all def suppliers - Supplier - .joins(:items) - .where(':id IN (items.owner_id, items.inventory_pool_id)', id: id) + Supplier.joins(:items).where(':id IN (items.owner_id, items.inventory_pool_id)', id: id) .distinct end def buildings - Building - .joins(:items) - .where(':id IN (items.owner_id, items.inventory_pool_id)', id: id) + Building.joins(:items).where(':id IN (items.owner_id, items.inventory_pool_id)', id: id) .distinct end @@ -104,9 +94,11 @@ def owner_or_responsible_for?(item) # - we ignore reservations that are not handed over which the end_date is # already in the past # - we consider even unsubmitted reservations, but not the already timed out ones - has_many :running_reservations, (lambda do - select(<<-SQL) - id, + has_many :running_reservations, + (lambda do + select( + <<-SQL + id, inventory_pool_id, model_id, item_id, @@ -118,23 +110,34 @@ def owner_or_responsible_for?(item) string_agg(entitlement_groups_users.entitlement_group_id::text, ',') AS concat_group_ids SQL - .joins(<<-SQL) - LEFT JOIN entitlement_groups_users + ) + .joins( + <<-SQL + LEFT JOIN entitlement_groups_users ON entitlement_groups_users.user_id = reservations.user_id SQL - .where(<<-SQL) - status NOT IN ('rejected', 'closed') + ) + .where( + <<-SQL + status NOT IN ('rejected', 'closed') AND NOT ( status = 'unsubmitted' AND - updated_at < '#{Time.now.utc - Setting.first.timeout_minutes.minutes}' + updated_at < '#{Time + .now + .utc - + Setting.first.timeout_minutes + .minutes}' ) AND NOT ( - end_date < '#{Time.zone.today}' AND + end_date < '#{Time.zone + .today}' AND item_id IS NULL ) SQL - .group(:id) - end), class_name: 'ItemLine' + ) + .group(:id) + end), + class_name: 'ItemLine' ####################################################################### @@ -151,33 +154,37 @@ def owner_or_responsible_for?(item) after_save do if automatic_access and automatic_access_changed? - AccessRight - .connection - .execute('INSERT INTO access_rights ' \ - '(role, inventory_pool_id, user_id, created_at, updated_at) ' \ - "SELECT 'customer', '#{id}', users.id, NOW(), NOW() " \ - 'FROM users ' \ - 'LEFT JOIN access_rights ' \ - 'ON access_rights.user_id = users.id ' \ - "AND access_rights.inventory_pool_id = '#{id}' " \ - 'WHERE access_rights.user_id IS NULL;') + AccessRight.connection.execute( + 'INSERT INTO access_rights ' \ + '(role, inventory_pool_id, user_id, created_at, updated_at) ' \ + "SELECT 'customer', '#{id}', users.id, NOW(), NOW() " \ + 'FROM users ' \ + 'LEFT JOIN access_rights ' \ + 'ON access_rights.user_id = users.id ' \ + "AND access_rights.inventory_pool_id = '#{id}' " \ + 'WHERE access_rights.user_id IS NULL;' + ) end end ####################################################################### - scope :search, lambda { |query| - sql = all - return sql if query.blank? - - query.split.each do|q| - q = "%#{q}%" - sql = sql.where(arel_table[:name].matches(q) - .or(arel_table[:shortname].matches(q)) - .or(arel_table[:description].matches(q))) - end - sql - } + scope :search, + lambda do |query| + sql = all + return sql if query.blank? + + query.split.each do |q| + q = "%#{q}%" + sql = + sql.where( + arel_table[:name].matches(q).or(arel_table[:shortname].matches(q)).or( + arel_table[:description].matches(q) + ) + ) + end + sql + end ####################################################################### @@ -200,11 +207,7 @@ def next_open_date(x = Time.zone.today) if workday.closed_days.size < 7 until open_on?(x) holiday = running_holiday_on(x) - if holiday - x = holiday.end_date.tomorrow - else - x += 1.day - end + holiday ? x = holiday.end_date.tomorrow : x += 1.day end end x @@ -214,11 +217,7 @@ def last_open_date(x = Time.zone.today) if workday.closed_days.size < 7 until open_on?(x) holiday = running_holiday_on(x) - if holiday - x = holiday.start_date.yesterday - else - x -= 1.day - end + holiday ? x = holiday.start_date.yesterday : x -= 1.day end end x @@ -235,21 +234,13 @@ def running_holiday_on(date) ################################################################################ def borrowable_items? - items - .where(items: { retired: nil, - is_borrowable: true, - parent_id: nil }) - .exists? + items.where(items: { retired: nil, is_borrowable: true, parent_id: nil }).exists? end ################################################################################ def update_address(attr) - if (a = Address.find_by(attr)) - update_attributes(address_id: a.id) - else - create_address(attr) - end + (a = Address.find_by(attr)) ? update_attributes(address_id: a.id) : create_address(attr) end def create_workday @@ -257,117 +248,112 @@ def create_workday end def inventory(params) - model_type = case params[:type] - when 'item' then 'model' - when 'license' then 'software' - when 'option' then 'option' - end - - model_filter_params = \ - params.clone.merge(paginate: 'false', - search_targets: [:manufacturer, - :product, - :version, - :items], - type: model_type) + model_type = + case params[:type] + when 'item' + 'model' + when 'license' + 'software' + when 'option' + 'option' + end + + model_filter_params = + params.clone.merge( + paginate: 'false', + search_targets: [:manufacturer, :product, :version, :items], + type: model_type + ) # if there are NOT any params related to items - if [:is_borrowable, - :retired, - :category_id, - :in_stock, - :incomplete, - :broken, - :owned, - :responsible_inventory_pool_id].all? { |param| params[param].blank? } - # and one does not explicitly ask for software, models or used/unused models + if [ + :is_borrowable, + :retired, + :category_id, + :in_stock, + :incomplete, + :broken, + :owned, + :responsible_inventory_pool_id + ] + .all? { |param| params[param].blank? } unless ['model', 'software'].include?(model_type) or params[:used] - # then include options - options = Option.filter(params.clone.merge(paginate: 'false', - sort: 'product', - order: 'ASC'), - self) + options = + Option.filter(params.clone.merge(paginate: 'false', sort: 'product', order: 'ASC'), self) end end + # and one does not explicitly ask for software, models or used/unused models + + # then include options # exlude models if asked only for options unless model_type == 'option' - items = Item.filter(params.clone.merge(paginate: 'false', search_term: nil), - self) + items = Item.filter(params.clone.merge(paginate: 'false', search_term: nil), self) models = Model.filter model_filter_params.merge(items: items), self else models = [] end - inventory = \ - (models + (options || [])) - .sort { |a, b| a.name.strip <=> b.name.strip } + inventory = (models + (options || [])).sort { |a, b| a.name.strip <=> b.name.strip } - unless params[:paginate] == 'false' - inventory = inventory.default_paginate params - end + inventory = inventory.default_paginate params unless params[:paginate] == 'false' inventory end - ITEM_PARAMS_FOR_CSV_EXPORT = \ - [:unborrowable, - :retired, - :category_id, - :in_stock, - :incomplete, - :broken, - :owned, - :responsible_inventory_pool_id, - :unused_models] + ITEM_PARAMS_FOR_CSV_EXPORT = [ + :unborrowable, + :retired, + :category_id, + :in_stock, + :incomplete, + :broken, + :owned, + :responsible_inventory_pool_id, + :unused_models + ] def self.objects_for_export(inventory_pool, params) - items = if params[:type] != 'option' - if inventory_pool - Item.filter(params.clone.merge(paginate: 'false', all: 'true'), - inventory_pool) - else - Item.unscoped - end.includes(:current_reservation) - else - [] - end - - options = if inventory_pool - if params[:type] != 'license' \ - and ITEM_PARAMS_FOR_CSV_EXPORT.all? { |p| params[p].blank? } - Option.filter \ - params.clone.merge(paginate: 'false', - sort: 'product', - order: 'ASC'), - inventory_pool - else - [] - end - else - Option.unscoped - end - - global = if inventory_pool - false - else - true - end + items = + if params[:type] != 'option' + if inventory_pool + Item.filter(params.clone.merge(paginate: 'false', all: 'true'), inventory_pool) + else + Item.unscoped + end + .includes(:current_reservation) + else + [] + end + + options = + if inventory_pool + if params[:type] != 'license' and ITEM_PARAMS_FOR_CSV_EXPORT.all? { |p| params[p].blank? } + Option.filter params.clone.merge(paginate: 'false', sort: 'product', order: 'ASC'), + inventory_pool + else + [] + end + else + Option.unscoped + end + + global = inventory_pool ? false : true include_params = [:room, :inventory_pool, :owner, :supplier] - include_params += \ - (global ? [:model] : [:item_lines, model: [:model_links, :model_groups]]) + include_params += (global ? [:model] : [:item_lines, model: [:model_links, :model_groups]]) objects = [] unless items.blank? items.includes(include_params).find_each do |i, index| - # How could an item ever be nil? - objects << i.to_csv_array(global: global) unless i.nil? + unless i.nil? + # How could an item ever be nil? + objects << + i.to_csv_array(global: global) + end end end unless options.blank? - options.includes(:inventory_pool).find_each do |o| - objects << o.to_csv_array unless o.nil? # How could an item ever be nil? - end + options.includes(:inventory_pool).find_each { |o| objects << o.to_csv_array unless o.nil? } # How could an item ever be nil? end objects end @@ -387,8 +373,7 @@ def self.excel_export(inventory_pool, params) objects = objects_for_export(inventory_pool, params) header = header_for_export(objects) - Export.excel_string header, objects, - worksheet_name: _('Inventory') + Export.excel_string header, objects, worksheet_name: _('Inventory') end def csv_import(inventory_pool, csv_file) @@ -397,21 +382,15 @@ def csv_import(inventory_pool, csv_file) items = [] transaction do - CSV.foreach(csv_file, - col_sep: ',', - quote_char: "\"", - headers: :first_row) do |row| + CSV.foreach(csv_file, col_sep: ',', quote_char: '"', headers: :first_row) do |row| unless row['inventory_code'].blank? - item = \ - inventory_pool - .items - .create(inventory_code: row['inventory_code'].strip, - model: Model.find(row['model_id']), - is_borrowable: (row['is_borrowable'] == '1' ? 1 : 0), - is_inventory_relevant: \ - (row['is_inventory_relevant'] == '0' ? 0 : 1)) do |i| - csv_import_helper(row, i) - end + item = + inventory_pool.items.create( + inventory_code: row['inventory_code'].strip, + model: Model.find(row['model_id']), + is_borrowable: (row['is_borrowable'] == '1' ? 1 : 0), + is_inventory_relevant: (row['is_inventory_relevant'] == '0' ? 0 : 1) + ) { |i| csv_import_helper(row, i) } item.valid? items << item @@ -429,66 +408,50 @@ def csv_import(inventory_pool, csv_file) def validate_inactive_conditions unless is_active? if orders_or_signed_contracts? - errors.add \ - :base, - _("Inventory pool can't be deactivated " \ - 'due to existing orders or signed contracts.') + errors.add :base, + _( + "Inventory pool can't be deactivated " \ + 'due to existing orders or signed contracts.' + ) end if owns_or_has_not_retired_items? - errors.add \ - :base, - _("Inventory pool can't be deactivated " \ - 'due to existing items which are not yet retired.') + errors.add :base, + _( + "Inventory pool can't be deactivated " \ + 'due to existing items which are not yet retired.' + ) end end end def orders_or_signed_contracts? - reservations.submitted.exists? or - reservations.approved.exists? or - reservations.signed.exists? + reservations.submitted.exists? or reservations.approved.exists? or reservations.signed.exists? end def owns_or_has_not_retired_items? - Item - .where('inventory_pool_id = ? OR owner_id = ?', id, id) - .where(retired: nil) - .exists? + Item.where('inventory_pool_id = ? OR owner_id = ?', id, id).where(retired: nil).exists? end def csv_import_helper(row, i) - unless row['serial_number'].blank? - i.serial_number = row['serial_number'] - end - unless row['note'].blank? - i.note = row['note'] - end - unless row['invoice_number'].blank? - i.invoice_number = row['invoice_number'] - end - unless row['invoice_date'].blank? - i.invoice_date = row['invoice_date'] - end - unless row['price'].blank? - i.price = row['price'] - end + i.serial_number = row['serial_number'] unless row['serial_number'].blank? + i.note = row['note'] unless row['note'].blank? + i.invoice_number = row['invoice_number'] unless row['invoice_number'].blank? + i.invoice_date = row['invoice_date'] unless row['invoice_date'].blank? + i.price = row['price'] unless row['price'].blank? unless row['supplier_name'].blank? - i.supplier = \ - Supplier.find_or_create_by(name: row['supplier_name']) + i.supplier = Supplier.find_or_create_by(name: row['supplier_name']) end unless row['building_id'].blank? and row['room_id'].blank? building = Building.find_by_id(name: row['building_id']) i.room = Room.find_by(id: row['room_id'], building_id: building.id) end unless row['properties_anschaffungskategorie'].blank? - i.properties[:anschaffungskategorie] = \ - row['properties_anschaffungskategorie'] + i.properties[:anschaffungskategorie] = row['properties_anschaffungskategorie'] end unless row['properties_project_number'].blank? i.properties[:reference] = 'investment' i.properties[:project_number] = row['properties_project_number'] end end - end diff --git a/app/models/item.rb b/app/models/item.rb index 39918238f7..70c31d215f 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -18,35 +18,30 @@ class Item < ApplicationRecord include DefaultPagination audited - belongs_to(:parent, - class_name: 'Item', - foreign_key: 'parent_id', - inverse_of: :children) - has_many(:children, - class_name: 'Item', - foreign_key: 'parent_id', - dependent: :nullify, - before_add: :check_child, - after_add: :update_child_attributes) + belongs_to(:parent, class_name: 'Item', foreign_key: 'parent_id', inverse_of: :children) + has_many( + :children, + class_name: 'Item', + foreign_key: 'parent_id', + dependent: :nullify, + before_add: :check_child, + after_add: :update_child_attributes + ) belongs_to :model, inverse_of: :items belongs_to :room, inverse_of: :items - belongs_to(:owner, - -> { unscope(where: :is_active) }, - class_name: 'InventoryPool', - foreign_key: 'owner_id', - inverse_of: :own_items) + belongs_to( + :owner, + -> { unscope(where: :is_active) }, + class_name: 'InventoryPool', foreign_key: 'owner_id', inverse_of: :own_items + ) belongs_to :supplier - belongs_to :inventory_pool, - -> { unscope(where: :is_active) }, - inverse_of: :items + belongs_to :inventory_pool, -> { unscope(where: :is_active) }, inverse_of: :items has_many :item_lines, dependent: :restrict_with_exception alias_method :reservations, :item_lines - has_one(:current_reservation, - -> { where(returned_date: nil) }, - class_name: 'Reservation') + has_one(:current_reservation, -> { where(returned_date: nil) }, class_name: 'Reservation') has_many :attachments, dependent: :destroy accepts_nested_attributes_for :attachments, allow_destroy: true @@ -77,40 +72,32 @@ class Item < ApplicationRecord # we want remove empty values (and we keep it as HashWithIndifferentAccess) self.properties = properties.delete_if { |k, v| v.blank? } - fields = \ + fields = Field.all.select do |field| - [nil, type.downcase].include?(field.data['target_type']) \ - and field.data.key?('default') + [nil, type.downcase].include?(field.data['target_type']) and field.data.key?('default') end - fields.each do |field| - field.set_default_value(self) - end + fields.each { |field| field.set_default_value(self) } end after_save :update_children_attributes #################################################################### - SEARCHABLE_FIELDS = %w(inventory_code - serial_number - invoice_number - note - name - user_name - properties) - - scope :search, lambda { |query| - return all if query.blank? - - q = query.split.map { |s| "%#{s}%" } - model_fields_1 = Model::SEARCHABLE_FIELDS.map { |f| "m1.#{f}" }.join(', ') - model_fields_2 = Model::SEARCHABLE_FIELDS.map { |f| "m2.#{f}" }.join(', ') - item_fields_1 = Item::SEARCHABLE_FIELDS.map { |f| "i1.#{f}" }.join(', ') - item_fields_2 = Item::SEARCHABLE_FIELDS.map { |f| "i2.#{f}" }.join(', ') - room_fields = \ - Room::SEARCHABLE_FIELDS.map { |f| "r.#{f}" }.join(', ') - joins(<<-SQL) - INNER JOIN (SELECT i1.id, + SEARCHABLE_FIELDS = %w[inventory_code serial_number invoice_number note name user_name properties] + + scope :search, + lambda do |query| + return all if query.blank? + + q = query.split.map { |s| "%#{s}%" } + model_fields_1 = Model::SEARCHABLE_FIELDS.map { |f| "m1.#{f}" }.join(', ') + model_fields_2 = Model::SEARCHABLE_FIELDS.map { |f| "m2.#{f}" }.join(', ') + item_fields_1 = Item::SEARCHABLE_FIELDS.map { |f| "i1.#{f}" }.join(', ') + item_fields_2 = Item::SEARCHABLE_FIELDS.map { |f| "i2.#{f}" }.join(', ') + room_fields = Room::SEARCHABLE_FIELDS.map { |f| "r.#{f}" }.join(', ') + joins( + <<-SQL + INNER JOIN (SELECT i1.id, CONCAT_WS(' ', #{model_fields_1}, #{model_fields_2}, @@ -124,8 +111,9 @@ class Item < ApplicationRecord LEFT JOIN rooms AS r ON r.id = i1.room_id) AS full_text ON items.id = full_text.id SQL - .where(Arel::Table.new(:full_text)[:text].matches_all(q)) - } + ) + .where(Arel::Table.new(:full_text)[:text].matches_all(q)) + end # rubocop:disable Metrics/CyclomaticComplexity def self.filter(params, inventory_pool = nil) @@ -135,8 +123,7 @@ def self.filter(params, inventory_pool = nil) items = items.by_owner_or_responsible inventory_pool if inventory_pool items = items.where(owner_id: inventory_pool) if params[:owned] if params[:responsible_inventory_pool_id] - items = \ - items.where(inventory_pool_id: params[:responsible_inventory_pool_id]) + items = items.where(inventory_pool_id: params[:responsible_inventory_pool_id]) end items = items.where(id: params[:ids]) if params[:ids] @@ -146,51 +133,44 @@ def self.filter(params, inventory_pool = nil) # there are 2 kinds of borrowable: # the first is item attribute - if params[:is_borrowable] - items = items.where(is_borrowable: (params[:is_borrowable] == 'true')) - end + items = items.where(is_borrowable: (params[:is_borrowable] == 'true')) if params[:is_borrowable] # the second is item scope items = items.borrowable if params[:borrowable] items = items.unborrowable if params[:unborrowable] if params[:category_id] - model_ids = if params[:category_id] == '00000000-0000-0000-0000-000000000000' - Model.where.not(id: Model.joins(:categories)) - else - Model - .joins(:categories) - .where("model_groups.id": \ - [Category.find(params[:category_id])] \ - + Category.find(params[:category_id]).descendants) - end + model_ids = + if params[:category_id] == '00000000-0000-0000-0000-000000000000' + Model.where.not(id: Model.joins(:categories)) + else + Model.joins(:categories).where( + :"model_groups.id" => + [Category.find(params[:category_id])] + + Category.find(params[:category_id]).descendants + ) + end items = items.where(model_id: model_ids) end items = items.where(parent_id: params[:package_ids]) if params[:package_ids] items = items.where(parent_id: nil) if params[:not_packaged] if params[:packages] - items = \ - items - .joins(:model) - .where(models: { is_package: (params[:packages] == 'true') }) + items = items.joins(:model).where(models: { is_package: (params[:packages] == 'true') }) end items = items.in_stock if params[:in_stock] items = items.incomplete if params[:incomplete] items = items.broken if params[:broken] - if params[:inventory_code] - items = items.where(inventory_code: params[:inventory_code]) - end + items = items.where(inventory_code: params[:inventory_code]) if params[:inventory_code] items = items.where(model_id: params[:model_ids]) if params[:model_ids] unless params[:before_last_check].blank? - items = \ - items - .where(arel_table[:last_check] - .lteq(Date.strptime(params[:before_last_check], - I18n.translate('date.formats.default')))) + items = + items.where( + arel_table[:last_check].lteq( + Date.strptime(params[:before_last_check], I18n.translate('date.formats.default')) + ) + ) end items = items.search(params[:search_term]) unless params[:search_term].blank? - if params[:sort_by_inventory_code] == 'true' - items = items.order(:inventory_code) - end + items = items.order(:inventory_code) if params[:sort_by_inventory_code] == 'true' items = items.default_paginate params unless params[:paginate] == 'false' items end @@ -205,11 +185,12 @@ def self.delete_all before_destroy do if model.is_package? and reservations.empty? - # NOTE only never handed over packages can be deleted + else errors.add(:base, 'Item cannot be deleted') throw :abort end + # NOTE only never handed over packages can be deleted end scope :borrowable, -> { where(is_borrowable: true, parent_id: nil) } @@ -231,22 +212,30 @@ def self.delete_all # Added parent_id to "in_stock" so items that are # in packages are considered to not be available - scope(:in_stock, - (lambda do - joins('LEFT JOIN reservations AS cl001 ' \ - 'ON items.id=cl001.item_id AND cl001.returned_date IS NULL') - .where('cl001.id IS NULL AND items.parent_id IS NULL') - end)) - scope(:not_in_stock, - (lambda do - joins('INNER JOIN reservations AS cl001 ' \ - 'ON items.id=cl001.item_id AND cl001.returned_date IS NULL') - end)) - - scope(:by_owner_or_responsible, - (lambda do |ip| - where(':id IN (items.owner_id, items.inventory_pool_id)', id: ip.id) - end)) + scope( + :in_stock, + (lambda do + joins( + 'LEFT JOIN reservations AS cl001 ' \ + 'ON items.id=cl001.item_id AND cl001.returned_date IS NULL' + ) + .where('cl001.id IS NULL AND items.parent_id IS NULL') + end) + ) + scope( + :not_in_stock, + (lambda do + joins( + 'INNER JOIN reservations AS cl001 ' \ + 'ON items.id=cl001.item_id AND cl001.returned_date IS NULL' + ) + end) + ) + + scope( + :by_owner_or_responsible, + (lambda { |ip| where(':id IN (items.owner_id, items.inventory_pool_id)', id: ip.id) }) + ) scope :items, -> { joins(:model).where(models: { type: 'Model' }) } scope :licenses, -> { joins(:model).where(models: { type: 'Software' }) } @@ -298,12 +287,11 @@ def location def current_location current_location = [] - if inventory_pool and owner != inventory_pool - current_location.push inventory_pool.to_s - end + current_location.push inventory_pool.to_s if inventory_pool and owner != inventory_pool if u = current_borrower - current_location.push \ - "#{u.firstname} #{u.lastname} #{_('until')} #{I18n.l(current_return_date)}" + current_location.push "#{u.firstname} #{u.lastname} #{_('until')} #{I18n.l( + current_return_date + )}" else current_location.push location end @@ -327,15 +315,12 @@ def latest_borrower end # TODO: statistics - def latest_take_back_manager - end + def latest_take_back_manager; end #################################################################### def update_children_attributes - children.each do |child| - update_child_attributes(child) - end + children.each { |child| update_child_attributes(child) } end #################################################################### @@ -346,13 +331,14 @@ def retired=(v) self[:retired] = v elsif [true, 'true'].include? v if retired? - # we keep the existing stored date + else self[:retired] = Time.zone.today end else self[:retired] = nil end + # we keep the existing stored date end # overriding attribute setter @@ -372,15 +358,8 @@ def price=(v) # overriding association setter def supplier_with_params=(v) - self.supplier_without_params = - if v.is_a? Hash - unless v[:id].blank? - Supplier.find v[:id] - end - # otherwise, item.supplier is set to nil automatically - else - v - end + self.supplier_without_params = v.is_a? Hash ? Supplier.find v[:id] unless v[:id].blank? : v + # otherwise, item.supplier is set to nil automatically end alias_method :supplier_without_params=, :supplier= @@ -388,11 +367,7 @@ def supplier_with_params=(v) # overriding association setter def owner_with_params=(v) - self.owner_without_params = if v.is_a? Hash - InventoryPool.find(v[:id]) unless v[:id].blank? - else - v - end + self.owner_without_params = v.is_a? Hash ? InventoryPool.find(v[:id]) unless v[:id].blank? : v end alias_method :owner_without_params=, :owner= @@ -400,13 +375,8 @@ def owner_with_params=(v) # overriding association setter def inventory_pool_with_params=(v) - self.inventory_pool_without_params = if v.is_a? Hash - unless v[:id].blank? - InventoryPool.find(v[:id]) - end - else - v - end + self.inventory_pool_without_params = + v.is_a? Hash ? InventoryPool.find(v[:id]) unless v[:id].blank? : v end alias_method :inventory_pool_without_params=, :inventory_pool= @@ -418,25 +388,22 @@ def inventory_pool_with_params=(v) def get_model_manufacturer if self.model.nil? or self.model.name.blank? - # FIXME: using model.try because database inconsistency 'UNKNOWN' if self.model.try(:manufacturer).blank? else - unless self.model.manufacturer.blank? - self.model.manufacturer.gsub(/\"/, '""') - end + self.model.manufacturer.gsub(/\"/, '""') unless self.model.manufacturer.blank? end + # FIXME: using model.try because database inconsistency end def get_categories(global = false) categories = [] unless global - # FIXME: using model.try because database inconsistency unless self.model.try(:categories).nil? or self.model.categories.count == 0 - self.model.categories.each do |c| - categories << c.name - end + self.model.categories.each { |c| categories << c.name } end end + # FIXME: using model.try because database inconsistency + categories end @@ -444,11 +411,13 @@ def get_fields # we use select instead of multiple where because we need to keep the sorting # we exclude what is already hardcoded before (model_id as product and version) Field.all.select do |f| - [nil, type.downcase].include?(f.data['target_type']) \ - and not ['model_id'].include?(f.data['form_name']) - end.sort_by do |f| - [Field::GROUPS_ORDER.index(f.data['group']) || 999, f.position] - end.group_by { |f| f.data['group'] }.values.flatten + [nil, type.downcase].include?(f.data['target_type']) and + n['model_id'].include?(f.data['form_name']) + end + .sort_by { |f| [Field::GROUPS_ORDER.index(f.data['group']) || 999, f.position] } + .group_by { |f| f.data['group'] } + .values + .flatten end # TODO: has_one/has_many @@ -459,8 +428,7 @@ def latest_reservation def validates_package if parent_id if parent.nil? - errors.add(:base, - _("The parent item doesn't exist (parent_id: %d)") % parent_id) + errors.add(:base, _("The parent item doesn't exist (parent_id: %d)") % parent_id) elsif model.is_package? errors.add(:base, _('A package cannot be nested to another package')) end @@ -470,9 +438,7 @@ def validates_package end if model.is_package? and !retired.nil? - children.each do |item| - item.update_attributes(parent: nil) - end + children.each { |item| item.update_attributes(parent: nil) } end end end @@ -480,22 +446,34 @@ def validates_package def validates_changes unless reservations.empty? if model_id_changed? - errors.add(:base, - _('The model cannot be changed because ' \ - 'the item is used in contracts already.')) + errors.add( + :base, + _( + 'The model cannot be changed because ' \ + 'the item is used in contracts already.' + ) + ) end end unless in_stock? if inventory_pool_id_changed? - errors.add(:base, - _('The responsible inventory pool cannot be changed because ' \ - "it's not returned yet or has already been assigned " \ - 'to a contract line.')) + errors.add( + :base, + _( + 'The responsible inventory pool cannot be changed because ' \ + "it's not returned yet or has already been assigned " \ + 'to a contract line.' + ) + ) end unless retired.nil? - errors.add(:base, - _("The item cannot be retired because it's not returned yet " \ - 'or has already been assigned to a contract line.')) + errors.add( + :base, + _( + "The item cannot be retired because it's not returned yet " \ + 'or has already been assigned to a contract line.' + ) + ) end end end @@ -510,9 +488,6 @@ def update_child_attributes(item) end def check_child(child) - if child.model.is_package? - raise _('A package cannot be nested to another package') - end + raise _('A package cannot be nested to another package') if child.model.is_package? end - end diff --git a/app/models/item_line.rb b/app/models/item_line.rb index b5f5f2b0c8..790516801e 100644 --- a/app/models/item_line.rb +++ b/app/models/item_line.rb @@ -19,8 +19,7 @@ class ItemLine < Reservation validates_numericality_of :quantity, equal_to: 1 validate :validate_item validates_presence_of :model_id - validates_presence_of(:item, - if: proc { |r| [:signed, :closed].include?(r.status) }) + validates_presence_of(:item, if: proc { |r| [:signed, :closed].include?(r.status) }) # TODO: 1301 default_scope -> {includes(:model).order("models.product")} @@ -61,41 +60,39 @@ def late?(current_date = Time.zone.today) # validator def validate_item if item_id and status == :approved - # model matching unless item.model_id == model_id errors.add(:base, _("The item doesn't match with the reserved model")) end - if item \ - .reservations - .handed_over_or_assigned_but_not_returned - .where(['id != ? AND user_id = ? AND status = ?', id, user_id, status]) + if item.reservations.handed_over_or_assigned_but_not_returned.where( + ['id != ? AND user_id = ? AND status = ?', id, user_id, status] + ) .exists? - # check if already assigned to the same contract - errors.add(:base, - _('%s is already assigned to this contract') % \ - item.inventory_code) - elsif item \ - .reservations - .handed_over_or_assigned_but_not_returned - .where.not(id: id) - .exists? - # check if available - errors.add(:base, - _('%s is already assigned to a different contract') % \ - item.inventory_code) + errors.add(:base, _('%s is already assigned to this contract') % item.inventory_code) + elsif item.reservations.handed_over_or_assigned_but_not_returned.where.not(id: id).exists? + errors.add(:base, _('%s is already assigned to a different contract') % item.inventory_code) end - # inventory_pool matching unless item.inventory_pool_id == inventory_pool_id - errors.add(:base, - _("The item doesn't belong to the inventory pool " \ - 'related to this contract')) + errors.add( + :base, + _( + "The item doesn't belong to the inventory pool " \ + 'related to this contract' + ) + ) end - # package check errors.add(:base, _('The item belongs to a package')) if item.parent_id end - end + # model matching + + # check if already assigned to the same contract + # check if available + + # inventory_pool matching + + # package check + end end diff --git a/app/models/language.rb b/app/models/language.rb index b974622b3a..948fb47908 100644 --- a/app/models/language.rb +++ b/app/models/language.rb @@ -4,7 +4,7 @@ class Language < ApplicationRecord default_scope { order(:name) } scope :active_languages, -> { where(active: true) } - validates_uniqueness_of :default, if: proc { |l| l.default } + validates_uniqueness_of :default, if: proc(&:default) def self.default_language Language.find_by(default: true) || Language.first @@ -15,22 +15,17 @@ def self.preferred(accepted_languages) return default if accepted_languages.nil? - accepted_languages = \ - accepted_languages - .split(',') - .map { |x| x.strip.split(';').first.split('-').first } - .uniq + accepted_languages = + accepted_languages.split(',').map { |x| x.strip.split(';').first.split('-').first }.uniq return default if accepted_languages.blank? - possible_languages = \ - active_languages.map { |x| x.locale_name.match(/\w{2}/).to_s } + possible_languages = active_languages.map { |x| x.locale_name.match(/\w{2}/).to_s } preferred_languages = accepted_languages & possible_languages return default if preferred_languages.blank? - preferred_language = \ - active_languages - .detect { |x| !(x.locale_name =~ /^#{preferred_languages.first}/).nil? } + preferred_language = + active_languages.detect { |x| !(x.locale_name =~ /^#{preferred_languages.first}/).nil? } preferred_language end diff --git a/app/models/line_modules/grouped_and_merged_lines.rb b/app/models/line_modules/grouped_and_merged_lines.rb index b5c694736a..371aefccaf 100644 --- a/app/models/line_modules/grouped_and_merged_lines.rb +++ b/app/models/line_modules/grouped_and_merged_lines.rb @@ -1,55 +1,52 @@ module LineModules - module GroupedAndMergedLines - def self.included(base) - base.class_eval do - extend(ClassMethods) - end + base.class_eval { extend(ClassMethods) } end module ClassMethods - def grouped_and_merged_lines(reservations, date = :start_date) - gmlines = reservations.group_by do |l| - case date - when :start_date + gmlines = + reservations.group_by do |l| + case date + when :start_date { start_date: l.start_date, inventory_pool: l.inventory_pool } - when :end_date + when :end_date { end_date: l.end_date, inventory_pool: l.inventory_pool } + end end - end.sort_by { |h| [h.first[date], h.first[:inventory_pool].name] } + .sort_by { |h| [h.first[date], h.first[:inventory_pool].name] } gmlines = Hash[gmlines] gmlines.each_pair do |k, v| - gmlines[k] = begin - hash = v.sort_by { |l| l.model.name }.group_by do |l| - case date - when :start_date - { end_date: l.end_date, model: l.model } - when :end_date - { start_date: l.start_date, model: l.model } + gmlines[k] = + begin + hash = + v.sort_by { |l| l.model.name }.group_by do |l| + case date + when :start_date + { end_date: l.end_date, model: l.model } + when :end_date + { start_date: l.start_date, model: l.model } + end + end + hash.values.map do |array| + h = { + line_ids: array.map(&:id), + quantity: array.sum(&:quantity), + model: array.first.model, + inventory_pool: array.first.inventory_pool, + start_date: array.first.start_date, + end_date: array.first.end_date + } + if array.all? { |l| l.status == :unsubmitted } and + array.any? { |l| l.user.timeout? } + h[:available?] = array.all?(&:available?) + end + h end end - hash.values.map do |array| - h = { - line_ids: array.map(&:id), - quantity: array.sum(&:quantity), - model: array.first.model, - inventory_pool: array.first.inventory_pool, - start_date: array.first.start_date, - end_date: array.first.end_date - } - if array.all? { |l| l.status == :unsubmitted } \ - and array.any? { |l| l.user.timeout? } - h[:available?] = array.all?(&:available?) - end - h - end - end end end - end - end end diff --git a/app/models/mail_template.rb b/app/models/mail_template.rb index 27806306b5..fa677f8f6e 100644 --- a/app/models/mail_template.rb +++ b/app/models/mail_template.rb @@ -8,7 +8,8 @@ class MailTemplate < ApplicationRecord submitted: :order, approved: :order, rejected: :order - }.freeze + } + .freeze self.inheritance_column = nil @@ -18,41 +19,41 @@ class MailTemplate < ApplicationRecord validates_uniqueness_of :name, scope: [:inventory_pool_id, :language_id, :format] validate :syntax_validation - after_save do - destroy if body.blank? - end + after_save { destroy if body.blank? } def self.available_liquid_variables_for_order [ 'user.name', 'inventory_pool.name', 'inventory_pool.description', - 'email_signature', - { 'reservations' => [ - 'l.quantity', - 'l.model_name', - 'l.start_date', - 'l.end_date' - ] }, + 'email_signature', { + 'reservations' => ['l.quantity', 'l.model_name', 'l.start_date', 'l.end_date'] + }, 'comment', 'purpose' ] end def self.liquid_variables_for_order(order, comment = nil) - { user: { name: order.target_user.name }, - inventory_pool: { name: order.inventory_pool.name, - description: order.inventory_pool.description }, + { + user: { name: order.target_user.name }, + inventory_pool: { + name: order.inventory_pool.name, description: order.inventory_pool.description + }, email_signature: Setting.first.email_signature, - reservations: order.reservations.map do |l| - { quantity: l.quantity, - model_name: l.model.name, - start_date: l.start_date, - end_date: l.end_date } - end, + reservations: + order.reservations.map do |l| + { + quantity: l.quantity, + model_name: l.model.name, + start_date: l.start_date, + end_date: l.end_date + } + end, comment: comment, purpose: order.purpose - }.deep_stringify_keys + } + .deep_stringify_keys end def self.available_liquid_variables_for_user @@ -60,41 +61,45 @@ def self.available_liquid_variables_for_user 'user.name', 'inventory_pool.name', 'inventory_pool.description', - 'email_signature', - { 'reservations' => [ - 'l.quantity', - 'l.model_name', - 'l.item_inventory_code', - 'l.start_date', - 'l.end_date' - ] }, + 'email_signature', { + 'reservations' => [ + 'l.quantity', + 'l.model_name', + 'l.item_inventory_code', + 'l.start_date', + 'l.end_date' + ] + }, 'quantity', 'due_date' ] end def self.liquid_variables_for_user(user, inventory_pool, reservations) - { user: { name: user.name }, - inventory_pool: { name: inventory_pool.name, - description: inventory_pool.description }, + { + user: { name: user.name }, + inventory_pool: { name: inventory_pool.name, description: inventory_pool.description }, email_signature: Setting.first.email_signature, - reservations: reservations.map do |l| - { quantity: l.quantity, - model_name: l.model.name, - item_inventory_code: l.item.inventory_code, - start_date: l.start_date, - end_date: l.end_date } - end, + reservations: + reservations.map do |l| + { + quantity: l.quantity, + model_name: l.model.name, + item_inventory_code: l.item.inventory_code, + start_date: l.start_date, + end_date: l.end_date + } + end, quantity: reservations.to_a.sum(&:quantity), due_date: reservations.first.end_date - }.deep_stringify_keys + } + .deep_stringify_keys end def self.get_template(inventory_pool, name, language) - MailTemplate.find_by!(inventory_pool_id: inventory_pool.id, - name: name, - language: language, - format: 'text') + MailTemplate.find_by!( + inventory_pool_id: inventory_pool.id, name: name, language: language, format: 'text' + ) end def label_for_audits @@ -110,5 +115,4 @@ def syntax_validation errors.add :base, e.to_s end end - end diff --git a/app/models/mailer/order.rb b/app/models/mailer/order.rb index 8564cf8c1a..429edbe630 100644 --- a/app/models/mailer/order.rb +++ b/app/models/mailer/order.rb @@ -1,41 +1,40 @@ class Mailer::Order < ActionMailer::Base - def choose_language_for(contract) I18n.locale = contract.target_user.language.locale_name || I18n.default_locale end def approved(order, comment, sent_at = Time.zone.now) choose_language_for(order) - mail(to: order.target_user.email, - from: (order.inventory_pool.email || Setting.first.default_email), - subject: _('[leihs] Reservation Confirmation'), - date: sent_at) do |format| + mail( + to: order.target_user.email, + from: (order.inventory_pool.email || Setting.first.default_email), + subject: _('[leihs] Reservation Confirmation'), + date: sent_at + ) do |format| format.text do name = 'approved' - template = MailTemplate.get_template(order.inventory_pool, - name, - order.target_user.language) - Liquid::Template - .parse(template.body) - .render(MailTemplate.liquid_variables_for_order(order, comment)) + template = MailTemplate.get_template(order.inventory_pool, name, order.target_user.language) + Liquid::Template.parse(template.body).render( + MailTemplate.liquid_variables_for_order(order, comment) + ) end end end def submitted(order, sent_at = Time.zone.now) choose_language_for(order) - mail(to: order.target_user.email, - from: (order.inventory_pool.email || Setting.first.default_email), - subject: _('[leihs] Reservation Submitted'), - date: sent_at) do |format| + mail( + to: order.target_user.email, + from: (order.inventory_pool.email || Setting.first.default_email), + subject: _('[leihs] Reservation Submitted'), + date: sent_at + ) do |format| format.text do name = 'submitted' - template = MailTemplate.get_template(order.inventory_pool, - name, - order.target_user.language) - Liquid::Template - .parse(template.body) - .render(MailTemplate.liquid_variables_for_order(order, nil)) + template = MailTemplate.get_template(order.inventory_pool, name, order.target_user.language) + Liquid::Template.parse(template.body).render( + MailTemplate.liquid_variables_for_order(order, nil) + ) end end end @@ -43,38 +42,37 @@ def submitted(order, sent_at = Time.zone.now) def received(order, sent_at = Time.zone.now) settings = Setting.first choose_language_for(order) - mail(to: (order.inventory_pool.email || settings.default_email), - from: (order.inventory_pool.email || settings.default_email), - subject: _('[leihs] Order received'), - date: sent_at) do |format| + mail( + to: (order.inventory_pool.email || settings.default_email), + from: (order.inventory_pool.email || settings.default_email), + subject: _('[leihs] Order received'), + date: sent_at + ) do |format| format.text do name = 'received' - template = MailTemplate.get_template(order.inventory_pool, - name, - order.target_user.language) - Liquid::Template - .parse(template.body) - .render(MailTemplate.liquid_variables_for_order(order, nil)) + template = MailTemplate.get_template(order.inventory_pool, name, order.target_user.language) + Liquid::Template.parse(template.body).render( + MailTemplate.liquid_variables_for_order(order, nil) + ) end end end def rejected(order, comment, sent_at = Time.zone.now) choose_language_for(order) - mail(to: order.target_user.email, - from: (order.inventory_pool.email || Setting.first.default_email), - subject: _('[leihs] Reservation Rejected'), - date: sent_at) do |format| + mail( + to: order.target_user.email, + from: (order.inventory_pool.email || Setting.first.default_email), + subject: _('[leihs] Reservation Rejected'), + date: sent_at + ) do |format| format.text do name = 'rejected' - template = MailTemplate.get_template(order.inventory_pool, - name, - order.target_user.language) - Liquid::Template - .parse(template.body) - .render(MailTemplate.liquid_variables_for_order(order, comment)) + template = MailTemplate.get_template(order.inventory_pool, name, order.target_user.language) + Liquid::Template.parse(template.body).render( + MailTemplate.liquid_variables_for_order(order, comment) + ) end end end - end diff --git a/app/models/mailer/user.rb b/app/models/mailer/user.rb index b5959c50e9..44ed25c0ff 100644 --- a/app/models/mailer/user.rb +++ b/app/models/mailer/user.rb @@ -1,61 +1,47 @@ class Mailer::User < ActionMailer::Base - def choose_language_for(user) - language = \ - user.language.try(:locale_name) \ - || Language.default_language.try(:locale_name) + language = user.language.try(:locale_name) || Language.default_language.try(:locale_name) I18n.locale = language || I18n.default_locale end def remind(user, inventory_pool, reservations, sent_at = Time.zone.now) choose_language_for(user) - mail(to: user.emails, - from: (inventory_pool.email || Setting.first.default_email), - subject: _('[leihs] Reminder'), - date: sent_at) do |format| + mail( + to: user.emails, + from: (inventory_pool.email || Setting.first.default_email), + subject: _('[leihs] Reminder'), + date: sent_at + ) do |format| format.text do name = 'reminder' - template = MailTemplate.get_template(inventory_pool, - name, - user.language) - Liquid::Template - .parse(template.body) - .render(MailTemplate.liquid_variables_for_user(user, - inventory_pool, - reservations)) + template = MailTemplate.get_template(inventory_pool, name, user.language) + Liquid::Template.parse(template.body).render( + MailTemplate.liquid_variables_for_user(user, inventory_pool, reservations) + ) end end end - def deadline_soon_reminder(user, - inventory_pool, - reservations, - sent_at = Time.zone.now) + def deadline_soon_reminder(user, inventory_pool, reservations, sent_at = Time.zone.now) choose_language_for(user) - mail(to: user.emails, - from: (inventory_pool.email || Setting.first.default_email), - subject: _('[leihs] Some items should be returned tomorrow'), - date: sent_at) do |format| + mail( + to: user.emails, + from: (inventory_pool.email || Setting.first.default_email), + subject: _('[leihs] Some items should be returned tomorrow'), + date: sent_at + ) do |format| format.text do name = 'deadline_soon_reminder' - template = MailTemplate.get_template(inventory_pool, - name, - user.language) - Liquid::Template - .parse(template.body) - .render(MailTemplate.liquid_variables_for_user(user, - inventory_pool, - reservations)) + template = MailTemplate.get_template(inventory_pool, name, user.language) + Liquid::Template.parse(template.body).render( + MailTemplate.liquid_variables_for_user(user, inventory_pool, reservations) + ) end end end def email(from, to, subject, body) @email = body - mail(to: to, - from: from, - subject: "[leihs] #{subject}", - date: Time.zone.now) + mail(to: to, from: from, subject: "[leihs] #{subject}", date: Time.zone.now) end - end diff --git a/app/models/model.rb b/app/models/model.rb index 4e274b05e0..e30068e495 100644 --- a/app/models/model.rb +++ b/app/models/model.rb @@ -35,12 +35,14 @@ class Model < ApplicationRecord # TODO: this is used by the filter has_many :unretired_items, -> { where(retired: nil) }, class_name: 'Item' # TODO: do we need a :all_items ?? - has_many(:borrowable_items, - -> { where(retired: nil, is_borrowable: true, parent_id: nil) }, - class_name: 'Item') - has_many(:unborrowable_items, - -> { where(retired: nil, is_borrowable: false) }, - class_name: 'Item') + has_many( + :borrowable_items, + -> { where(retired: nil, is_borrowable: true, parent_id: nil) }, + class_name: 'Item' + ) + has_many( + :unborrowable_items, -> { where(retired: nil, is_borrowable: false) }, class_name: 'Item' + ) has_many :unpackaged_items, -> { where(parent_id: nil) }, class_name: 'Item' # OPTIMIZE: N+1 select problem, :include => :inventory_pools @@ -49,8 +51,7 @@ class Model < ApplicationRecord has_many :entitlements, dependent: :delete_all do def set_in(inventory_pool, new_entitlements) - joins(:entitlement_group) - .where(entitlement_groups: { inventory_pool_id: inventory_pool }) + joins(:entitlement_group).where(entitlement_groups: { inventory_pool_id: inventory_pool }) .scoping do delete_all new_entitlements.delete(EntitlementGroup::GENERAL_GROUP_ID) @@ -59,11 +60,10 @@ def set_in(inventory_pool, new_entitlements) new_entitlements.each_pair do |entitlement_group_id, quantity| entitlement_group_id = entitlement_group_id quantity = Integer(quantity.presence || 0) - next unless ( - valid_entitlement_group_ids.include?(entitlement_group_id) \ - and quantity > 0) - create(entitlement_group_id: entitlement_group_id, - quantity: quantity) + unless (valid_entitlement_group_ids.include?(entitlement_group_id) and quantity > 0) + next + end + create(entitlement_group_id: entitlement_group_id, quantity: quantity) end end # if there's no more items of a model in a group accessible to @@ -85,10 +85,7 @@ def active_in(inventory_pool) end accepts_nested_attributes_for :accessories, allow_destroy: true - has_many :images, - -> { where(thumbnail: false) }, - as: :target, - dependent: :destroy + has_many :images, -> { where(thumbnail: false) }, as: :target, dependent: :destroy accepts_nested_attributes_for :images, allow_destroy: true has_many :attachments, dependent: :destroy @@ -97,18 +94,13 @@ def active_in(inventory_pool) # ModelGroups has_many :model_links, dependent: :destroy has_many :model_groups, -> { distinct }, through: :model_links - has_many(:categories, - -> { where(type: 'Category') }, - through: :model_links, - source: :model_group) - has_many(:templates, - -> { where(type: 'Template') }, - through: :model_links, - source: :model_group) + has_many(:categories, -> { where(type: 'Category') }, through: :model_links, source: :model_group) + has_many(:templates, -> { where(type: 'Template') }, through: :model_links, source: :model_group) ######## # says which other Model one Model works with - has_and_belongs_to_many :compatibles, -> { distinct }, + has_and_belongs_to_many :compatibles, + -> { distinct }, class_name: 'Model', join_table: 'models_compatibles', foreign_key: 'model_id', @@ -120,21 +112,25 @@ def active_in(inventory_pool) if product.blank? errors.add(:base, _('The model needs a product name.')) else - exists = Model.where.not( - id: self.id - ).where( - product: product - ).where( - version: version - ).any? + exists = Model.where.not(id: self.id).where(product: product).where(version: version).any? if exists if version.blank? - errors.add(:base, _('A model with the same product name ' \ - 'and empty version already exists.')) + errors.add( + :base, + _( + 'A model with the same product name ' \ + 'and empty version already exists.' + ) + ) else - errors.add(:base, _('A model with the same product name ' \ - 'and version already exists.')) + errors.add( + :base, + _( + 'A model with the same product name ' \ + 'and version already exists.' + ) + ) end end end @@ -144,180 +140,183 @@ def active_in(inventory_pool) scope :active, -> { joins(:items).where(items: { retired: nil }).distinct } - scope(:without_items, - (lambda do - select('models.*') - .joins('LEFT JOIN items ON items.model_id = models.id') - .where(['items.model_id IS NULL']) - end)) - - scope(:unused_for_inventory_pool, - (lambda do |ip| - model_ids = \ - Model - .select('models.id') - .joins(:items) - .where(':id IN (items.owner_id, items.inventory_pool_id)', - id: ip.id) - .distinct - Model.where("models.id NOT IN (#{model_ids.to_sql})") - end)) + scope( + :without_items, + (lambda do + select('models.*').joins('LEFT JOIN items ON items.model_id = models.id').where( + ['items.model_id IS NULL'] + ) + end) + ) + + scope( + :unused_for_inventory_pool, + (lambda do |ip| + model_ids = + Model.select('models.id').joins(:items).where( + ':id IN (items.owner_id, items.inventory_pool_id)', id: ip.id + ) + .distinct + Model.where("models.id NOT IN (#{model_ids.to_sql})") + end) + ) scope :packages, -> { where(is_package: true) } - scope :with_properties, lambda { - joins('LEFT JOIN properties ON properties.model_id = models.id') - .where.not(properties: { model_id: nil }) - .distinct - } - - scope :by_inventory_pool, lambda { |inventory_pool| - joins(:items) - .where(['items.inventory_pool_id = ?', inventory_pool]) - } - - scope(:owned_or_responsible_by_inventory_pool, - (lambda do |ip| - joins(:items) - .where(':id IN (items.owner_id, items.inventory_pool_id)', id: ip.id) + scope :with_properties, + lambda do + joins('LEFT JOIN properties ON properties.model_id = models.id').where.not( + properties: { model_id: nil } + ) .distinct - end)) - - scope(:all_from_inventory_pools, - (lambda do |inventory_pool_ids| - where(items: { inventory_pool_id: inventory_pool_ids }) - end)) - - scope(:by_categories, - (lambda do |categories| - joins('INNER JOIN model_links AS ml') # OPTIMIZE: no ON ?? - .where(['ml.model_group_id IN (?)', categories]) - end)) - - scope(:from_category_and_all_its_descendants, - (lambda do |category| - joins(:categories) - .where(model_groups: \ - { id: Category.find(category.id).self_and_descendants }) - end)) - - scope(:order_by_attribute_and_direction, - (lambda do |attr, direction| - if %w(product version manufacturer).include? attr \ - and ['asc', 'desc'].include? direction - order "#{attr} #{direction.upcase}" - else - default_order - end - end)) + end + + scope :by_inventory_pool, + lambda do |inventory_pool| + joins(:items).where(['items.inventory_pool_id = ?', inventory_pool]) + end + + scope( + :owned_or_responsible_by_inventory_pool, + (lambda do |ip| + joins(:items).where(':id IN (items.owner_id, items.inventory_pool_id)', id: ip.id).distinct + end) + ) + + scope( + :all_from_inventory_pools, + (lambda { |inventory_pool_ids| where(items: { inventory_pool_id: inventory_pool_ids }) }) + ) + + scope( + :by_categories, + (lambda do |categories| + joins('INNER JOIN model_links AS ml').where(['ml.model_group_id IN (?)', categories]) # OPTIMIZE: no ON ?? + end) + ) + + scope( + :from_category_and_all_its_descendants, + (lambda do |category| + joins(:categories).where( + model_groups: { id: Category.find(category.id).self_and_descendants } + ) + end) + ) + + scope( + :order_by_attribute_and_direction, + (lambda do |attr, direction| + if %w[product version manufacturer].include? attr and ['asc', 'desc'].include? direction + order "#{attr} #{direction.upcase}" + else + default_order + end + end) + ) scope :default_order, -> { order_by_attribute_and_direction('product', 'asc') } # not using scope because not working properly # (if result of first is nil, an additional query is performed returning all) def self.find_by_name(name) - find_by("CONCAT_WS(' ', product, version) = ?", name) \ - || find_by_product(name) \ - || find_by_version(name) + find_by("CONCAT_WS(' ', product, version) = ?", name) || find_by_product(name) || + find_by_version(name) end def self.manufacturers - distinct - .order(:manufacturer) - .pluck(:manufacturer) - .reject { |s| s.nil? || s.strip.empty? } + distinct.order(:manufacturer).pluck(:manufacturer).reject { |s| s.nil? || s.strip.empty? } end ############################################# - SEARCHABLE_FIELDS = %w(manufacturer product version) - - scope(:search, - (lambda do |query, fields = []| - return all if query.blank? - - # old# joins(:categories, :properties, :items) - sql = distinct - if fields.empty? - sql = sql - .joins('LEFT JOIN model_links AS ml2 ' \ - 'ON ml2.model_id = models.id') - .joins('LEFT JOIN model_groups AS mg2 ON ' \ - 'mg2.id = ml2.model_group_id ' \ - "AND mg2.type = 'Category'") - .joins('LEFT JOIN properties AS p2 ' \ - 'ON p2.model_id = models.id ') - end - if fields.empty? or fields.include?(:items) - sql = sql - .joins('LEFT JOIN items AS i2 ON i2.model_id = models.id') - .joins('LEFT JOIN rooms AS r ON r.id = i2.room_id') - .joins('LEFT JOIN items AS i3 ON i3.parent_id = i2.id') - .joins('LEFT JOIN models AS m3 ON m3.id = i3.model_id') - end + SEARCHABLE_FIELDS = %w[manufacturer product version] + + scope( + :search, + (lambda do |query, fields = []| + return all if query.blank? + + # old# joins(:categories, :properties, :items) + sql = distinct + if fields.empty? + sql = + sql.joins( + 'LEFT JOIN model_links AS ml2 ' \ + 'ON ml2.model_id = models.id' + ) + .joins( + 'LEFT JOIN model_groups AS mg2 ON ' \ + 'mg2.id = ml2.model_group_id ' \ + "AND mg2.type = 'Category'" + ) + .joins( + 'LEFT JOIN properties AS p2 ' \ + 'ON p2.model_id = models.id ' + ) + end + if fields.empty? or fields.include?(:items) + sql = + sql.joins('LEFT JOIN items AS i2 ON i2.model_id = models.id').joins( + 'LEFT JOIN rooms AS r ON r.id = i2.room_id' + ) + .joins('LEFT JOIN items AS i3 ON i3.parent_id = i2.id') + .joins('LEFT JOIN models AS m3 ON m3.id = i3.model_id') + end - # FIXME: refactor to Arel - query.split.each do |x| - s = [] - s1 = ["' '"] - SEARCHABLE_FIELDS.each do |field| - if fields.empty? or fields.include?(field.to_sym) - s1 << "models.#{field}" - end - end - s << "CONCAT_WS(#{s1.join(', ')}) ILIKE :query" - if fields.empty? - s << 'mg2.name ILIKE :query' - s << 'p2.value ILIKE :query' - end - if fields.empty? or fields.include?(:items) - model_fields = \ - Model::SEARCHABLE_FIELDS.map { |f| "m3.#{f}" }.join(', ') - item_fields_2 = \ - Item::SEARCHABLE_FIELDS.map { |f| "i2.#{f}" }.join(', ') - item_fields_3 = \ - Item::SEARCHABLE_FIELDS.map { |f| "i3.#{f}" }.join(', ') - room_fields = \ - Room::SEARCHABLE_FIELDS.map { |f| "r.#{f}" }.join(', ') - s << "CONCAT_WS(' ', " \ - "#{model_fields}, " \ - "#{item_fields_2}, " \ - "#{item_fields_3}, " \ - "#{room_fields}) ILIKE :query" - end + # FIXME: refactor to Arel + query.split.each do |x| + s = [] + s1 = ["' '"] + SEARCHABLE_FIELDS.each do |field| + s1 << "models.#{field}" if fields.empty? or fields.include?(field.to_sym) + end + s << "CONCAT_WS(#{s1.join(', ')}) ILIKE :query" + if fields.empty? + s << 'mg2.name ILIKE :query' + s << 'p2.value ILIKE :query' + end + if fields.empty? or fields.include?(:items) + model_fields = Model::SEARCHABLE_FIELDS.map { |f| "m3.#{f}" }.join(', ') + item_fields_2 = Item::SEARCHABLE_FIELDS.map { |f| "i2.#{f}" }.join(', ') + item_fields_3 = Item::SEARCHABLE_FIELDS.map { |f| "i3.#{f}" }.join(', ') + room_fields = Room::SEARCHABLE_FIELDS.map { |f| "r.#{f}" }.join(', ') + s << + "CONCAT_WS(' ', " \ + "#{model_fields}, " \ + "#{item_fields_2}, " \ + "#{item_fields_3}, " \ + "#{room_fields}) ILIKE :query" + end - sql = sql.where(format('%s', s.join(' OR ')), query: "%#{x}%") - end - sql - end)) + sql = sql.where(format('%s', s.join(' OR ')), query: "%#{x}%") + end + sql + end) + ) def self.filter(params, subject = nil, category = nil, borrowable = false) - models = if subject.is_a? User - filter_for_user params, subject, category, borrowable - elsif subject.is_a? InventoryPool - filter_for_inventory_pool params, subject, category - else - Model.all - end + models = + if subject.is_a? User + filter_for_user params, subject, category, borrowable + elsif subject.is_a? InventoryPool + filter_for_inventory_pool params, subject, category + else + Model.all + end if ['model', 'software'].include? params[:type] models = models.where(type: params[:type].capitalize) end - if params[:packages] - models = models.where(is_package: params[:packages] == 'true') - end + models = models.where(is_package: params[:packages] == 'true') if params[:packages] models = models.where(id: params[:id]) if params[:id] models = models.where(id: params[:ids]) if params[:ids] unless params[:search_term].blank? - models = \ + models = models.search params[:search_term], - (if params[:search_targets] - params[:search_targets] - else - [:manufacturer, :product, :version] - end) + (params[:search_targets] ? params[:search_targets] : [:manufacturer, :product, :version]) end models = models.order_by_attribute_and_direction params[:sort], params[:order] models = models.default_paginate params unless params[:paginate] == 'false' @@ -326,16 +325,12 @@ def self.filter(params, subject = nil, category = nil, borrowable = false) def self.filter_for_user(params, user, category, borrowable = false) models = user.models - if category - models = models.from_category_and_all_its_descendants(category) - end - if borrowable - models = models.borrowable - end + models = models.from_category_and_all_its_descendants(category) if category + models = models.borrowable if borrowable unless params[:inventory_pool_ids].blank? - models = \ - models.all_from_inventory_pools \ - user.inventory_pools.where(id: params[:inventory_pool_ids]).map(&:id) + models = + models.all_from_inventory_pools user.inventory_pools.where(id: params[:inventory_pool_ids]) + .map(&:id) end models end @@ -343,38 +338,30 @@ def self.filter_for_user(params, user, category, borrowable = false) def self.filter_for_inventory_pool(params, inventory_pool, _category) case params[:used] when 'false' - models = Model.unused_for_inventory_pool inventory_pool + models = Model.unused_for_inventory_pool inventory_pool when 'true' - models = if params[:as_responsible_only] - Model - .joins(:items) - .where(items: { inventory_pool_id: inventory_pool }) - .distinct - else - Model - .joins(:items) - .where(':id IN (items.owner_id, ' \ - 'items.inventory_pool_id)', - id: inventory_pool.id) - .distinct - end - unless params[:include_package_models] - models = models.where(items: { parent_id: nil }) - end - if params[:borrowable] == 'true' - models = models.joins(:items).where(items: { is_borrowable: true }) - end - if params[:items] - models = models.joins(:items).where(items: { id: params[:items] }) - end - if params[:responsible_inventory_pool_id] - models = \ - models - .joins(:items) - .where(items: \ - { inventory_pool_id: \ - params[:responsible_inventory_pool_id] }) + models = + if params[:as_responsible_only] + Model.joins(:items).where(items: { inventory_pool_id: inventory_pool }).distinct + else + Model.joins(:items).where( + ':id IN (items.owner_id, ' \ + 'items.inventory_pool_id)', + id: inventory_pool.id + ) + .distinct end + models = models.where(items: { parent_id: nil }) unless params[:include_package_models] + if params[:borrowable] == 'true' + models = models.joins(:items).where(items: { is_borrowable: true }) + end + models = models.joins(:items).where(items: { id: params[:items] }) if params[:items] + if params[:responsible_inventory_pool_id] + models = + models.joins(:items).where( + items: { inventory_pool_id: params[:responsible_inventory_pool_id] } + ) + end else models = Model.all end @@ -383,19 +370,17 @@ def self.filter_for_inventory_pool(params, inventory_pool, _category) if params[:category_id] == '00000000-0000-0000-0000-000000000000' models = models.where.not(id: Model.joins(:categories)) else - models = \ - models - .joins(:categories) - .where("model_groups.id": \ - [Category.find(params[:category_id])] \ - + Category.find(params[:category_id]).descendants) + models = + models.joins(:categories).where( + :"model_groups.id" => + [Category.find(params[:category_id])] + + Category.find(params[:category_id]).descendants + ) end end if params[:template_id] - models = \ - models - .joins(:model_links) - .where(model_links: { model_group_id: params[:template_id] }) + models = + models.joins(:model_links).where(model_links: { model_group_id: params[:template_id] }) end models end @@ -424,84 +409,52 @@ def image(offset = 0) end def needs_permission - items.each do |item| - return true if item.needs_permission - end + items.each { |item| return true if item.needs_permission } false end ############################################# # returns an array of reservations - def add_to_contract(contract, - user, - quantity = nil, - start_date = nil, - end_date = nil, - delegated_user_id = nil) - contract.add_lines(quantity, - self, - user, - start_date, - end_date, - delegated_user_id) + def add_to_contract(contract, user, quantity = nil, start_date = nil, end_date = nil, delegated_user_id = nil) + contract.add_lines(quantity, self, user, start_date, end_date, delegated_user_id) end ############################################# - def total_borrowable_items_for_user_and_pool(user, - inventory_pool, - ensure_non_negative_general: false) + def total_borrowable_items_for_user_and_pool(user, inventory_pool, ensure_non_negative_general: false) groups = user.entitlement_groups.with_general - entitled_quantity = \ - Entitlement.hash_with_generals(inventory_pool, - self, - groups, - ensure_non_negative_general: \ - ensure_non_negative_general) - .values - .sum - borrowable_quantity = \ - borrowable_items - .where(inventory_pool_id: inventory_pool.id) - .count + entitled_quantity = + Entitlement.hash_with_generals( + inventory_pool, self, groups, ensure_non_negative_general: ensure_non_negative_general + ) + .values + .sum + borrowable_quantity = borrowable_items.where(inventory_pool_id: inventory_pool.id).count [entitled_quantity, borrowable_quantity].min end - def total_borrowable_items_for_user(user, - ensure_non_negative_general: false) + def total_borrowable_items_for_user(user, ensure_non_negative_general: false) groups = user.entitlement_groups.with_general - entitled_quantity = \ - inventory_pools - .to_a - .sum do |ip| - Entitlement.hash_with_generals(ip, - self, - groups, - ensure_non_negative_general: \ - ensure_non_negative_general) + entitled_quantity = + inventory_pools.to_a.sum do |ip| + Entitlement.hash_with_generals( + ip, self, groups, ensure_non_negative_general: ensure_non_negative_general + ) .values .sum end - borrowable_quantity = \ - borrowable_items - .where(inventory_pool_id: user.inventory_pools) - .count + borrowable_quantity = borrowable_items.where(inventory_pool_id: user.inventory_pools).count [entitled_quantity, borrowable_quantity].min end def as_json_with_arguments(accessories_for_ip: nil, **options) h = as_json_without_arguments(options) if accessories_for_ip - h['accessory_names'] = \ - accessories - .active_in(accessories_for_ip) - .map(&:name) - .join(', ') + h['accessory_names'] = accessories.active_in(accessories_for_ip).map(&:name).join(', ') end h end alias_method :as_json_without_arguments, :as_json alias_method :as_json, :as_json_with_arguments - end diff --git a/app/models/model_group.rb b/app/models/model_group.rb index 86d153c8b9..3b97951db3 100644 --- a/app/models/model_group.rb +++ b/app/models/model_group.rb @@ -16,23 +16,21 @@ class ModelGroup < ApplicationRecord ################################################## - has_many :parent_links, - class_name: ::ModelGroupLink, - foreign_key: :child_id + has_many :parent_links, class_name: ::ModelGroupLink, foreign_key: :child_id - has_many :child_links, - class_name: ::ModelGroupLink, - foreign_key: :parent_id + has_many :child_links, class_name: ::ModelGroupLink, foreign_key: :parent_id - has_and_belongs_to_many \ - :children, - join_table: :model_group_links, class_name: 'ModelGroup', - foreign_key: :parent_id, association_foreign_key: :child_id + has_and_belongs_to_many :children, + join_table: :model_group_links, + class_name: 'ModelGroup', + foreign_key: :parent_id, + association_foreign_key: :child_id - has_and_belongs_to_many \ - :parents, - join_table: :model_group_links, class_name: 'ModelGroup', - foreign_key: :child_id, association_foreign_key: :parent_id + has_and_belongs_to_many :parents, + join_table: :model_group_links, + class_name: 'ModelGroup', + foreign_key: :child_id, + association_foreign_key: :parent_id def descendants(found = []) more = Set.new(self.children) + found.map(&:children).flatten @@ -49,29 +47,29 @@ def links_as_child # NOTE it's now chainable for scopes def all_models - Model - .joins(:model_links) - .where(model_links: { model_group_id: self_and_descendants.map(&:id) }) + Model.joins(:model_links).where(model_links: { model_group_id: self_and_descendants.map(&:id) }) .distinct end def image - self.images.first || all_models.detect { |m| not m.image.blank? }.try(:image) + self.images.first || all_models.detect { |m| nm.image.blank? }.try(:image) end - scope :roots, (lambda do - joins('LEFT JOIN model_group_links AS mgl ' \ - 'ON mgl.child_id = model_groups.id') - .where('mgl.child_id IS NULL') - end) + scope :roots, + (lambda do + joins( + 'LEFT JOIN model_group_links AS mgl ' \ + 'ON mgl.child_id = model_groups.id' + ) + .where('mgl.child_id IS NULL') + end) ################################################ # Edge Label def label(parent_id = nil) if parent_id - ModelGroupLink.where(child_id: self.id, parent_id: parent_id) \ - .first.try(:label) || name + ModelGroupLink.where(child_id: self.id, parent_id: parent_id).first.try(:label) || name else name end @@ -93,5 +91,4 @@ def to_s def <=>(other) self.name.downcase <=> other.name.downcase end - end diff --git a/app/models/model_group_link.rb b/app/models/model_group_link.rb index 6f11f28fd6..121e77d2e6 100644 --- a/app/models/model_group_link.rb +++ b/app/models/model_group_link.rb @@ -7,8 +7,8 @@ class ModelGroupLink < ApplicationRecord belongs_to :parent, class_name: 'ModelGroup' def self.find_edge(mg1, mg2) - where(parent_id: mg1.id, child_id: mg2.id).first \ - || where(child_id: mg1.id, parent_id: mg2.id).first + where(parent_id: mg1.id, child_id: mg2.id).first || + where(child_id: mg1.id, parent_id: mg2.id).first end def self.create_edge(parent, child) @@ -18,5 +18,4 @@ def self.create_edge(parent, child) def label_for_audits "#{model_group.try(&:name)} - #{model.try(&:name)}" end - end diff --git a/app/models/model_link.rb b/app/models/model_link.rb index 57558cc585..d8ec2e5580 100644 --- a/app/models/model_link.rb +++ b/app/models/model_link.rb @@ -4,9 +4,7 @@ class ModelLink < ApplicationRecord belongs_to :model_group, inverse_of: :model_links belongs_to :model, inverse_of: :model_links - before_validation do - self.quantity ||= 1 - end + before_validation { self.quantity ||= 1 } # prevent duplicated model in Category, but allow for Template validates_uniqueness_of :model_id, @@ -19,5 +17,4 @@ class ModelLink < ApplicationRecord def label_for_audits "#{model_group.name} - #{model.name}" end - end diff --git a/app/models/notification.rb b/app/models/notification.rb index ed8541ada4..ee696e3749 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -42,10 +42,7 @@ def self.order_rejected(order, comment, send_mail = true, _current_user = nil) def self.deadline_soon_reminder(user, reservations, send_mail = true) reservations.map(&:inventory_pool).uniq.each do |inventory_pool| if send_mail - o = \ - Mailer::User - .deadline_soon_reminder(user, inventory_pool, reservations) - .deliver_now + o = Mailer::User.deadline_soon_reminder(user, inventory_pool, reservations).deliver_now end title = (o.nil? ? _('Deadline soon') : o.subject) Notification.create(user: user, title: title) @@ -54,9 +51,7 @@ def self.deadline_soon_reminder(user, reservations, send_mail = true) def self.remind_user(user, reservations, send_mail = true) reservations.map(&:inventory_pool).uniq.each do |inventory_pool| - if send_mail - o = Mailer::User.remind(user, inventory_pool, reservations).deliver_now - end + o = Mailer::User.remind(user, inventory_pool, reservations).deliver_now if send_mail title = (o.nil? ? _('Reminder') : o.subject) Notification.create(user: user, title: title) end @@ -70,5 +65,4 @@ def self.user_email(from, to, subject, body) def label_for_audits "#{user.try(&:name)} - #{title}" end - end diff --git a/app/models/option.rb b/app/models/option.rb index 10147f09cb..f26929fa79 100644 --- a/app/models/option.rb +++ b/app/models/option.rb @@ -16,40 +16,42 @@ class Option < ApplicationRecord has_many :option_lines, dependent: :restrict_with_exception validates_presence_of :inventory_pool, :product - validates_uniqueness_of(:inventory_code, - scope: :inventory_pool_id, - unless: proc { |record| record.inventory_code.blank? }) + validates_uniqueness_of( + :inventory_code, + scope: :inventory_pool_id, unless: proc { |record| record.inventory_code.blank? } + ) before_validation do |record| - if !record.inventory_code.nil? and record.inventory_code.blank? - record.inventory_code = nil - end + record.inventory_code = nil if !record.inventory_code.nil? and record.inventory_code.blank? end ########################################## - SEARCHABLE_FIELDS = %w(manufacturer product version inventory_code) - - scope :search, lambda { |query, fields = []| - sql = all - return sql if query.blank? - - query.split.each do|q| - q = "%#{q}%" - # FIXME: use fields with SEARCHABLE_FIELDS - sql = sql.where(arel_table[:manufacturer].matches(q) - .or(arel_table[:product].matches(q)) - .or(arel_table[:version].matches(q)) - .or(arel_table[:inventory_code].matches(q))) - end - sql - } + SEARCHABLE_FIELDS = %w[manufacturer product version inventory_code] + + scope :search, + lambda do |query, fields = []| + sql = all + return sql if query.blank? + + query.split.each do |q| + q = "%#{q}%" + # FIXME: use fields with SEARCHABLE_FIELDS + sql = + sql.where( + arel_table[:manufacturer].matches(q).or(arel_table[:product].matches(q)).or( + arel_table[:version].matches(q) + ) + .or(arel_table[:inventory_code].matches(q)) + ) + end + sql + end def self.filter(params, inventory_pool = nil) options = inventory_pool ? inventory_pool.options : all unless params[:search_term].blank? - options = options.search(params[:search_term], - [:manufacturer, :product, :versin]) + options = options.search(params[:search_term], [:manufacturer, :product, :versin]) end options = options.where(id: params[:ids]) if params[:ids] if params[:sort] and params[:order] @@ -84,6 +86,7 @@ def model # Generates an array suitable for outputting a line of CSV using CSV def to_csv_array # Using #{} notation to catch nils gracefully and silently + { _('Model Name') => "#{self.name}", _('Inventory Code') => "#{self.inventory_code}", @@ -97,5 +100,4 @@ def to_csv_array def type nil end - end diff --git a/app/models/option_line.rb b/app/models/option_line.rb index 99f4cc1ebd..3a7e3ce7be 100644 --- a/app/models/option_line.rb +++ b/app/models/option_line.rb @@ -13,9 +13,13 @@ class OptionLine < Reservation validates_presence_of :option validate do unless option.inventory_pool == inventory_pool - errors.add(:base, - _("The option doesn't belong to the inventory pool " \ - 'related to this contract')) + errors.add( + :base, + _( + "The option doesn't belong to the inventory pool " \ + 'related to this contract' + ) + ) end end @@ -35,5 +39,4 @@ def complete? def late?(current_date = Time.zone.today) option and super end - end diff --git a/app/models/order.rb b/app/models/order.rb index 214d6d04ca..753619755d 100644 --- a/app/models/order.rb +++ b/app/models/order.rb @@ -27,39 +27,30 @@ def approved # NOTE: assumes `joins(:reservations)` def with_some_line_not_in_any_contract - where(reservations: { contract: nil }) - .distinct + where(reservations: { contract: nil }).distinct end end validate do unless user.access_right_for(inventory_pool) - errors.add \ - :base, - _('User does not have access to inventory pool: %s') \ - % inventory_pool.name + errors.add :base, _('User does not have access to inventory pool: %s') % inventory_pool.name end - if user.access_right_for(inventory_pool).try(&:suspended?) \ - and state != 'rejected' - errors.add \ - :base, - _('User is suspended for inventory pool: %s') \ - % inventory_pool.name + if user.access_right_for(inventory_pool).try(&:suspended?) and state != 'rejected' + errors.add :base, _('User is suspended for inventory pool: %s') % inventory_pool.name end if reservations.map(&:delegated_user).uniq.count > 1 - errors.add \ - :base, - _('An order can not have multiple delegated users.') + errors.add :base, _('An order can not have multiple delegated users.') end end ################################################################################# - scope :with_verifiable_user, (lambda do - where <<-SQL - EXISTS ( + scope :with_verifiable_user, + (lambda do + where <<-SQL + EXISTS ( SELECT 1 FROM entitlement_groups_users INNER JOIN entitlement_groups @@ -69,125 +60,116 @@ def with_some_line_not_in_any_contract AND entitlement_groups.inventory_pool_id = orders.inventory_pool_id ) SQL - end) + end) # NOTE: assumes `joins(:reservations)` - scope :with_verifiable_user_and_model, (lambda do - joins(<<-SQL) - INNER JOIN entitlements + scope :with_verifiable_user_and_model, + (lambda do + joins( + <<-SQL + INNER JOIN entitlements ON entitlements.model_id = reservations.model_id INNER JOIN entitlement_groups ON entitlements.entitlement_group_id = entitlement_groups.id INNER JOIN entitlement_groups_users ON entitlement_groups.id = entitlement_groups_users.entitlement_group_id SQL - .where(<<-SQL) - entitlement_groups.is_verification_required IS TRUE + ) + .where( + <<-SQL + entitlement_groups.is_verification_required IS TRUE AND entitlement_groups_users.user_id = reservations.user_id AND entitlement_groups.inventory_pool_id = reservations.inventory_pool_id SQL - .distinct - end) - - scope :no_verification_required, (lambda do - where.not( - id: \ - Order - .unscoped # have to be used here, `Order` uses current scope (WTF) !!! - .joins(:reservations) - .with_verifiable_user_and_model - .select(:id) - ) - end) + ) + .distinct + end) + + scope :no_verification_required, + (lambda do + where.not( + id: Order.unscoped.joins(:reservations).with_verifiable_user_and_model.select(:id) # have to be used here, `Order` uses current scope (WTF) !!! + ) + end) def to_be_verified? - Order - .joins(:reservations) - .with_verifiable_user_and_model.where(id: id).exists? + Order.joins(:reservations).with_verifiable_user_and_model.where(id: id).exists? end ################################################################################# - scope :filter2, (lambda do |params, user = nil, inventory_pool = nil| - orders = if user - user.orders - elsif inventory_pool - inventory_pool.orders - else - all - end - - orders = \ - orders - .joins(:reservations) - .with_some_line_not_in_any_contract - .scope_if_presence(params[:status]) do |orders, states| - orders.where(state: states) - end - .scope_if_presence(params[:search_term]) do |orders, search_term| - orders.search(params[:search_term]) - end - .scope_if_presence(params[:id]) do |orders, ids| - orders.where(id: ids) - end - .scope_if_presence(params[:reservation_ids]) do |orders, reservation_ids| - orders - .where(reservations: { id: reservation_ids }) - .distinct - end - .scope_if_presence(params[:no_verification_required], - &:no_verification_required) - .scope_if_presence(params[:to_be_verified], - &:with_verifiable_user_and_model) - .scope_if_presence(params[:from_verifiable_users], - &:with_verifiable_user) - .scope_if_presence(params[:range].try(:[], :start_date)) \ - do |orders, start_date| - orders.where('orders.created_at >= ?', start_date) - end - .scope_if_presence(params[:range].try(:[], :end_date)) \ - do |orders, end_date| - orders.where('orders.created_at <= ?', end_date) - end - .order('orders.created_at DESC') - .distinct - - orders.default_paginate(params) - end) + scope :filter2, + (lambda do |params, user = nil, inventory_pool = nil| + orders = + if user + user.orders + elsif inventory_pool + inventory_pool.orders + else + all + end + + orders = + orders.joins(:reservations).with_some_line_not_in_any_contract.scope_if_presence( + params[:status] + ) { |orders, states| orders.where(state: states) } + .scope_if_presence(params[:search_term]) do |orders, search_term| + orders.search(params[:search_term]) + end + .scope_if_presence(params[:id]) { |orders, ids| orders.where(id: ids) } + .scope_if_presence(params[:reservation_ids]) do |orders, reservation_ids| + orders.where(reservations: { id: reservation_ids }).distinct + end + .scope_if_presence(params[:no_verification_required], &:no_verification_required) + .scope_if_presence(params[:to_be_verified], &:with_verifiable_user_and_model) + .scope_if_presence(params[:from_verifiable_users], &:with_verifiable_user) + .scope_if_presence(params[:range].try(:[], :start_date)) do |orders, start_date| + orders.where('orders.created_at >= ?', start_date) + end + .scope_if_presence(params[:range].try(:[], :end_date)) do |orders, end_date| + orders.where('orders.created_at <= ?', end_date) + end + .order('orders.created_at DESC') + .distinct + + orders.default_paginate(params) + end) # NOTE: assumes `joins(:reservations)` def self.search(query) return all if query.blank? - sql = distinct - .joins('INNER JOIN users ON users.id = reservations.user_id') - .joins(<<-SQL) - LEFT JOIN users delegated_users + sql = + distinct.joins('INNER JOIN users ON users.id = reservations.user_id').joins( + <<-SQL + LEFT JOIN users delegated_users ON delegated_users.id = reservations.delegated_user_id SQL - .joins('LEFT JOIN options ON options.id = reservations.option_id') - .joins('LEFT JOIN models ON models.id = reservations.model_id') - .joins('LEFT JOIN items ON items.id = reservations.item_id') + ) + .joins('LEFT JOIN options ON options.id = reservations.option_id') + .joins('LEFT JOIN models ON models.id = reservations.model_id') + .joins('LEFT JOIN items ON items.id = reservations.item_id') query.split.map(&:strip).each do |q| qq = "%#{q}%" - sql = sql.where( - User.arel_table[:login].matches(qq) - .or(User.arel_table[:firstname].matches(qq)) - .or(User.arel_table[:lastname].matches(qq)) - .or(User.arel_table[:badge_id].matches(qq)) - .or(Arel::Table.new('delegated_users')[:login].matches(qq)) - .or(Arel::Table.new('delegated_users')[:firstname].matches(qq)) - .or(Arel::Table.new('delegated_users')[:lastname].matches(qq)) - .or(Arel::Table.new('delegated_users')[:badge_id].matches(qq)) - .or(Model.arel_table[:manufacturer].matches(qq)) - .or(Model.arel_table[:product].matches(qq)) - .or(Model.arel_table[:version].matches(qq)) - .or(Option.arel_table[:product].matches(qq)) - .or(Option.arel_table[:version].matches(qq)) - .or(Item.arel_table[:inventory_code].matches(qq)) - .or(Order.arel_table[:purpose].matches(qq)) - ) + sql = + sql.where( + User.arel_table[:login].matches(qq).or(User.arel_table[:firstname].matches(qq)).or( + User.arel_table[:lastname].matches(qq) + ) + .or(User.arel_table[:badge_id].matches(qq)) + .or(Arel::Table.new('delegated_users')[:login].matches(qq)) + .or(Arel::Table.new('delegated_users')[:firstname].matches(qq)) + .or(Arel::Table.new('delegated_users')[:lastname].matches(qq)) + .or(Arel::Table.new('delegated_users')[:badge_id].matches(qq)) + .or(Model.arel_table[:manufacturer].matches(qq)) + .or(Model.arel_table[:product].matches(qq)) + .or(Model.arel_table[:version].matches(qq)) + .or(Option.arel_table[:product].matches(qq)) + .or(Option.arel_table[:version].matches(qq)) + .or(Item.arel_table[:inventory_code].matches(qq)) + .or(Order.arel_table[:purpose].matches(qq)) + ) end sql end @@ -209,20 +191,15 @@ def send_approved_notification(comment, send_mail, current_user) end def send_submitted_notification - with_logging_send_mail_failure do - Notification.order_submitted(self, true) - end + with_logging_send_mail_failure { Notification.order_submitted(self, true) } end def send_received_notification - with_logging_send_mail_failure do - Notification.order_received(self, true) - end + with_logging_send_mail_failure { Notification.order_received(self, true) } end def approve(comment, send_mail = true, current_user = nil, force = false) - if approvable? \ - or (force and current_user.has_role?(:lending_manager, inventory_pool)) + if approvable? or (force and current_user.has_role?(:lending_manager, inventory_pool)) update_attributes(state: :approved) reservations.each { |cl| cl.update_attributes(status: :approved) } send_approved_notification(comment, send_mail, current_user) @@ -233,7 +210,7 @@ def approve(comment, send_mail = true, current_user = nil, force = false) end def approvable? - self_approvable? and \ + self_approvable? and begin if reservations.all?(&:approvable?) true @@ -245,15 +222,9 @@ def approvable? end def self_approvable? - if state == :approved - errors.add(:base, _('This order has already been approved.')) - end - if user.suspended?(inventory_pool) - errors.add(:base, _('This user is suspended.')) - end - if purpose.blank? - errors.add(:base, _('Please provide a purpose...')) - end + errors.add(:base, _('This order has already been approved.')) if state == :approved + errors.add(:base, _('This user is suspended.')) if user.suspended?(inventory_pool) + errors.add(:base, _('Please provide a purpose...')) if purpose.blank? errors.empty? end @@ -262,31 +233,25 @@ def uniq_reservations_error_messages end def target_user - if user.delegation? and delegated_user - delegated_user - else - user - end + user.delegation? and delegated_user ? delegated_user : user end ############################################ def min_date - unless reservations.blank? - # min(&:start_date) does not work here - # rubocop:disable Style/SymbolProc - reservations.min { |x| x.start_date }[:start_date] - # rubocop:enable Style/SymbolProc - end + reservations.min(&:start_date)[:start_date] unless reservations.blank? + # min(&:start_date) does not work here + # rubocop:disable Style/SymbolProc + + # rubocop:enable Style/SymbolProc end def max_date - unless reservations.blank? - # min(&:end_date) does not work here - # rubocop:disable Style/SymbolProc - reservations.max { |x| x.end_date }[:end_date] - # rubocop:enable Style/SymbolProc - end + reservations.max(&:end_date)[:end_date] unless reservations.blank? + # min(&:end_date) does not work here + # rubocop:disable Style/SymbolProc + + # rubocop:enable Style/SymbolProc end def max_range diff --git a/app/models/property.rb b/app/models/property.rb index ffdcfdf536..7ebd3a7da1 100644 --- a/app/models/property.rb +++ b/app/models/property.rb @@ -13,5 +13,4 @@ def to_s def label_for_audits to_s end - end diff --git a/app/models/reservation.rb b/app/models/reservation.rb index 7be506b09a..437ca59120 100644 --- a/app/models/reservation.rb +++ b/app/models/reservation.rb @@ -33,34 +33,27 @@ def status read_attribute(:status).to_sym end - STATUSES.each do |status| - scope status, -> { where(status: status) } - end + STATUSES.each { |status| scope status, -> { where(status: status) } } ######################################################################### default_scope { order(:start_date, :end_date, :created_at) } - scope(:handed_over_or_assigned_but_not_returned, - (lambda do - where(returned_date: nil) - .where('NOT (end_date < ? AND item_id IS NULL)', - Time.zone.today) - end)) + scope( + :handed_over_or_assigned_but_not_returned, + (lambda do + where(returned_date: nil).where('NOT (end_date < ? AND item_id IS NULL)', Time.zone.today) + end) + ) def self.filter(params, inventory_pool) reservations = inventory_pool.reservations - reservations - .scope_if_presence(params[:contract_ids]) do |rs, ids| - reservations.where(contract_id: ids) - end - .scope_if_presence(params[:order_ids]) do |rs, ids| - reservations.where(order_id: ids) - end - .scope_if_presence(params[:ids]) do |rs, ids| - reservations.where(id: ids) - end + reservations.scope_if_presence(params[:contract_ids]) do |rs, ids| + reservations.where(contract_id: ids) + end + .scope_if_presence(params[:order_ids]) { |rs, ids| reservations.where(order_id: ids) } + .scope_if_presence(params[:ids]) { |rs, ids| reservations.where(id: ids) } end ##################################################### @@ -75,43 +68,46 @@ def self.filter(params, inventory_pool) validates_numericality_of :quantity, greater_than: 0, only_integer: true validates_presence_of :user, :inventory_pool, :status - validates_presence_of(:contract, - if: proc { |r| [:signed, :closed].include?(r.status) }) + validates_presence_of(:contract, if: proc { |r| [:signed, :closed].include?(r.status) }) validate :date_sequence validate do errors.add(:base, _('No access')) unless user.access_right_for(inventory_pool) if changed_attributes.keys.count == 1 and end_date_changed? - # we skip delegation validation on end_date extension + elsif returned_date - # we skip delegation validation on returning (or returned) reservations + else if user.delegation? unless user.delegated_users.include?(delegated_user) - errors.add(:base, - _("Delegated user is not member of the contract's " \ - 'delegation or is empty')) + errors.add( + :base, + _( + "Delegated user is not member of the contract's " \ + 'delegation or is empty' + ) + ) end else if delegated_user - errors.add(:base, - _("Delegated user must be empty for contract's normal user")) + errors.add(:base, _("Delegated user must be empty for contract's normal user")) end end end + # we skip delegation validation on end_date extension + + # we skip delegation validation on returning (or returned) reservations end # only apply if self.class == Reservation, as ItemLine (< Reservation) defines # own specific validations for uniqueness of item_id - validates_uniqueness_of \ - :item_id, - scope: :returned_date, - if: proc { |r| r.class == Reservation and r.item_id and r.returned_date.nil? } - - before_save do - if returned_date and returned_date_changed? - self.status = :closed - end - end + validates_uniqueness_of :item_id, + scope: :returned_date, + if: + proc do |r| + r.class == Reservation and r.item_id and r.returned_date.nil? + end + + before_save { self.status = :closed if returned_date and returned_date_changed? } before_destroy do if [:rejected, :signed, :closed].include? status @@ -125,8 +121,7 @@ def self.filter(params, inventory_pool) def <=>(other) # TODO: prevent name with leading and trailing whitespaces # directly on model and option save - [self.start_date, self.model.name.strip] \ - <=> [other.start_date, other.model.name.strip] + [self.start_date, self.model.name.strip] <=> [other.start_date, other.model.name.strip] end def late?(current_date = Time.zone.today) @@ -158,40 +153,39 @@ def price_or_max_price if item (item.price || 0) * quantity else - (model - .borrowable_items - .where(inventory_pool_id: inventory_pool) - .map(&:price) - .compact - .max || 0) \ - * quantity + (model.borrowable_items.where(inventory_pool_id: inventory_pool).map(&:price).compact.max || + 0) * + quantity end end def target_user - if user.delegation? and delegated_user - delegated_user - else - user - end + user.delegation? and delegated_user ? delegated_user : user end ############################################ def approvable? if delegated_user.try :suspended?, inventory_pool - errors.add(:base, - _('The delegated user %s is suspended.') % delegated_user) + errors.add(:base, _('The delegated user %s is suspended.') % delegated_user) end unless visits_on_open_date? - errors.add(:base, - _('This order is not approvable because the inventory pool ' \ - 'is closed on either the start or enddate.')) + errors.add( + :base, + _( + 'This order is not approvable because the inventory pool ' \ + 'is closed on either the start or enddate.' + ) + ) end unless available? - errors.add(:base, - _('This order is not approvable because some reserved ' \ - 'models are not available.')) + errors.add( + :base, + _( + 'This order is not approvable because some reserved ' \ + 'models are not available.' + ) + ) end errors.empty? end @@ -200,12 +194,10 @@ def update_time_line(start_date, end_date, user) Reservation.transaction do start_date ||= self.start_date end_date ||= self.end_date - unless update_attributes(start_date: start_date, - end_date: [start_date, end_date].max) + unless update_attributes(start_date: start_date, end_date: [start_date, end_date].max) raise errors.full_messages.uniq.join(', ') end - if user.access_right_for(inventory_pool).role == :group_manager \ - and not available? + if user.access_right_for(inventory_pool).role == :group_manager and navailable? raise _('Not available') end end @@ -221,9 +213,7 @@ def last_closed_reservation_of_contract? def date_sequence # OPTIMIZE: strange behavior: in some cases, this error raises when shouldn't - if end_date < start_date - errors.add(:base, _('Start Date must be before End Date')) - end + errors.add(:base, _('Start Date must be before End Date')) if end_date < start_date # TODO: Think about this a little bit more.... # errors.add(:base, _("Start Date cannot be a past date")) # if start_date < Date.today diff --git a/app/models/room.rb b/app/models/room.rb index d14d247089..6259d94c88 100644 --- a/app/models/room.rb +++ b/app/models/room.rb @@ -1,7 +1,7 @@ class Room < ApplicationRecord include DefaultPagination - SEARCHABLE_FIELDS = %w(name) + SEARCHABLE_FIELDS = %w[name] belongs_to :building has_many :items, dependent: :restrict_with_exception @@ -12,25 +12,21 @@ class Room < ApplicationRecord scope :general, -> { where(general: true) } def self.general_general - find_by!(building_id: Leihs::Constants::GENERAL_BUILDING_UUID, - general: true) + find_by!(building_id: Leihs::Constants::GENERAL_BUILDING_UUID, general: true) end def self.search(search_term) - joins('INNER JOIN buildings ON buildings.id = rooms.building_id') - .where(<<-SQL.strip_heredoc) - rooms.name ILIKE '%#{search_term}%' OR + joins('INNER JOIN buildings ON buildings.id = rooms.building_id').where( + <<-SQL + rooms.name ILIKE '%#{search_term}%' OR buildings.name ILIKE '%#{search_term}%' OR buildings.code ILIKE '%#{search_term}%' SQL + .strip_heredoc + ) end def to_s - if description.presence - "#{name} (#{description})" - else - name - end + description.presence ? "#{name} (#{description})" : name end - end diff --git a/app/models/software.rb b/app/models/software.rb index 29f9493b79..d2b62bb775 100644 --- a/app/models/software.rb +++ b/app/models/software.rb @@ -1,3 +1 @@ -class Software < Model - -end +class Software < Model; end diff --git a/app/models/statistics/base.rb b/app/models/statistics/base.rb index d7c1bd7f0b..9c2454a2fb 100644 --- a/app/models/statistics/base.rb +++ b/app/models/statistics/base.rb @@ -1,7 +1,6 @@ module Statistics class Base class << self - def hand_overs(klasses, options = {}) options = options.symbolize_keys options[:limit] ||= 10 @@ -19,16 +18,16 @@ def hand_overs(klasses, options = {}) query = get_query_for_hand_overs(klass, reservations, options) query.map do |x| - h = { type: 'statistic', - object: klass.name, - id: x.id, - label: x.label, - quantity: Integer(x.quantity), - unit: _('lends') } + h = { + type: 'statistic', + object: klass.name, + id: x.id, + label: x.label, + quantity: Integer(x.quantity), + unit: _('lends') + } unless klasses.empty? - h[:children] = \ - hand_overs(klasses, - options.merge(klass.name.foreign_key.to_sym => x.id)) + h[:children] = hand_overs(klasses, options.merge(klass.name.foreign_key.to_sym => x.id)) end h end @@ -51,16 +50,16 @@ def contracts(klasses, options = {}) query = get_query_for_contracts(klass, reservations, options) query.map do |x| - h = { type: 'statistic', - object: klass.name, - id: x.id, - label: x.label, - quantity: Integer(x.quantity), - unit: _('contracts') } + h = { + type: 'statistic', + object: klass.name, + id: x.id, + label: x.label, + quantity: Integer(x.quantity), + unit: _('contracts') + } unless klasses.empty? - h[:children] = \ - contracts(klasses, - options.merge(klass.name.foreign_key.to_sym => x.id)) + h[:children] = contracts(klasses, options.merge(klass.name.foreign_key.to_sym => x.id)) end h end @@ -83,16 +82,17 @@ def item_values(klasses, options = {}) query = prepare_query_for_item_values(klass, items, options) query.map do |x| - h = { type: 'statistic', - object: klass.name, - id: x.id, - label: "#{x.quantity}x #{x.label}", - quantity: Integer(x.price), - unit: _('CHF') } + h = { + type: 'statistic', + object: klass.name, + id: x.id, + label: "#{x.quantity}x #{x.label}", + quantity: Integer(x.price), + unit: _('CHF') + } unless klasses.empty? - h[:children] = \ - item_values(klasses, - options.merge(klass.name.foreign_key.to_sym => x.id)) + h[:children] = + item_values(klasses, options.merge(klass.name.foreign_key.to_sym => x.id)) end h end @@ -101,28 +101,29 @@ def item_values(klasses, options = {}) private def prepare_query_for_item_values(klass, items, options) - query = klass.unscoped - .select("#{klass.name.tableize}.id, " \ - 'COUNT(items.id) AS quantity, ' \ - 'SUM(items.price) AS price') - .where(items[:price].gt(0)) - .order('price DESC') - .limit(options[:limit]) + query = + klass.unscoped.select( + "#{klass.name.tableize}.id, " \ + 'COUNT(items.id) AS quantity, ' \ + 'SUM(items.price) AS price' + ) + .where(items[:price].gt(0)) + .order('price DESC') + .limit(options[:limit]) - query = case klass.name - when 'InventoryPool' - query.joins(:own_items) - .group('items.owner_id') - .group('inventory_pools.id') - .select('inventory_pools.name AS label') - when 'Model' - query.joins(:items) - .group("items.#{klass.name.foreign_key}") - .group('models.id') - .select('models.product AS label') - else - raise "#{klass} not supported" - end + query = + case klass.name + when 'InventoryPool' + query.joins(:own_items).group('items.owner_id').group('inventory_pools.id').select( + 'inventory_pools.name AS label' + ) + when 'Model' + query.joins(:items).group("items.#{klass.name.foreign_key}").group('models.id').select( + 'models.product AS label' + ) + else + raise "#{klass} not supported" + end unless options[:inventory_pool_id].blank? query = query.where(items: { owner_id: options[:inventory_pool_id] }) @@ -131,53 +132,50 @@ def prepare_query_for_item_values(klass, items, options) query = query.where(items: { model_id: options[:model_id] }) end unless options[:start_date].blank? - query = \ - query.where \ - items[:created_at].gteq \ - Date.parse(options[:start_date]).to_s(:db) + query = query.where items[:created_at].gteq Date.parse(options[:start_date]).to_s(:db) end unless options[:end_date].blank? - query = query.where \ - items[:created_at].lteq \ - Date.parse(options[:end_date]).to_s(:db) + query = query.where items[:created_at].lteq Date.parse(options[:end_date]).to_s(:db) end query end def get_query_for_contracts(klass, reservations, options) - query = klass.unscoped - .select("#{klass.name.tableize}.id, " \ - 'COUNT(DISTINCT contracts.id) AS quantity') - .where(reservations: { status: [:signed, :closed] }) - .order('quantity DESC') - .limit(options[:limit]) + query = + klass.unscoped.select( + "#{klass.name.tableize}.id, " \ + 'COUNT(DISTINCT contracts.id) AS quantity' + ) + .where(reservations: { status: [:signed, :closed] }) + .order('quantity DESC') + .limit(options[:limit]) - query = case klass.name - when 'User' - query.joins(reservations: :contract) - .group("reservations.#{klass.name.foreign_key}") - .group('users.id') - .select(<<~SQL) - CONCAT_WS(' ', + query = + case klass.name + when 'User' + query.joins(reservations: :contract).group("reservations.#{klass.name.foreign_key}") + .group('users.id') + .select( + <<~SQL + CONCAT_WS(' ', users.firstname, users.lastname) AS label, delegator_user_id SQL - when 'InventoryPool' - query.joins(reservations: :contract) - .group('inventory_pools.id') - .select('inventory_pools.name AS label') - else - raise "#{klass} not supported" - end + ) + when 'InventoryPool' + query.joins(reservations: :contract).group('inventory_pools.id').select( + 'inventory_pools.name AS label' + ) + else + raise "#{klass} not supported" + end unless options[:user_id].blank? query = query.where(reservations: { user_id: options[:user_id] }) end unless options[:inventory_pool_id].blank? - query = \ - query.where(reservations: \ - { inventory_pool_id: options[:inventory_pool_id] }) + query = query.where(reservations: { inventory_pool_id: options[:inventory_pool_id] }) end unless options[:model_id].blank? query = query.where(reservations: { model_id: options[:model_id] }) @@ -186,25 +184,24 @@ def get_query_for_contracts(klass, reservations, options) query = query.where(reservations: { item_id: options[:item_id] }) end unless options[:start_date].blank? - query = \ - query.where \ - reservations[:start_date].gteq \ - Date.parse(options[:start_date]).to_s(:db) + query = + query.where reservations[:start_date].gteq Date.parse(options[:start_date]).to_s(:db) end unless options[:end_date].blank? - query.where \ - reservations[:returned_date].lteq \ - Date.parse(options[:end_date]).to_s(:db) + query.where reservations[:returned_date].lteq Date.parse(options[:end_date]).to_s(:db) end end def get_initial_query_for_hand_overs(klass, reservations, options) - klass.unscoped - .select("#{klass.name.tableize}.id, " \ - 'SUM(reservations.quantity) AS quantity') - .where(reservations[:type].eq('ItemLine') - .and(reservations[:item_id].not_eq(nil)) - .and(reservations[:returned_date].not_eq(nil))) + klass.unscoped.select( + "#{klass.name.tableize}.id, " \ + 'SUM(reservations.quantity) AS quantity' + ) + .where( + reservations[:type].eq('ItemLine').and(reservations[:item_id].not_eq(nil)).and( + reservations[:returned_date].not_eq(nil) + ) + ) .order('quantity DESC') .limit(options[:limit]) end @@ -217,10 +214,7 @@ def get_query_for_hand_overs(klass, reservations, options) query = query.where(reservations: { user_id: options[:user_id] }) end unless options[:inventory_pool_id].blank? - query = \ - query - .where(reservations: \ - { inventory_pool_id: options[:inventory_pool_id] }) + query = query.where(reservations: { inventory_pool_id: options[:inventory_pool_id] }) end unless options[:model_id].blank? query = query.where(reservations: { model_id: options[:model_id] }) @@ -229,52 +223,54 @@ def get_query_for_hand_overs(klass, reservations, options) query = query.where(reservations: { item_id: options[:item_id] }) end unless options[:start_date].blank? - query = \ - query.where \ - reservations[:start_date].gteq \ - Date.parse(options[:start_date]).to_s(:db) + query = + query.where reservations[:start_date].gteq Date.parse(options[:start_date]).to_s(:db) end unless options[:end_date].blank? - query.where \ - reservations[:returned_date].lteq \ - Date.parse(options[:end_date]).to_s(:db) + query.where reservations[:returned_date].lteq Date.parse(options[:end_date]).to_s(:db) end end def extend_query_for_hand_overs(query, klass) case klass.name when 'User' - query.joins(:reservations) - .group('users.id') - .group("reservations.#{klass.name.foreign_key}") - .select("CONCAT_WS(' ', " \ - 'users.firstname, ' \ - 'users.lastname) AS label, ' \ - 'delegator_user_id') + query.joins(:reservations).group('users.id').group( + "reservations.#{klass.name.foreign_key}" + ) + .select( + "CONCAT_WS(' ', " \ + 'users.firstname, ' \ + 'users.lastname) AS label, ' \ + 'delegator_user_id' + ) when 'InventoryPool' - query.joins(:reservations) - .group('inventory_pools.id') - .select('inventory_pools.name AS label') + query.joins(:reservations).group('inventory_pools.id').select( + 'inventory_pools.name AS label' + ) when 'Model' - query.joins(:reservations) - .group('models.id') - .group("reservations.#{klass.name.foreign_key}") - .select("CONCAT_WS(' ', " \ - 'models.manufacturer, ' \ - 'models.product, ' \ - 'models.version) AS label') + query.joins(:reservations).group('models.id').group( + "reservations.#{klass.name.foreign_key}" + ) + .select( + "CONCAT_WS(' ', " \ + 'models.manufacturer, ' \ + 'models.product, ' \ + 'models.version) AS label' + ) when 'Item' - query.joins(item_lines: :model) - .group('items.id') - .group("reservations.#{klass.name.foreign_key}") + query.joins(item_lines: :model).group('items.id').group( + "reservations.#{klass.name.foreign_key}" + ) .group('models.manufacturer') .group('models.product') .group('models.version') - .select("CONCAT_WS(' ', " \ - 'items.inventory_code, ' \ - 'models.manufacturer, ' \ - 'models.product, ' \ - 'models.version) AS label') + .select( + "CONCAT_WS(' ', " \ + 'items.inventory_code, ' \ + 'models.manufacturer, ' \ + 'models.product, ' \ + 'models.version) AS label' + ) else raise "#{klass} not supported" end diff --git a/app/models/supplier.rb b/app/models/supplier.rb index 7104eb7ec8..172eb29867 100644 --- a/app/models/supplier.rb +++ b/app/models/supplier.rb @@ -17,23 +17,22 @@ def label_for_audits def self.filter(search_term: nil, pool_id: nil) suppliers = search(search_term).order(:name) if pool_id.present? - suppliers = suppliers.joins(:items) - .where('items.inventory_pool_id': pool_id).distinct + suppliers = suppliers.joins(:items).where(:"items.inventory_pool_id" => pool_id).distinct end # FIXME: not used? # suppliers = suppliers.where(id: params[:ids]) if params[:ids] suppliers end - scope :search, lambda { |query| - sql = all - return sql if query.blank? - - query.split.each do |q| - q = "%#{q}%" - sql = sql.where(arel_table[:name].matches(q)) - end - sql - } - + scope :search, + lambda do |query| + sql = all + return sql if query.blank? + + query.split.each do |q| + q = "%#{q}%" + sql = sql.where(arel_table[:name].matches(q)) + end + sql + end end diff --git a/app/models/template.rb b/app/models/template.rb index d260a2f205..7baf0f106e 100644 --- a/app/models/template.rb +++ b/app/models/template.rb @@ -6,17 +6,12 @@ class Template < ModelGroup # TODO 12** validates all models are present to current inventory_pool # TODO 12** has_many :models through - after_save do - raise _('Template must have at least one model') if model_links.blank? - end + after_save { raise _('Template must have at least one model') if model_links.blank? } def self.filter(params, inventory_pool) templates = inventory_pool.templates - unless params[:search_term].blank? - templates = templates.search(params[:search_term]) - end - templates = \ - templates.order("#{params[:sort] || 'name'} #{params[:order] || 'ASC'}") + templates = templates.search(params[:search_term]) unless params[:search_term].blank? + templates = templates.order("#{params[:sort] || 'name'} #{params[:order] || 'ASC'}") templates = templates.default_paginate params templates end @@ -24,19 +19,9 @@ def self.filter(params, inventory_pool) ################################################################################ # returns an array of reservations - def add_to_contract(contract, - user, - _quantity = nil, - start_date = nil, - end_date = nil, - delegated_user_id = nil) + def add_to_contract(contract, user, _quantity = nil, start_date = nil, end_date = nil, delegated_user_id = nil) model_links.flat_map do |ml| - ml.model.add_to_contract(contract, - user, - ml.quantity, - start_date, - end_date, - delegated_user_id) + ml.model.add_to_contract(contract, user, ml.quantity, start_date, end_date, delegated_user_id) end end @@ -51,7 +36,7 @@ def accomplishable?(user = nil) def unaccomplishable_models(user = nil, quantity = nil) models.to_a.keep_if do |model| q = quantity || model_links.detect { |l| l.model_id == model.id }.quantity - not inventory_pools.any? do |ip| + ninventory_pools.any? do |ip| if user model.total_borrowable_items_for_user_and_pool(user, ip) >= q else diff --git a/app/models/user.rb b/app/models/user.rb index 0b69a2404c..6019991987 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -8,9 +8,7 @@ class User < ApplicationRecord # not as general validation because of first admin user # feature (only email and password) if delegation? - unless firstname - raise "Firstname can't be blank" - end + raise "Firstname can't be blank" unless firstname elsif !firstname or !lastname or !email raise "Firstname and lastname can't be blank" end @@ -19,20 +17,20 @@ class User < ApplicationRecord serialize :extended_info serialize :settings - store_accessor :settings, [:latest_inventory_pool_id_before_logout, - :start_screen] + store_accessor :settings, [:latest_inventory_pool_id_before_logout, :start_screen] belongs_to :language has_many :orders has_many :access_rights, dependent: :restrict_with_exception - has_many(:inventory_pools, - -> { where(access_rights: { deleted_at: nil }).distinct }, - through: :access_rights) do + has_many( + :inventory_pools, + -> { where(access_rights: { deleted_at: nil }).distinct }, + through: :access_rights + ) do def with_borrowable_items - joins(:items) - .where(items: { retired: nil, is_borrowable: true, parent_id: nil }) + joins(:items).where(items: { retired: nil, is_borrowable: true, parent_id: nil }) end # get the inventory pools managed by the current user @@ -44,42 +42,43 @@ def managed(role = [:inventory_manager, :lending_manager, :group_manager]) has_many :items, -> { distinct }, through: :inventory_pools has_many(:models, -> { distinct }, through: :inventory_pools) do def borrowable - joins(:items) - .where(items: { retired: nil, is_borrowable: true, parent_id: nil }) - .joins("INNER JOIN (#{Entitlement.query}) AS pwg " \ - 'ON models.id = pwg.model_id ' \ - 'AND inventory_pools.id = pwg.inventory_pool_id ' \ - 'AND pwg.quantity > 0 ' \ - 'AND (pwg.entitlement_group_id IN ' \ - '(SELECT entitlement_group_id FROM entitlement_groups_users ' \ - "WHERE user_id = '#{proxy_association.owner.id}') " \ - 'OR pwg.entitlement_group_id IS NULL)') + joins(:items).where(items: { retired: nil, is_borrowable: true, parent_id: nil }).joins( + "INNER JOIN (#{Entitlement.query}) AS pwg " \ + 'ON models.id = pwg.model_id ' \ + 'AND inventory_pools.id = pwg.inventory_pool_id ' \ + 'AND pwg.quantity > 0 ' \ + 'AND (pwg.entitlement_group_id IN ' \ + '(SELECT entitlement_group_id FROM entitlement_groups_users ' \ + "WHERE user_id = '#{proxy_association.owner.id}') " \ + 'OR pwg.entitlement_group_id IS NULL)' + ) end end has_many(:categories, -> { distinct }, through: :models) do def with_borrowable_items - where(items: { retired: nil, is_borrowable: true, parent_id: nil }) - .joins("INNER JOIN (#{Entitlement.query}) AS pwg " \ - 'ON models.id = pwg.model_id ' \ - 'AND inventory_pools.id = pwg.inventory_pool_id ' \ - 'AND pwg.quantity > 0 ' \ - 'AND (pwg.entitlement_group_id IN ' \ - '(SELECT entitlement_group_id FROM entitlement_groups_users ' \ - "WHERE user_id = '#{proxy_association.owner.id}') " \ - 'OR pwg.entitlement_group_id IS NULL)') + where(items: { retired: nil, is_borrowable: true, parent_id: nil }).joins( + "INNER JOIN (#{Entitlement.query}) AS pwg " \ + 'ON models.id = pwg.model_id ' \ + 'AND inventory_pools.id = pwg.inventory_pool_id ' \ + 'AND pwg.quantity > 0 ' \ + 'AND (pwg.entitlement_group_id IN ' \ + '(SELECT entitlement_group_id FROM entitlement_groups_users ' \ + "WHERE user_id = '#{proxy_association.owner.id}') " \ + 'OR pwg.entitlement_group_id IS NULL)' + ) end end def all_categories borrowable_categories = categories.with_borrowable_items - ancestors = \ - Category \ - .joins('INNER JOIN model_group_links ' \ - 'ON model_groups.id = model_group_links.parent_id') - .where(model_group_links: \ - { child_id: borrowable_categories.pluck(:id) }) + ancestors = + Category.joins( + 'INNER JOIN model_group_links ' \ + 'ON model_groups.id = model_group_links.parent_id' + ) + .where(model_group_links: { child_id: borrowable_categories.pluck(:id) }) .distinct [borrowable_categories, ancestors].flatten.uniq @@ -121,47 +120,47 @@ def with_general ################################################ - before_save do - self.language ||= Language.default_language - end + before_save { self.language ||= Language.default_language } ################################################ - SEARCHABLE_FIELDS = %w(login firstname lastname badge_id) + SEARCHABLE_FIELDS = %w[login firstname lastname badge_id] - scope :search, lambda { |query| - sql = all - return sql if query.blank? - sql = sql.distinct.joins(<<-SQL) - LEFT JOIN delegations_users AS du ON du.delegation_id = users.id + scope :search, + lambda do |query| + sql = all + return sql if query.blank? + sql = + sql.distinct.joins( + <<-SQL + LEFT JOIN delegations_users AS du ON du.delegation_id = users.id LEFT JOIN users AS u2 ON du.user_id = u2.id SQL - u2_table = Arel::Table.new(:u2) - - query.split.each do|q| - q = "%#{q}%" - sql = sql.where(arel_table[:login].matches(q) - .or(arel_table[:firstname].matches(q)) - .or(arel_table[:lastname].matches(q)) - .or(arel_table[:badge_id].matches(q)) - .or(arel_table[:org_id].matches(q)) - .or(u2_table[:login].matches(q)) - .or(u2_table[:firstname].matches(q)) - .or(u2_table[:lastname].matches(q)) - .or(u2_table[:badge_id].matches(q)) - .or(u2_table[:org_id].matches(q)) - ) - end - sql - } + ) + u2_table = Arel::Table.new(:u2) + + query.split.each do |q| + q = "%#{q}%" + sql = + sql.where( + arel_table[:login].matches(q).or(arel_table[:firstname].matches(q)).or( + arel_table[:lastname].matches(q) + ) + .or(arel_table[:badge_id].matches(q)) + .or(arel_table[:org_id].matches(q)) + .or(u2_table[:login].matches(q)) + .or(u2_table[:firstname].matches(q)) + .or(u2_table[:lastname].matches(q)) + .or(u2_table[:badge_id].matches(q)) + .or(u2_table[:org_id].matches(q)) + ) + end + sql + end def self.filter(params, inventory_pool = nil) if inventory_pool and params[:all].blank? - users = if params[:suspended] == 'true' - inventory_pool.suspended_users - else - inventory_pool.users - end + users = params[:suspended] == 'true' ? inventory_pool.suspended_users : inventory_pool.users unless params[:delegation_id].blank? users = users.find(params[:delegation_id]).delegated_users end @@ -209,21 +208,16 @@ def short_name if delegation? name else - "#{firstname.presence && firstname[0] + '.'} #{lastname}" - .strip.presence \ - || self.login.to_s.strip.presence \ - || self.email + "#{firstname.presence && firstname[0] + '.'} #{lastname}".strip.presence || + self.login.to_s.strip.presence || + self.email end end ################################################ def email - if delegation? - delegator_user.email - else - read_attribute(:email) - end + delegation? ? delegator_user.email : read_attribute(:email) end def alternative_email @@ -245,43 +239,31 @@ def address ################################################ def self.remind_and_suspend_all - # TODO: dry - grouped_reservations = \ - Visit - .take_back_overdue - .flat_map(&:reservations) - .group_by do |vl| - { inventory_pool: vl.inventory_pool, - user_id: (vl.delegated_user_id || vl.user_id) } - end + grouped_reservations = + Visit.take_back_overdue.flat_map(&:reservations).group_by do |vl| + { inventory_pool: vl.inventory_pool, user_id: (vl.delegated_user_id || vl.user_id) } + end grouped_reservations.each_pair do |k, reservations| user = User.find(k[:user_id]) user.remind(reservations) end # TODO: dry - grouped_reservations = \ - Visit - .take_back_overdue - .flat_map(&:reservations) - .group_by do |vl| - { inventory_pool: vl.inventory_pool, user_id: vl.user_id } - end + grouped_reservations = + Visit.take_back_overdue.flat_map(&:reservations).group_by do |vl| + { inventory_pool: vl.inventory_pool, user_id: vl.user_id } + end grouped_reservations.each_pair do |k, reservations| user = User.find(k[:user_id]) user.automatic_suspend(k[:inventory_pool]) end end + # TODO: dry def self.send_deadline_soon_reminder_to_everybody - grouped_reservations = \ - Visit - .take_back - .where('date = ?', Date.tomorrow) - .flat_map(&:reservations) - .group_by do |vl| - { inventory_pool: vl.inventory_pool, - user_id: (vl.delegated_user_id || vl.user_id) } - end + grouped_reservations = + Visit.take_back.where('date = ?', Date.tomorrow).flat_map(&:reservations).group_by do |vl| + { inventory_pool: vl.inventory_pool, user_id: (vl.delegated_user_id || vl.user_id) } + end grouped_reservations.each_pair do |k, reservations| user = User.find(k[:user_id]) user.send_deadline_soon_reminder(reservations) @@ -289,10 +271,10 @@ def self.send_deadline_soon_reminder_to_everybody end def automatic_suspend(inventory_pool) - if inventory_pool.automatic_suspension? and not suspended?(inventory_pool) - access_right_for(inventory_pool).update_attributes \ - suspended_until: AccessRight::AUTOMATIC_SUSPENSION_DATE, - suspended_reason: inventory_pool.automatic_suspension_reason + if inventory_pool.automatic_suspension? and nsuspended?(inventory_pool) + access_right_for(inventory_pool).update_attributes suspended_until: + AccessRight::AUTOMATIC_SUSPENSION_DATE, + suspended_reason: inventory_pool.automatic_suspension_reason puts "Suspended: #{self.name} on #{inventory_pool} for overdue take back" end end @@ -303,11 +285,13 @@ def remind(reservations) Notification.remind_user(self, reservations) puts "Reminded: #{self.name}" true - rescue Exception => exception - puts "Failed to remind: #{self.name}" + # archive problem in the log, so the admin/developper # can look up what happened - logger.error "#{exception}\n #{exception.backtrace.join("\n ")}" + rescue Exception => exception + puts "Failed to remind: #{self.name}" + + logger.error "#{exception}undefined #{exception.backtrace.join('undefined ')}" false end end @@ -318,7 +302,7 @@ def send_deadline_soon_reminder(reservations, _reminder_user = self) begin Notification.deadline_soon_reminder(self, reservations) puts "Deadline soon: #{self.name}" - rescue + rescue StandardError puts "Couldn't send reminder: #{self.name}" end end @@ -330,17 +314,13 @@ def send_deadline_soon_reminder(reservations, _reminder_user = self) # rubocop:disable Style/PredicateName def has_role?(role, inventory_pool = nil) role = role.to_sym - roles = if inventory_pool - access_rights.where(inventory_pool_id: inventory_pool) - else - access_rights - end.active.collect(&:role) + roles = + inventory_pool ? access_rights.where(inventory_pool_id: inventory_pool) : access_rights.active + .collect(&:role) if AccessRight::ROLES_HIERARCHY.include? role i = AccessRight::ROLES_HIERARCHY.index role - (roles & AccessRight::ROLES_HIERARCHY).any? do |r| - AccessRight::ROLES_HIERARCHY.index(r) >= i - end + (roles & AccessRight::ROLES_HIERARCHY).any? { |r| AccessRight::ROLES_HIERARCHY.index(r) >= i } else roles.include? role end @@ -364,10 +344,9 @@ def deletable? ############################################ def timeout? - reservations - .unsubmitted - .where('updated_at < ?', - Time.zone.now - Setting.first.timeout_minutes.minutes) + reservations.unsubmitted.where( + 'updated_at < ?', Time.zone.now - Setting.first.timeout_minutes.minutes + ) .exists? end end diff --git a/app/models/user_session.rb b/app/models/user_session.rb index 10a6639f6f..04ec4fd65c 100644 --- a/app/models/user_session.rb +++ b/app/models/user_session.rb @@ -3,24 +3,33 @@ class UserSession < ApplicationRecord belongs_to :delegation, foreign_key: :delegation_id, class_name: 'User' def self.find_by_token_base(token) - where(<<-SQL.strip_heredoc, token) - user_sessions.token_hash = encode(digest(?, 'sha256'), 'hex') + where( + <<-SQL + user_sessions.token_hash = encode(digest(?, 'sha256'), 'hex') SQL + .strip_heredoc, + token + ) .joins(:user) .where(users: { account_enabled: true }) end def self.find_by_token(token) - find_by_token_base(token) - .joins(<<-SQL.strip_heredoc) - INNER JOIN settings + find_by_token_base(token).joins( + <<-SQL + INNER JOIN settings ON settings.id = 0 SQL - .where(<<-SQL.strip_heredoc) - now() < + .strip_heredoc + ) + .where( + <<-SQL + now() < user_sessions.created_at + settings.sessions_max_lifetime_secs * interval '1 second' SQL + .strip_heredoc + ) .first end end diff --git a/app/models/visit.rb b/app/models/visit.rb index afc8b486b2..99c8a55790 100644 --- a/app/models/visit.rb +++ b/app/models/visit.rb @@ -17,9 +17,7 @@ def readonly? self.primary_key = 'id' self.inheritance_column = nil - default_scope do - order(:date, :id) - end + default_scope { order(:date, :id) } belongs_to :user belongs_to :inventory_pool @@ -30,84 +28,81 @@ def reservations end ################################################################################# - scope :potential_hand_over, (lambda do - where(type: :hand_over).where(is_approved: false) - end) + scope :potential_hand_over, (lambda { where(type: :hand_over).where(is_approved: false) }) scope :hand_over, -> { where(type: :hand_over).where(is_approved: true) } scope :take_back, -> { where(type: :take_back) } scope :take_back_overdue, -> { take_back.where('date < ?', Time.zone.today) } - scope :search, lambda { |query| - sql = where(is_approved: true) - return sql if query.blank? - - # TODO: search on reservations' models and items - query.split.each do |q| - q = "%#{q}%" - sql = sql.where(User.arel_table[:login].matches(q) - .or(User.arel_table[:firstname].matches(q)) - .or(User.arel_table[:lastname].matches(q)) - .or(User.arel_table[:badge_id].matches(q))) - end - - sql.joins(:user) - } - - scope :filter2, (lambda do |params, inventory_pool = nil| - - visits = if inventory_pool.nil? - all - else - inventory_pool.visits - end.where(is_approved: true) - - if params[:status] - visits = visits.where( - type: case params[:status] - when ['approved', 'signed'] then ['hand_over', 'take_back'] - when 'approved' then 'hand_over' - when 'signed' then 'take_back' + scope :search, + lambda do |query| + sql = where(is_approved: true) + return sql if query.blank? + + # TODO: search on reservations' models and items + query.split.each do |q| + q = "%#{q}%" + sql = + sql.where( + User.arel_table[:login].matches(q).or(User.arel_table[:firstname].matches(q)).or( + User.arel_table[:lastname].matches(q) + ) + .or(User.arel_table[:badge_id].matches(q)) + ) + end + + sql.joins(:user) + end + + scope :filter2, + (lambda do |params, inventory_pool = nil| + visits = inventory_pool.nil? ? all : inventory_pool.visits.where(is_approved: true) + + if params[:status] + visits = + visits.where( + type: + case params[:status] + when ['approved', 'signed'] + ['hand_over', 'take_back'] + when 'approved' + 'hand_over' + when 'signed' + 'take_back' + end + ) + end + + if params[:verification].presence + visits = + case params[:verification] + when 'with_user_to_verify' + visits.where(with_user_to_verify: true) + when 'with_user_and_model_to_verify' + visits.where(with_user_and_model_to_verify: true) + when 'no_verification' + visits.where(with_user_to_verify: false, with_user_and_model_to_verify: false) + else + visits end - ) - end + end - if params[:verification].presence - visits = case params[:verification] - when 'with_user_to_verify' - visits.where(with_user_to_verify: true) - when 'with_user_and_model_to_verify' - visits.where(with_user_and_model_to_verify: true) - when 'no_verification' - visits.where(with_user_to_verify: false, - with_user_and_model_to_verify: false) - else - visits - end - end + visits = visits.search(params[:search_term]) unless params[:search_term].blank? - unless params[:search_term].blank? - visits = visits.search(params[:search_term]) - end + if params[:date] and params[:date_comparison] == 'lteq' + visits = visits.where arel_table[:date].lteq(params[:date]) + end - if params[:date] and params[:date_comparison] == 'lteq' - visits = visits.where arel_table[:date].lteq(params[:date]) - end + if params[:date] and params[:date_comparison] == 'eq' + visits = visits.where arel_table[:date].eq(params[:date]) + end - if params[:date] and params[:date_comparison] == 'eq' - visits = visits.where arel_table[:date].eq(params[:date]) - end + if r = params[:range] + visits = visits.where(arel_table[:date].gteq(r[:start_date])) if r[:start_date].presence + visits = visits.where(arel_table[:date].lteq(r[:end_date])) if r[:end_date].presence + end - if r = params[:range] - if r[:start_date].presence - visits = visits.where(arel_table[:date].gteq(r[:start_date])) - end - if r[:end_date].presence - visits = visits.where(arel_table[:date].lteq(r[:end_date])) - end - end - - visits - end) + visits + end) def self.total_count_for_paginate scope_sql = Visit.all.reorder(nil).to_sql @@ -124,9 +119,12 @@ def action def status case [self.type.to_sym, self.is_approved?] - when [:hand_over, false] then :submitted - when [:hand_over, true] then :approved - when [:take_back, true] then :signed + when [:hand_over, false] + :submitted + when [:hand_over, true] + :approved + when [:take_back, true] + :signed end end @@ -137,5 +135,4 @@ def visit_as_json ################################################################################# ################################################################################# ################################################################################# - end diff --git a/app/models/workday.rb b/app/models/workday.rb index 91cdda8a69..3735dad984 100644 --- a/app/models/workday.rb +++ b/app/models/workday.rb @@ -6,10 +6,10 @@ class Workday < ApplicationRecord serialize :max_visits, Hash # deprecated - DAYS = %w(monday tuesday wednesday thursday friday saturday sunday) + DAYS = %w[monday tuesday wednesday thursday friday saturday sunday] # better - WORKDAYS = %w(sunday monday tuesday wednesday thursday friday saturday) + WORKDAYS = %w[sunday monday tuesday wednesday thursday friday saturday] def open_on?(date) return false if date.nil? @@ -28,9 +28,9 @@ def open_on?(date) when 6 return saturday when 0 - return sunday + return sunday # Should not be reached else - return false # Should not be reached + return false end end @@ -48,14 +48,9 @@ def closed_days def workdays=(wdays) wdays.each_pair do |k, v| - write_attribute(WORKDAYS[Integer(k.presence || 0)], - Integer(v['open'].presence || 0)) - max_visits[Integer(k.presence || 0)] = \ - if v['max_visits'].blank? - nil - else - Integer(v['max_visits'].presence || 0) - end + write_attribute(WORKDAYS[Integer(k.presence || 0)], Integer(v['open'].presence || 0)) + max_visits[Integer(k.presence || 0)] = + v['max_visits'].blank? ? nil : Integer(v['max_visits'].presence || 0) end end @@ -70,9 +65,7 @@ def total_visits_by_date def reached_max_visits dates = [] total_visits_by_date.each_pair do |date, visits| - next if date.past? \ - or max_visits_on(date.wday).nil? \ - or visits.size < max_visits_on(date.wday) + next if date.past? or max_visits_on(date.wday).nil? or visits.size < max_visits_on(date.wday) dates << date end dates.sort @@ -81,5 +74,4 @@ def reached_max_visits def label_for_audits "#{_('Workdays')} #{inventory_pool}" end - end diff --git a/app/presenters/application_record_presenter.rb b/app/presenters/application_record_presenter.rb index 07f97dacd5..c4216de9bb 100644 --- a/app/presenters/application_record_presenter.rb +++ b/app/presenters/application_record_presenter.rb @@ -35,7 +35,7 @@ def self.delegate_to(inst_var, *args) end # pundit helpers (if library is used) - if defined? Pundit + if defined?(Pundit) include Pundit def policy_for(user) diff --git a/app/presenters/borrow/booking_calendar.rb b/app/presenters/borrow/booking_calendar.rb index b2458e6574..430b21793d 100644 --- a/app/presenters/borrow/booking_calendar.rb +++ b/app/presenters/borrow/booking_calendar.rb @@ -1,7 +1,5 @@ class Borrow::BookingCalendar < ApplicationPresenter - def initialize( - inventory_pool, model, user, start_date_string, end_date_string, reservations - ) + def initialize(inventory_pool, model, user, start_date_string, end_date_string, reservations) @inventory_pool = inventory_pool @model = model @user = user @@ -11,15 +9,12 @@ def initialize( @end_date_string = end_date_string @end_date = Date.parse(@end_date_string) @group_ids = user.entitlement_groups.map(&:id) - @availability = \ - @model.availability_in(@inventory_pool, exclude_reservations: @reservations) + @availability = @model.availability_in(@inventory_pool, exclude_reservations: @reservations) @changes = @availability.changes.to_a.sort_by(&:first) @init_date = @start_date - 1.day - @total_borrowable_quantity = \ + @total_borrowable_quantity = @model.total_borrowable_items_for_user_and_pool( - @user, - @inventory_pool, - ensure_non_negative_general: true + @user, @inventory_pool, ensure_non_negative_general: true ) @availabilities_per_day = availabilities_per_day @total_borrowable_quantities_per_day = total_borrowable_quantities_per_day @@ -27,10 +22,8 @@ def initialize( end def list - @total_borrowable_quantities_per_day.map.with_index \ - do |total_borrow_qty_per_day, i| - quantity = \ - (@availabilities_per_day[i] or total_borrow_qty_per_day)[:quantity] + @total_borrowable_quantities_per_day.map.with_index do |total_borrow_qty_per_day, i| + quantity = (@availabilities_per_day[i] or total_borrow_qty_per_day)[:quantity] @visits_per_day[i].merge(quantity: quantity) end end @@ -38,33 +31,29 @@ def list private def total_borrowable_quantities_per_day - (@start_date..@end_date).map do |d| - { d: d, quantity: @total_borrowable_quantity } - end + (@start_date..@end_date).map { |d| { d: d, quantity: @total_borrowable_quantity } } end def availabilities_per_day - result = @changes.drop(1).reduce([[@init_date, 0]]) do |memo, obj| - s_date = memo.last.first + 1.day - e_date = obj.first - 1.day - qty = \ - @availability - .maximum_available_in_period_summed_for_groups(s_date, - e_date, - @group_ids) - new_dates = (s_date..e_date).map { |d| [d, qty] } - memo + new_dates - end + result = + @changes.drop(1).reduce([[@init_date, 0]]) do |memo, obj| + s_date = memo.last.first + 1.day + e_date = obj.first - 1.day + qty = + @availability.maximum_available_in_period_summed_for_groups(s_date, e_date, @group_ids) + new_dates = (s_date..e_date).map { |d| [d, qty] } + memo + new_dates + end result.shift(1) result.map { |fst, snd| { d: fst, quantity: snd } } end def visits_per_day - BookingCalendarVisitsQuery - .new(inventory_pool_id: @inventory_pool.id, - start_date: @start_date_string, - end_date: @end_date_string) + BookingCalendarVisitsQuery.new( + inventory_pool_id: @inventory_pool.id, + start_date: @start_date_string, + end_date: @end_date_string + ) .run end - end diff --git a/app/queries/booking_calendar_visits_query.rb b/app/queries/booking_calendar_visits_query.rb index 5d636a7ebe..e1da9facf3 100644 --- a/app/queries/booking_calendar_visits_query.rb +++ b/app/queries/booking_calendar_visits_query.rb @@ -3,9 +3,8 @@ class BookingCalendarVisitsQuery def initialize(inventory_pool_id:, start_date:, end_date:) # TODO: UUID check!!! - @query = \ - <<-SQL - WITH dates AS + @query = <<-SQL + WITH dates AS (SELECT d::date FROM generate_series('#{start_date}'::date, '#{end_date}'::date, diff --git a/app/validators/email_validator.rb b/app/validators/email_validator.rb index 709086a2d4..b2ecf9677c 100644 --- a/app/validators/email_validator.rb +++ b/app/validators/email_validator.rb @@ -1,15 +1,9 @@ class EmailValidator < ActiveModel::EachValidator def validate_each(record, _attribute, value) unless value.to_s.empty? # email can be blank - - # validate email syntax - valid = if value.match?(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i) - true - else - false - end + valid = value.match?(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/) ? true : false record.errors.add("#{value} is not a valid email address") unless valid - end + # validate email syntax end end diff --git a/cider-ci/bin/check-rails-warnings.rb b/cider-ci/bin/check-rails-warnings.rb index 4e1a4ca373..8373b70837 100755 --- a/cider-ci/bin/check-rails-warnings.rb +++ b/cider-ci/bin/check-rails-warnings.rb @@ -1,12 +1,4 @@ #!/usr/bin/env bash set -eu -export PATH=~/.rubies/$RUBY/bin:$PATH - -RAILS_ENV=test bundle exec rails runner '' - -if [ $(RAILS_ENV=test bundle exec rails runner '' 2>&1 | wc -l) -gt 0 ]; then - exit 1; -else - exit 0; -fi +export PATH =~ /.rubies/ diff --git a/cider-ci/bin/create-feature-tasks.rb b/cider-ci/bin/create-feature-tasks.rb index b622bb955c..afe78747cd 100644 --- a/cider-ci/bin/create-feature-tasks.rb +++ b/cider-ci/bin/create-feature-tasks.rb @@ -6,36 +6,40 @@ ENGINES = ['leihs_admin'] def task_hash(name, exec) - h = { 'name' => name, - 'scripts' => { - 'test' => { - 'body' => "set -eux\nexport PATH=~/.rubies/$RUBY/bin:$PATH\nmkdir -p log\n#{exec}" - } - } + h = { + 'name' => name, + 'scripts' => { + 'test' => { + 'body' => + "set -euxundefinedexport PATH=~/.rubies/$RUBY/bin:$PATHundefinedmkdir -p logundefined#{exec}" } + } + } h end -def task_for_feature_file file_path, _timeout = 200 - name= file_path.match(/features\/(.*)\.feature/).captures.first - exec = %{DISPLAY=\":$XVNC_PORT\" bundle exec cucumber -p default #{STRICT_MODE ? "--strict " : nil}"#{file_path}"} +def task_for_feature_file(file_path, _timeout = 200) + name = file_path.match(%r{features\/(.*)\.feature}).captures.first + exec = + "DISPLAY=undefined:$XVNC_PORTundefined bundle exec cucumber -p default #{if STRICT_MODE + '--strict ' + else + nil + end}\"#{file_path}\"" task_hash(name, exec) end def create_feature_tasks(filepath, feature_files) - File.open(filepath,'w') do |f| - string = {'tasks' => feature_files.map do |f| - task_for_feature_file(f) - end} + File.open(filepath, 'w') do |f| + string = { 'tasks' => feature_files.map { |f| task_for_feature_file(f) } } f.write(string.to_yaml) end end -leihs_feature_files = \ - Dir.glob('features/**/*.feature') - - Dir.glob('features/personas/*.feature') - - Dir.glob('features/**/*.feature.disabled') - - Dir.glob('engines/**/features/*') +leihs_feature_files = + Dir.glob('features/**/*.feature') - Dir.glob('features/personas/*.feature') - + Dir.glob('features/**/*.feature.disabled') - + Dir.glob('engines/**/features/*') filepath = 'cider-ci/tasks/all-features.yml' create_feature_tasks(filepath, leihs_feature_files) diff --git a/cider-ci/bin/create-scenario-tasks.rb b/cider-ci/bin/create-scenario-tasks.rb index 4e41952eea..e312c1b830 100755 --- a/cider-ci/bin/create-scenario-tasks.rb +++ b/cider-ci/bin/create-scenario-tasks.rb @@ -3,51 +3,38 @@ STRICT_MODE = true ENGINES = ['leihs_admin'] -EXCLUDE_TAGS = %w(@manual - @broken - @flapping - @unstable) +EXCLUDE_TAGS = %w[@manual @broken @flapping @unstable] def task_hash(name, exec) - { 'name' => name, - 'scripts' => { - 'test' => { - 'body' => "set -eux\nexport PATH=~/.rubies/$RUBY/bin:$PATH\nmkdir -p log\n#{exec}" + { + 'name' => name, + 'scripts' => { + 'test' => { + 'body' => + "set -euxundefinedexport PATH=~/.rubies/$RUBY/bin:$PATHundefinedmkdir -p logundefined#{exec}" } } } end def empty_task_hash - { 'name' => 'No Tasks for this Job!', - 'scripts' => { 'test' => { 'body' => 'echo OK' } } - } + { 'name' => 'No Tasks for this Job!', 'scripts' => { 'test' => { 'body' => 'echo OK' } } } end -def create_scenario_tasks(filepath, - feature_dir_paths, - framework: nil, - additional_options: nil, - tags: nil) - File.open(filepath,'w') do |f| +def create_scenario_tasks(filepath, feature_dir_paths, framework: nil, additional_options: nil, tags: nil) + File.open(filepath, 'w') do |f| tasks = [] - egrep_cmd = \ - "egrep -R -n -B 1 -H '^\s*(Scenario|Szenario)' #{feature_dir_paths.join(' ')}" + egrep_cmd = + "egrep -R -n -B 1 -H '^undefined*(Scenario|Szenario)' #{feature_dir_paths.join(' ')}" - `#{egrep_cmd}` - .split("--\n") - .map { |x| x.split("\n") } - .sort { |a, b| a.first <=> b.first } + `#{egrep_cmd}`.split('--undefined').map { |x| x.split('undefined') }.sort do |a, b| + a.first <=> b.first + end .each do |t, s| + next if tags and nt.match /#{tags.join('|')}/ - if tags and not t.match /#{tags.join("|")}/ - next - end - - if not tags and t.match /#{EXCLUDE_TAGS.join("|")}/ - next - end + next if ntags and t.match /#{EXCLUDE_TAGS.join('|')}/ path = get_path(s) exec = get_exec_command(path, framework, additional_options) @@ -55,22 +42,19 @@ def create_scenario_tasks(filepath, tasks << task_hash(path, exec).merge(task_extensions) end - result = {'tasks' => tasks.any? ? tasks : [empty_task_hash]} + result = { 'tasks' => tasks.any? ? tasks : [empty_task_hash] } f.write result.to_yaml end end def get_task_extensions(t) task_hash_extension = {} - if m = t.match(/@eager_trials_(\d+)/) - task_hash_extension['eager_trials'] = m[1].to_i - end + task_hash_extension['eager_trials'] = m[1].to_i if m = t.match(/@eager_trials_(\d+)/) task_hash_extension end def get_path(s) - splitted_string = \ - s.split(/:\s*(Scenario|Szenario)( Outline| Template|grundriss)?: /) + splitted_string = s.split(/:\s*(Scenario|Szenario)( Outline| Template|grundriss)?: /) k, v = splitted_string.first.split(':') "#{k}:#{v}" end @@ -80,7 +64,7 @@ def get_exec_command(path, framework, additional_options) case framework when :cucumber - exec = "#{xvfb} bundle exec cucumber #{STRICT_MODE ? "--strict " : nil}#{path}" + exec = "#{xvfb} bundle exec cucumber #{STRICT_MODE ? '--strict ' : nil}#{path}" when :rspec exec = [xvfb, 'bundle exec rspec', additional_options, path].compact.join(' ') else @@ -95,24 +79,24 @@ def get_exec_command(path, framework, additional_options) filepath = 'cider-ci/tasks/manage-scenarios.yml' create_scenario_tasks(filepath, manage_feature_dir_paths, framework: :cucumber) -%w(flapping broken unstable).each do |kind| +%w[flapping broken unstable].each do |kind| filepath = "cider-ci/tasks/manage-#{kind}-scenarios.yml" - create_scenario_tasks(filepath, manage_feature_dir_paths, framework: :cucumber, tags: ["@#{kind}"]) + create_scenario_tasks( + filepath, manage_feature_dir_paths, framework: :cucumber, tags: ["@#{kind}"] + ) end +filepath = 'cider-ci/tasks/manage-rspec-scenarios.yml' +create_scenario_tasks( + filepath, ['spec/features/manage'], + framework: :rspec, additional_options: '-r ./spec/steps/manage/load.rb' +) -filepath = "cider-ci/tasks/manage-rspec-scenarios.yml" -create_scenario_tasks(filepath, - ['spec/features/manage'], - framework: :rspec, - additional_options: "-r ./spec/steps/manage/load.rb") - -filepath = "cider-ci/tasks/manage-rspec-flapping-scenarios.yml" -create_scenario_tasks(filepath, - ['spec/features/manage'], - framework: :rspec, - additional_options: "-r ./spec/steps/manage/load.rb", - tags: ['@flapping']) +filepath = 'cider-ci/tasks/manage-rspec-flapping-scenarios.yml' +create_scenario_tasks( + filepath, ['spec/features/manage'], + framework: :rspec, additional_options: '-r ./spec/steps/manage/load.rb', tags: ['@flapping'] +) ############################## BORROW ################################### @@ -121,31 +105,32 @@ def get_exec_command(path, framework, additional_options) filepath = 'cider-ci/tasks/borrow-scenarios.yml' create_scenario_tasks(filepath, borrow_feature_dir_paths, framework: :cucumber) -%w(flapping broken unstable).each do |kind| +%w[flapping broken unstable].each do |kind| filepath = "cider-ci/tasks/borrow-#{kind}-scenarios.yml" - create_scenario_tasks(filepath, borrow_feature_dir_paths, framework: :cucumber, tags: ["@#{kind}"]) + create_scenario_tasks( + filepath, borrow_feature_dir_paths, framework: :cucumber, tags: ["@#{kind}"] + ) end -filepath = "cider-ci/tasks/borrow-rspec-scenarios.yml" -create_scenario_tasks(filepath, - ['spec/features/borrow'], - framework: :rspec, - additional_options: "-r ./spec/steps/borrow/load.rb") +filepath = 'cider-ci/tasks/borrow-rspec-scenarios.yml' +create_scenario_tasks( + filepath, ['spec/features/borrow'], + framework: :rspec, additional_options: '-r ./spec/steps/borrow/load.rb' +) -filepath = "cider-ci/tasks/borrow-rspec-flapping-scenarios.yml" -create_scenario_tasks(filepath, - ['spec/features/borrow'], - framework: :rspec, - additional_options: "-r ./spec/steps/borrow/load.rb", - tags: ['@flapping']) +filepath = 'cider-ci/tasks/borrow-rspec-flapping-scenarios.yml' +create_scenario_tasks( + filepath, ['spec/features/borrow'], + framework: :rspec, additional_options: '-r ./spec/steps/borrow/load.rb', tags: ['@flapping'] +) ############################## INTEGRATION ############################## -filepath = "cider-ci/tasks/integration-rspec-scenarios.yml" -create_scenario_tasks(filepath, - ['spec/features/integration'], - framework: :rspec, - additional_options: "-r ./spec/steps/integration/load.rb") +filepath = 'cider-ci/tasks/integration-rspec-scenarios.yml' +create_scenario_tasks( + filepath, ['spec/features/integration'], + framework: :rspec, additional_options: '-r ./spec/steps/integration/load.rb' +) ############################## ENGINES ################################## @@ -153,24 +138,27 @@ def get_exec_command(path, framework, additional_options) engine_feature_dir_paths = ["engines/#{engine}/spec/features"] filepath = "cider-ci/tasks/#{engine}-scenarios.yml" - create_scenario_tasks(filepath, - engine_feature_dir_paths, - framework: :rspec, - additional_options: "-r ./engines/#{engine}/spec/load.rb") + create_scenario_tasks( + filepath, + engine_feature_dir_paths, + framework: :rspec, additional_options: "-r ./engines/#{engine}/spec/load.rb" + ) filepath = "cider-ci/tasks/#{engine}-flapping-scenarios.yml" - create_scenario_tasks(filepath, - engine_feature_dir_paths, - framework: :rspec, - additional_options: "-r ./engines/#{engine}/spec/load.rb", - tags: ['@flapping']) + create_scenario_tasks( + filepath, + engine_feature_dir_paths, + framework: :rspec, + additional_options: "-r ./engines/#{engine}/spec/load.rb", + tags: ['@flapping'] + ) filepath = "cider-ci/tasks/#{engine}-broken-scenarios.yml" - create_scenario_tasks(filepath, - engine_feature_dir_paths, - framework: :rspec, - additional_options: "-r ./engines/#{engine}/spec/load.rb", - tags: ['@broken']) + create_scenario_tasks( + filepath, + engine_feature_dir_paths, + framework: :rspec, additional_options: "-r ./engines/#{engine}/spec/load.rb", tags: ['@broken'] + ) end ############################## HOTSPOTS ################################# diff --git a/config/application.rb b/config/application.rb index 096dad21dc..87647a8fdb 100644 --- a/config/application.rb +++ b/config/application.rb @@ -36,7 +36,7 @@ class Application < Rails::Application end # Configure the default encoding used in templates for Ruby 1.9. - config.encoding = "utf-8" + config.encoding = 'utf-8' config.active_record.schema_format = :sql config.active_record.timestamped_migrations = false diff --git a/config/environments/development.rb b/config/environments/development.rb index 3a8ed2ddcc..5d7301790a 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -10,7 +10,7 @@ config.eager_load = false # Show full error reports and disable caching. - config.consider_all_requests_local = true + config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. diff --git a/config/environments/migrations.rb b/config/environments/migrations.rb index ce0943f338..64e56be4b6 100644 --- a/config/environments/migrations.rb +++ b/config/environments/migrations.rb @@ -1,16 +1,16 @@ Leihs::Application.configure do # Settings specified here will take precedence over those in config/environment.rb - + # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false - + # Show full error reports and disable caching config.consider_all_requests_local = true - config.action_controller.perform_caching = false + config.action_controller.perform_caching = false #deprecated# config.action_view.cache_template_extensions = false - + # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false end diff --git a/config/environments/production.rb b/config/environments/production.rb index 4c00e8a208..7d6a94eb7b 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -15,7 +15,7 @@ config.eager_load = true # Full error reports are disabled and caching is turned on. - config.consider_all_requests_local = false + config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application @@ -26,8 +26,8 @@ # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. - config.public_file_server.enabled = \ - (YAML.load(ENV['RAILS_SERVE_STATIC_FILES'].presence || "no") == true) + config.public_file_server.enabled = + (YAML.load(ENV['RAILS_SERVE_STATIC_FILES'].presence || 'no') == true) # Compress JavaScripts and CSS. # NOTE: 'mangle: true' option makes the build non-reproducible! @@ -85,6 +85,6 @@ # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false - config.action_mailer.perform_deliveries = \ - (YAML.load(ENV['LEIHS_SEND_MAILS'].presence || "no") == true) + config.action_mailer.perform_deliveries = + (YAML.load(ENV['LEIHS_SEND_MAILS'].presence || 'no') == true) end diff --git a/config/environments/profiling.rb b/config/environments/profiling.rb index ed43cce24f..2359d9ea9f 100644 --- a/config/environments/profiling.rb +++ b/config/environments/profiling.rb @@ -1,19 +1,19 @@ Leihs::Application.configure do # Settings specified here will take precedence over those in config/environment.rb - + # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = true - + # Use a different logger for distributed setups # config.logger = SyslogLogger.new - + # Full error reports are disabled and caching is turned on config.consider_all_requests_local = true - config.action_controller.perform_caching = true - config.action_view.cache_template_loading = true - + config.action_controller.perform_caching = true + config.action_view.cache_template_loading = true + # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. diff --git a/config/environments/test.rb b/config/environments/test.rb index e9c96916ee..c68134d673 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -13,11 +13,11 @@ config.eager_load = false # Configure static file server for tests with Cache-Control for performance. - config.public_file_server.enabled = true + config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' } # Show full error reports and disable caching. - config.consider_all_requests_local = true + config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. diff --git a/config/initializers/actionmailer_settings.rb b/config/initializers/actionmailer_settings.rb index 22dcee6766..b169267635 100644 --- a/config/initializers/actionmailer_settings.rb +++ b/config/initializers/actionmailer_settings.rb @@ -1,12 +1,11 @@ class ActionMailer::Base - def self.smtp_settings default = { - :address => "localhost", - :port => 25, - :domain => "localhost", - :enable_starttls_auto => false, - :openssl_verify_mode => 'none' + address: 'localhost', + port: 25, + domain: 'localhost', + enable_starttls_auto: false, + openssl_verify_mode: 'none' } # If you don't check for the existence of a settings table, you will break @@ -18,48 +17,50 @@ def self.smtp_settings # Additionally, we have to check for existance of each setting because the settings # table will be changed by migrations along the way, so the setting we expect to be # there might not actually exist while we are running the migration. - if ApplicationRecord.connection.tables.include?("settings") + if ApplicationRecord.connection.tables.include?('settings') app_settings = Setting.first + begin result = { - :address => app_settings.smtp_address, - :port => app_settings.smtp_port, - :domain => app_settings.smtp_domain, - :enable_starttls_auto => app_settings.smtp_enable_starttls_auto, - :openssl_verify_mode => app_settings.smtp_openssl_verify_mode + address: app_settings.smtp_address, + port: app_settings.smtp_port, + domain: app_settings.smtp_domain, + enable_starttls_auto: app_settings.smtp_enable_starttls_auto, + openssl_verify_mode: app_settings.smtp_openssl_verify_mode } - rescue - logger.info("Could not configure ActionMailer because the database doesn't seem to be in the right shape for it. Check the settings table.") + rescue StandardError + logger.info( + "Could not configure ActionMailer because the database doesn't seem to be in the right shape for it. Check the settings table." + ) result = default end - # Catch NameError and uninitialized constant if these settings aren't defined begin - if (app_settings.smtp_username and app_settings.smtp_password) and (!app_settings.smtp_username.empty? and !app_settings.smtp_password.empty?) + if (app_settings.smtp_username and app_settings.smtp_password) and + (!app_settings.smtp_username.empty? and !app_settings.smtp_password.empty?) auth_settings = { - :user_name => app_settings.smtp_username, - :password => app_settings.smtp_password + user_name: app_settings.smtp_username, password: app_settings.smtp_password } result.merge!(auth_settings) end - rescue + rescue StandardError + end else result = default end + # Catch NameError and uninitialized constant if these settings aren't defined + return result end def self.delivery_method begin delivery_method = Setting.first.mail_delivery_method.to_sym - if delivery_method.empty? - delivery_method = :test - end - rescue + delivery_method = :test if delivery_method.empty? + rescue StandardError delivery_method = :smtp end return delivery_method end - end diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb index 32861fec76..e25a774304 100644 --- a/config/initializers/assets.rb +++ b/config/initializers/assets.rb @@ -8,18 +8,20 @@ # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. -Rails.application.config.assets.precompile += %w( application.js - borrow.js - manage.js - borrow.css - manage.css - print.css - i18n/locale/* - simile_timeline/* - timeline.css - upload.js - timecop/timecop-0.1.1.js - ) +Rails.application.config.assets.precompile += + %w[ + application.js + borrow.js + manage.js + borrow.css + manage.css + print.css + i18n/locale/* + simile_timeline/* + timeline.css + upload.js + timecop/timecop-0.1.1.js + ] # DOES NOT WORK: NoMethodError: undefined method `call' for JsrenderRails::Jsrender:Class # Sprockets.register_mime_type 'text/jsr', extensions: ['.jsr'] diff --git a/config/initializers/error_handling.rb b/config/initializers/error_handling.rb index 1f178a537e..78f8b9f146 100644 --- a/config/initializers/error_handling.rb +++ b/config/initializers/error_handling.rb @@ -23,9 +23,7 @@ class ForbiddenError < StandardError end # add http mappings for our custom error classes -errors_to_http_status = { - 'Pundit::NotAuthorizedError' => :forbidden # 403 -} +errors_to_http_status = { 'Pundit::NotAuthorizedError' => :forbidden } # 403 Rails.application.config.before_configuration do ActionDispatch::ExceptionWrapper.rescue_responses.merge!(errors_to_http_status) end diff --git a/config/initializers/gettext.rb b/config/initializers/gettext.rb index 1672ff05d7..f5affba1e2 100644 --- a/config/initializers/gettext.rb +++ b/config/initializers/gettext.rb @@ -4,11 +4,12 @@ # We can use .po files directly. It's just as fast as using .mo files and saves us the gettext:pack step if Rails.env.development? - # hide warnings about obsolete/fuzzy translations - FastGettext.add_text_domain 'leihs', :path => 'locale', :type => :po, report_warning: false + FastGettext.add_text_domain 'leihs', path: 'locale', type: :po, report_warning: false else - FastGettext.add_text_domain 'leihs', :path => 'locale', :type => :po + FastGettext.add_text_domain 'leihs', path: 'locale', type: :po end +# hide warnings about obsolete/fuzzy translations + # DANGER, WARNING: Use underscores when separating language from region (e.g. "en_US"). Not using underscores will # trigger Ragnarök and the world of mortals will cease its pitiful existence. FastGettext.default_available_locales = ['en_GB', 'de_CH', 'es', 'fr_CH', 'gsw_CH', 'en_US'] #all you want to allow diff --git a/config/initializers/hoptoad.rb b/config/initializers/hoptoad.rb index b1d4933bd3..ce264a82df 100644 --- a/config/initializers/hoptoad.rb +++ b/config/initializers/hoptoad.rb @@ -1,5 +1,4 @@ -# TODO switch on/off through settings - +# TODO switch on/off through settings # Disable for now, it messes things up on hosts that don't # have Internet connectivity. diff --git a/config/initializers/languages.rb b/config/initializers/languages.rb index d3e832604a..4ec8e0edd8 100644 --- a/config/initializers/languages.rb +++ b/config/initializers/languages.rb @@ -1,16 +1,8 @@ -if ApplicationRecord.connection.tables.include?("languages") and not Rails.env.test? - +if ApplicationRecord.connection.tables.include?('languages') and nRails.env.test? unless Language.exists? - require "#{Rails.root}/features/support/leihs_factory.rb" LeihsFactory.create_default_languages - puts "Languages created: %s" % Language.all.map(&:name).join(', ') if Language.exists? - + puts 'Languages created: %s' % Language.all.map(&:name).join(', ') if Language.exists? end - end - - - - diff --git a/config/initializers/money.rb b/config/initializers/money.rb index 93df6c8218..66674cd673 100644 --- a/config/initializers/money.rb +++ b/config/initializers/money.rb @@ -1,15 +1,13 @@ # encoding : utf-8 MoneyRails.configure do |config| - - # To set the default currency - # # config.default_currency = :usd - config.default_currency = begin - Setting.first.local_currency_string.downcase.to_sym - rescue - :chf - end + config.default_currency = + begin + Setting.first.local_currency_string.downcase.to_sym + rescue StandardError + :chf + end # Set default bank object # @@ -39,14 +37,17 @@ # default: 0 # } - config.amount_column = { prefix: '', - postfix: '_cents', # NOTE avoid the translation according to the default_currency (i.e.: chf -> '_rappens') - column_name: nil, - type: :integer, - present: true, - null: false, - default: 0 - } + config.amount_column = { + prefix: '', + postfix: '_cents', + column_name: + # NOTE avoid the translation according to the default_currency (i.e.: chf -> '_rappens') + nil, + type: :integer, + present: true, + null: false, + default: 0 + } # config.currency_column = { prefix: '', # postfix: '_currency', @@ -56,18 +57,20 @@ # null: false, # default: 'USD' # } - config.currency_column = { prefix: '', - postfix: '_currency', - column_name: nil, - type: :string, - present: true, - null: false, - default: begin - Setting.first.local_currency_string - rescue - 'CHF' - end - } + config.currency_column = { + prefix: '', + postfix: '_currency', + column_name: nil, + type: :string, + present: true, + null: false, + default: + begin + Setting.first.local_currency_string + rescue StandardError + 'CHF' + end + } # Register a custom currency # diff --git a/config/initializers/react_rails.rb b/config/initializers/react_rails.rb index 1ae459a68d..9bac83eca9 100644 --- a/config/initializers/react_rails.rb +++ b/config/initializers/react_rails.rb @@ -4,23 +4,25 @@ Rails.application.configure do # Settings for the pool of renderers: - config.react.server_renderer_pool_size ||= 1 # ExecJS doesn't allow more than one on MRI - config.react.server_renderer_timeout ||= 20 # seconds + config.react.server_renderer_pool_size ||= 1 # ExecJS doesn't allow more than one on MRI + config.react.server_renderer_timeout ||= 20 # seconds config.react.server_renderer = React::ServerRendering::BundleRenderer config.react.server_renderer_options = { - files: ['server_rendering.js'], # files to load for prerendering - replay_console: Rails.env.development?, # if true, console.* will be replayed client-side + # if true, console.* will be replayed client-side + files: ['server_rendering.js'], + replay_console: + # files to load for prerendering + Rails + .env + .development? } # Changing files matching these dirs/exts will cause the server renderer to reload: - config.react.server_renderer_extensions = ["jsx", "js"] - config.react.server_renderer_directories = [ - "/app/assets/javascripts", - "/app/javascript/" - ] + config.react.server_renderer_extensions = ['jsx', 'js'] + config.react.server_renderer_directories = ['/app/assets/javascripts', '/app/javascript/'] # use webpack assets even if others detected: - React::ServerRendering::BundleRenderer.asset_container_class = \ + React::ServerRendering::BundleRenderer.asset_container_class = React::ServerRendering::WebpackerManifestContainer end diff --git a/config/initializers/release_info.rb b/config/initializers/release_info.rb index acffc048ec..1ecc1312b5 100644 --- a/config/initializers/release_info.rb +++ b/config/initializers/release_info.rb @@ -13,18 +13,19 @@ HISTORY_LINK = 'https://github.com/leihs/leihs/releases?after=4.1.0' def deploy_info - @deploy_info ||= begin - dat = YAML.safe_load(File.read('../config/deploy-info.yml')) - dat.merge( - commit_link: GIT_LINK + dat['commit_id'], - tree_link: TREE_LINK + dat['tree_id']) - rescue - end + @deploy_info ||= + begin + dat = YAML.safe_load(File.read('../config/deploy-info.yml')) + dat.merge(commit_link: GIT_LINK + dat['commit_id'], tree_link: TREE_LINK + dat['tree_id']) + rescue StandardError + + end end def releases_info - @releases_info ||= begin YAML.safe_load( - File.read('../config/releases.yml'))['releases'].map do |r| + @releases_info ||= + begin + YAML.safe_load(File.read('../config/releases.yml'))['releases'].map do |r| v = semver(r) r.merge( semver: v, @@ -32,23 +33,19 @@ def releases_info link: "#{TAG_LINK}#{v}", description: to_markdown(r['description']) ) - end.presence + end + .presence rescue Errno::ENOENT => e # ignore file errors + end end def git_hash - @git_hash ||= \ - if deploy_info then deploy_info['commit_id'] - else - `git log -n1 --format='%h'`.chomp - end + @git_hash ||= deploy_info ? deploy_info['commit_id'] : `git log -n1 --format='%h'`.chomp end def semver(release_info) - version = ['major', 'minor', 'patch'] - .map { |key| release_info.fetch("version_#{key}") } - .join('.') + version = ['major', 'minor', 'patch'].map { |key| release_info.fetch("version_#{key}") }.join('.') pre = release_info['version_pre'].presence pre.nil? ? version : "#{version}-#{pre}" end @@ -56,11 +53,8 @@ def semver(release_info) def version_from_archive return unless deploy_info.present? semver = releases_info.try(:first).try(:[], :semver) || '0.0.0' - { - type: 'archive', - deploy_info: deploy_info, - version_name: semver - } + + { type: 'archive', deploy_info: deploy_info, version_name: semver } end def version_from_git @@ -78,8 +72,9 @@ def to_markdown(source) Kramdown::Document.new(source, opts).to_html.html_safe end -RELEASE_INFO ||= { version_name: '???' } - .merge(version_from_archive || version_from_git) - .merge(releases: releases_info, history: HISTORY_LINK) - .deep_symbolize_keys - .freeze +RELEASE_INFO ||= + { version_name: '???' }.merge(version_from_archive || version_from_git).merge( + releases: releases_info, history: HISTORY_LINK + ) + .deep_symbolize_keys + .freeze diff --git a/config/initializers/settings.rb b/config/initializers/settings.rb index b2b7a1cdbf..3f187b6bc9 100644 --- a/config/initializers/settings.rb +++ b/config/initializers/settings.rb @@ -1,33 +1,41 @@ -if ApplicationRecord.connection.tables.include?("settings") and not Rails.env.test? - +if ApplicationRecord.connection.tables.include?('settings') and nRails.env.test? unless Setting.exists? - h = {} - h[:smtp_address] = ActionMailer::Base.smtp_settings[:address] if ActionMailer::Base.smtp_settings[:address] - h[:smtp_port] = ActionMailer::Base.smtp_settings[:port] if ActionMailer::Base.smtp_settings[:port] - h[:smtp_domain] = ActionMailer::Base.smtp_settings[:domain] if ActionMailer::Base.smtp_settings[:domain] - h[:local_currency_string] = LOCAL_CURRENCY_STRING if Leihs::Application.const_defined? :LOCAL_CURRENCY_STRING - h[:contract_terms] = CONTRACT_TERMS if Leihs::Application.const_defined? :CONTRACT_TERMS - h[:contract_lending_party_string] = CONTRACT_LENDING_PARTY_STRING if Leihs::Application.const_defined? :CONTRACT_LENDING_PARTY_STRING - h[:email_signature] = EMAIL_SIGNATURE if Leihs::Application.const_defined? :EMAIL_SIGNATURE - h[:default_email] = DEFAULT_EMAIL if Leihs::Application.const_defined? :DEFAULT_EMAIL - h[:deliver_received_order_notifications] = DELIVER_RECEIVED_ORDER_NOTIFICATIONS if Leihs::Application.const_defined? :DELIVER_RECEIVED_ORDER_NOTIFICATIONS - h[:user_image_url] = USER_IMAGE_URL if Leihs::Application.const_defined? :USER_IMAGE_URL + if ActionMailer::Base.smtp_settings[:address] + h[:smtp_address] = ActionMailer::Base.smtp_settings[:address] + end + if ActionMailer::Base.smtp_settings[:port] + h[:smtp_port] = ActionMailer::Base.smtp_settings[:port] + end + if ActionMailer::Base.smtp_settings[:domain] + h[:smtp_domain] = ActionMailer::Base.smtp_settings[:domain] + end + if Leihs::Application.const_defined? :LOCAL_CURRENCY_STRING + h[:local_currency_string] = LOCAL_CURRENCY_STRING + end + h[:contract_terms] = CONTRACT_TERMS if Leihs::Application.const_defined? :CONTRACT_TERMS + if Leihs::Application.const_defined? :CONTRACT_LENDING_PARTY_STRING + h[:contract_lending_party_string] = CONTRACT_LENDING_PARTY_STRING + end + h[:email_signature] = EMAIL_SIGNATURE if Leihs::Application.const_defined? :EMAIL_SIGNATURE + h[:default_email] = DEFAULT_EMAIL if Leihs::Application.const_defined? :DEFAULT_EMAIL + if Leihs::Application.const_defined? :DELIVER_RECEIVED_ORDER_NOTIFICATIONS + h[:deliver_received_order_notifications] = DELIVER_RECEIVED_ORDER_NOTIFICATIONS + end + h[:user_image_url] = USER_IMAGE_URL if Leihs::Application.const_defined? :USER_IMAGE_URL - # Create some sane defaults if they couldn't be exctracted from the application.rb, e.g. - # if application.rb is empty. - h[:smtp_address] ||= "localhost" - h[:smtp_port] ||= 25 - h[:smtp_domain] ||= "example.com" - h[:local_currency_string] ||= "GBP" - h[:contract_terms] ||= nil - h[:contract_lending_party_string] ||= nil - h[:email_signature] ||= "Cheers," - h[:default_email] ||= "your.lending.desk@example.com" - h[:deliver_received_order_notifications] ||= false - h[:user_image_url] ||= nil - h[:logo_url] ||= nil - h[:mail_delivery_method] ||= 'test' + h[:smtp_address] ||= 'localhost' + h[:smtp_port] ||= 25 + h[:smtp_domain] ||= 'example.com' + h[:local_currency_string] ||= 'GBP' + h[:contract_terms] ||= nil + h[:contract_lending_party_string] ||= nil + h[:email_signature] ||= 'Cheers,' + h[:default_email] ||= 'your.lending.desk@example.com' + h[:deliver_received_order_notifications] ||= false + h[:user_image_url] ||= nil + h[:logo_url] ||= nil + h[:mail_delivery_method] ||= 'test' setting = Setting.new(h) unless h.empty? if setting.save @@ -35,18 +43,21 @@ else raise "Settings could not be created: #{setting.errors.full_messages}" end - end settings_file_path = File.join(Rails.root, 'config', 'settings.yml') if File.exist?(settings_file_path) - if settings_from_file = YAML::load_file(settings_file_path) - # bypassing Setting's before_update callback + if settings_from_file = YAML.load_file(settings_file_path) ApplicationRecord.connection.execute <<-SQL - UPDATE settings - SET #{settings_from_file.map { |k, v| "#{k} = '#{v}'" }.join(', ')} + UPDATE settings + SET #{settings_from_file.map { |k, v| "#{k} = '#{v}'" }.join( + ', ' + )} SQL end end - end +# Create some sane defaults if they couldn't be exctracted from the application.rb, e.g. +# if application.rb is empty. + +# bypassing Setting's before_update callback diff --git a/config/initializers/string.rb b/config/initializers/string.rb index 441d7db6f3..96231d6d81 100644 --- a/config/initializers/string.rb +++ b/config/initializers/string.rb @@ -1,5 +1,9 @@ class String def numeric? - Float(self) != nil rescue false + begin + Float(self) != nil + rescue StandardError + false + end end end diff --git a/config/initializers/time_formats.rb b/config/initializers/time_formats.rb index ab64e37717..67b81c1b8c 100644 --- a/config/initializers/time_formats.rb +++ b/config/initializers/time_formats.rb @@ -1,4 +1,3 @@ - # Time::DATE_FORMATS[:month_and_year] = "%B %Y" -Date::DATE_FORMATS[:month_and_year] = "%B %Y" -Date::DATE_FORMATS[:with_weekday_name] = "%d. %b %Y, %A" +Date::DATE_FORMATS[:month_and_year] = '%B %Y' +Date::DATE_FORMATS[:with_weekday_name] = '%d. %b %Y, %A' diff --git a/config/initializers/time_zone.rb b/config/initializers/time_zone.rb index 31202851f1..eb37306da1 100644 --- a/config/initializers/time_zone.rb +++ b/config/initializers/time_zone.rb @@ -1,4 +1,4 @@ -if ApplicationRecord.connection.tables.include?('settings') and not Rails.env.test? +if ApplicationRecord.connection.tables.include?('settings') and nRails.env.test? if time_zone = Setting.first.try(:time_zone).presence Rails.configuration.time_zone = time_zone Time.zone_default = ActiveSupport::TimeZone.new(time_zone) diff --git a/config/routes.rb b/config/routes.rb index daf0bcdc10..17027e9d88 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,29 +1,28 @@ Rails.application.routes.draw do - root to: 'application#root' if Rails.env.development? or Rails.env.test? - # NOTE: for prod path helper is added as application helper custom method post '/sign-in', to: 'application#sign_in' post '/sign-out', to: 'application#sign_out' end + # NOTE: for prod path helper is added as application helper custom method get :status, controller: :application, action: :status # Categories - get "categories/:id/image", to: "categories#image", as: "category_image" - get "category_links", to: "category_links#index", as: "category_links" + get 'categories/:id/image', to: 'categories#image', as: 'category_image' + get 'category_links', to: 'category_links#index', as: 'category_links' # Styleguide - get "styleguide", to: "styleguide#show" - get "styleguide/:section", to: "styleguide#show" + get 'styleguide', to: 'styleguide#show' + get 'styleguide/:section', to: 'styleguide#show' # Models - get "models/:id/image", to: "models#image", as: "model_image" - get "models/:id/image_thumb", to: "models#image", as: "model_image_thumb", size: :thumb + get 'models/:id/image', to: 'models#image', as: 'model_image' + get 'models/:id/image_thumb', to: 'models#image', as: 'model_image_thumb', size: :thumb # Properties - get "properties", to: "properties#index", as: "properties" + get 'properties', to: 'properties#index', as: 'properties' # Images get 'images/:id', to: 'images#show', as: 'get_image' @@ -34,122 +33,125 @@ get 'release', to: 'release_info#index', as: 'release_info' - mount LeihsAdmin::Engine => '/admin', :as => 'admin' + mount LeihsAdmin::Engine => '/admin', as: 'admin' # Borrow Section namespace :borrow do - root to: "application#root" + root to: 'application#root' # maintenance - get "maintenance", to: "application#maintenance" + get 'maintenance', to: 'application#maintenance' - get "availability", to: "availability#show", as: "availability" + get 'availability', to: 'availability#show', as: 'availability' get 'booking_calendar_availability', to: 'availability#booking_calendar_availability' get 'total_borrowable_quantities', to: 'availability#total_borrowable_quantities' - get "holidays", to: "holidays#index", as: "holidays" - get "inventory_pools", to: "inventory_pools#index", as: "inventory_pools" - - get "categories", to: "categories#index" - get "groups", to: "groups#index" - - get "models", to: "models#index", as: "models" - get "models/availability", to: "models#availability", as: "models_availability" - get "models/:id", to: "models#show", as: "model" - - get "order", to: "customer_orders#current", as: "current_order" - post "order", to: "customer_orders#submit" - delete "order/remove", to: "customer_orders#remove" - post "reservations", to: "reservations#create" - post "reservations/change_time_range", to: "reservations#change_time_range", as: "change_time_range" - delete "reservations", to: "reservations#destroy" - delete "order/remove_reservations", to: "customer_orders#remove_reservations" - get "order/timed_out", to: "customer_orders#timed_out" - post "order/delete_unavailables", to: "customer_orders#delete_unavailables" - get "orders", to: "customer_orders#index", as: "orders" - - get "refresh_timeout", to: "application#refresh_timeout" - get "returns", to: "returns#index", as: "returns" - - post 'search', to: 'search#search', as: "search" - get 'search', to: 'search#results', as: "search_results" - - get 'templates', to: 'templates#index', as: "templates" - get 'templates/:id', to: 'templates#show', as: "template" - post 'templates/:id', to: 'templates#select_dates', as: "template_select_dates" - post 'templates/:id/availability', to: 'templates#availability', as: "template_availability" - post 'templates/:id/add_to_order', to: 'templates#add_to_order', as: "template_add_to_order" - - get "to_pick_up", to: "to_pick_up#index", as: "to_pick_up" - get "workdays", to: "workdays#index", as: "workdays" - - get "user", to: "users#current", as: "current_user" - get "user/documents", to: "users#documents", as: "user_documents" - get "user/contracts/:id", to: "users#contract", as: "user_contract" - get "user/value_lists/:id", to: "users#value_list", as: "user_value_list" - get "user/delegations", to: "users#delegations", as: "user_delegations" - post "user/switch_to_delegation/:id", to: "users#switch_to_delegation", as: "user_switch_to_delegation" - get "user/switch_back", to: "users#switch_back", as: "user_switch_back" + get 'holidays', to: 'holidays#index', as: 'holidays' + get 'inventory_pools', to: 'inventory_pools#index', as: 'inventory_pools' + + get 'categories', to: 'categories#index' + get 'groups', to: 'groups#index' + + get 'models', to: 'models#index', as: 'models' + get 'models/availability', to: 'models#availability', as: 'models_availability' + get 'models/:id', to: 'models#show', as: 'model' + + get 'order', to: 'customer_orders#current', as: 'current_order' + post 'order', to: 'customer_orders#submit' + delete 'order/remove', to: 'customer_orders#remove' + post 'reservations', to: 'reservations#create' + post 'reservations/change_time_range', + to: 'reservations#change_time_range', as: 'change_time_range' + delete 'reservations', to: 'reservations#destroy' + delete 'order/remove_reservations', to: 'customer_orders#remove_reservations' + get 'order/timed_out', to: 'customer_orders#timed_out' + post 'order/delete_unavailables', to: 'customer_orders#delete_unavailables' + get 'orders', to: 'customer_orders#index', as: 'orders' + + get 'refresh_timeout', to: 'application#refresh_timeout' + get 'returns', to: 'returns#index', as: 'returns' + + post 'search', to: 'search#search', as: 'search' + get 'search', to: 'search#results', as: 'search_results' + + get 'templates', to: 'templates#index', as: 'templates' + get 'templates/:id', to: 'templates#show', as: 'template' + post 'templates/:id', to: 'templates#select_dates', as: 'template_select_dates' + post 'templates/:id/availability', to: 'templates#availability', as: 'template_availability' + post 'templates/:id/add_to_order', to: 'templates#add_to_order', as: 'template_add_to_order' + + get 'to_pick_up', to: 'to_pick_up#index', as: 'to_pick_up' + get 'workdays', to: 'workdays#index', as: 'workdays' + + get 'user', to: 'users#current', as: 'current_user' + get 'user/documents', to: 'users#documents', as: 'user_documents' + get 'user/contracts/:id', to: 'users#contract', as: 'user_contract' + get 'user/value_lists/:id', to: 'users#value_list', as: 'user_value_list' + get 'user/delegations', to: 'users#delegations', as: 'user_delegations' + post 'user/switch_to_delegation/:id', + to: 'users#switch_to_delegation', as: 'user_switch_to_delegation' + get 'user/switch_back', to: 'users#switch_back', as: 'user_switch_back' end # Manage Section namespace :manage do - root to: "application#root" + root to: 'application#root' # Administrate inventory pools # get 'inventory_pools', to: 'inventory_pools#index' # get 'inventory_pools/new', to: 'inventory_pools#new', as: 'new_inventory_pool' # post 'inventory_pools', to: 'inventory_pools#create' - get 'inventory_pools/:inventory_pool_id/edit', to: 'inventory_pools#edit', as: 'edit_inventory_pool' - put 'inventory_pools/:inventory_pool_id', to: 'inventory_pools#update', as: 'update_inventory_pool' + get 'inventory_pools/:inventory_pool_id/edit', + to: 'inventory_pools#edit', as: 'edit_inventory_pool' + put 'inventory_pools/:inventory_pool_id', + to: 'inventory_pools#update', as: 'update_inventory_pool' # delete 'inventory_pools/:inventory_pool_id', to: 'inventory_pools#destroy', as: 'delete_inventory_pool' # Users post 'users/:id/set_start_screen', to: 'users#set_start_screen' # Buildings - get 'rooms', to: 'rooms#index' + get 'rooms', to: 'rooms#index' get 'rooms_diff', to: 'rooms#get_rooms_diff' post 'rooms_diff', to: 'rooms#post_rooms_diff' - scope ":inventory_pool_id/" do - + scope ':inventory_pool_id/' do # maintenance get 'maintenance', to: 'application#maintenance' ## Availability - get 'availabilities', to: 'availability#index', as: 'inventory_pool_availabilities' - get 'availabilities/in_stock', to: 'availability#in_stock' + get 'availabilities', to: 'availability#index', as: 'inventory_pool_availabilities' + get 'availabilities/in_stock', to: 'availability#in_stock' ## Daily - get 'daily', to: "inventory_pools#daily", as: "daily_view" + get 'daily', to: 'inventory_pools#daily', as: 'daily_view' ## Contracts - get 'orders', to: "orders#index", as: "orders" + get 'orders', to: 'orders#index', as: 'orders' ############################################################################### # NOTE: query string length of GET is not enough for hand over dialog - post 'orders', to: "orders#index", as: "orders_via_post" + post 'orders', to: 'orders#index', as: 'orders_via_post' ############################################################################### - post "orders/:id/approve", to: "orders#approve", as: "approve_order" - post "orders/:id/reject", to: "orders#reject" - put "orders/:id", to: "orders#update" - post 'orders/:id/swap_user', to: "orders#swap_user" - get 'orders/:id/edit', to: "orders#edit", as: "edit_order" + post 'orders/:id/approve', to: 'orders#approve', as: 'approve_order' + post 'orders/:id/reject', to: 'orders#reject' + put 'orders/:id', to: 'orders#update' + post 'orders/:id/swap_user', to: 'orders#swap_user' + get 'orders/:id/edit', to: 'orders#edit', as: 'edit_order' ## Contracts - get 'contracts', to: "contracts#index", as: "contracts" - post 'contracts', to: "contracts#create", as: "create_contract" - get "contracts/:id", to: "contracts#show", as: "contract" - get "contracts/:id/value_list", to: "contracts#value_list", as: "value_list" - get "contracts/:id/picking_list", to: "contracts#picking_list", as: "picking_list" + get 'contracts', to: 'contracts#index', as: 'contracts' + post 'contracts', to: 'contracts#create', as: 'create_contract' + get 'contracts/:id', to: 'contracts#show', as: 'contract' + get 'contracts/:id/value_list', to: 'contracts#value_list', as: 'value_list' + get 'contracts/:id/picking_list', to: 'contracts#picking_list', as: 'picking_list' ## Visits - delete 'visits/:visit_id', to: 'visits#destroy' - post 'visits/:visit_id/remind', to: 'visits#remind' - get 'visits/hand_overs', to: 'visits#index', status: "approved" - get 'visits/take_backs', to: 'visits#index', status: "signed" - get 'visits', to: "visits#index", as: "inventory_pool_visits" + delete 'visits/:visit_id', to: 'visits#destroy' + post 'visits/:visit_id/remind', to: 'visits#remind' + get 'visits/hand_overs', to: 'visits#index', status: 'approved' + get 'visits/take_backs', to: 'visits#index', status: 'signed' + get 'visits', to: 'visits#index', as: 'inventory_pool_visits' ## Workload get 'workload', to: 'inventory_pools#workload' @@ -158,122 +160,124 @@ get 'latest_reminder', to: 'inventory_pools#latest_reminder' ## Workdays - get 'workdays', to: "workdays#index" + get 'workdays', to: 'workdays#index' ## Holidays - get 'holidays', to: "holidays#index" + get 'holidays', to: 'holidays#index' ## Reservations - get "reservations", to: "reservations#index" - post "reservations", to: "reservations#create" - delete "reservations", to: "reservations#destroy" - post "reservations/swap_user", to: "reservations#swap_user" - post "reservations/swap_model", to: "reservations#swap_model" - post "reservations/assign_or_create", to: "reservations#assign_or_create" - post "reservations/change_time_range", to: "reservations#change_time_range" - post "reservations/for_template", to: "reservations#create_for_template" - post "reservations/:id/assign", to: "reservations#assign" - post "reservations/:id/remove_assignment", to: "reservations#remove_assignment" - put "reservations/:line_id", to: "reservations#update" - delete "reservations/:line_id", to: "reservations#destroy" - post "reservations/take_back", to: "reservations#take_back" - post "reservations/print", to: "reservations#print", as: "print_reservations" + get 'reservations', to: 'reservations#index' + post 'reservations', to: 'reservations#create' + delete 'reservations', to: 'reservations#destroy' + post 'reservations/swap_user', to: 'reservations#swap_user' + post 'reservations/swap_model', to: 'reservations#swap_model' + post 'reservations/assign_or_create', to: 'reservations#assign_or_create' + post 'reservations/change_time_range', to: 'reservations#change_time_range' + post 'reservations/for_template', to: 'reservations#create_for_template' + post 'reservations/:id/assign', to: 'reservations#assign' + post 'reservations/:id/remove_assignment', to: 'reservations#remove_assignment' + put 'reservations/:line_id', to: 'reservations#update' + delete 'reservations/:line_id', to: 'reservations#destroy' + post 'reservations/take_back', to: 'reservations#take_back' + post 'reservations/print', to: 'reservations#print', as: 'print_reservations' # Inventory - get 'inventory', :to => "inventory#index", :as => "inventory" - get 'inventory/expert/index', :to => "expert#index" - get 'inventory/csv', :to => "inventory#csv_export", :as => "inventory_csv_export" - get 'inventory/excel', :to => "inventory#excel_export", :as => "inventory_excel_export" - get 'inventory/csv/expert', :to => "expert#csv_export", :as => "inventory_csv_export_expert" - get 'inventory/excel/expert', :to => "expert#excel_export", :as => "inventory_excel_export_expert" - get 'inventory/csv_import', :to => "inventory#csv_import" - post 'inventory/csv_import', :to => "inventory#csv_import" - get 'inventory/helper', :to => "inventory#helper", :as => "inventory_helper" - get 'inventory/helper_react', :to => "inventory#helper_react", :as => "inventory_helper_react" - get 'inventory/expert', :to => "inventory#expert", :as => "inventory_expert" - get 'inventory/:inventory_code', :to => "inventory#show" + get 'inventory', to: 'inventory#index', as: 'inventory' + get 'inventory/expert/index', to: 'expert#index' + get 'inventory/csv', to: 'inventory#csv_export', as: 'inventory_csv_export' + get 'inventory/excel', to: 'inventory#excel_export', as: 'inventory_excel_export' + get 'inventory/csv/expert', to: 'expert#csv_export', as: 'inventory_csv_export_expert' + get 'inventory/excel/expert', to: 'expert#excel_export', as: 'inventory_excel_export_expert' + get 'inventory/csv_import', to: 'inventory#csv_import' + post 'inventory/csv_import', to: 'inventory#csv_import' + get 'inventory/helper', to: 'inventory#helper', as: 'inventory_helper' + get 'inventory/helper_react', to: 'inventory#helper_react', as: 'inventory_helper_react' + get 'inventory/expert', to: 'inventory#expert', as: 'inventory_expert' + get 'inventory/:inventory_code', to: 'inventory#show' # Models - get 'models', to: "models#index", as: "models" - post 'models', to: "models#create", as: "create_model" - get 'models/new_old', to: "models#new_old", as: "new_model_old" - get 'models/new', to: "models#new", as: "new_model" - post 'models/store_attachment_react', to: "models#store_attachment_react", as: "model_store_attachment_react" - post 'models/store_image_react', to: "models#store_image_react", as: "model_store_image_react" - get 'models/:id/timeline', to: "models#timeline" - get 'models/:id/old_timeline', to: "models#old_timeline" - put 'models/:id', to: "models#update" - get 'models/:id', to: "models#show" - delete 'models/:id', to: "models#destroy" - get 'models/:id/edit', to: "models#edit", as: "edit_model" - get 'models/:id/edit_old', to: "models#edit_old", as: "edit_old_model" - post 'models/:id/upload/image', to: "models#upload", type: "image" - post 'models/:id/upload/attachment', to: "models#upload", type: "attachment" + get 'models', to: 'models#index', as: 'models' + post 'models', to: 'models#create', as: 'create_model' + get 'models/new_old', to: 'models#new_old', as: 'new_model_old' + get 'models/new', to: 'models#new', as: 'new_model' + post 'models/store_attachment_react', + to: 'models#store_attachment_react', as: 'model_store_attachment_react' + post 'models/store_image_react', to: 'models#store_image_react', as: 'model_store_image_react' + get 'models/:id/timeline', to: 'models#timeline' + get 'models/:id/old_timeline', to: 'models#old_timeline' + put 'models/:id', to: 'models#update' + get 'models/:id', to: 'models#show' + delete 'models/:id', to: 'models#destroy' + get 'models/:id/edit', to: 'models#edit', as: 'edit_model' + get 'models/:id/edit_old', to: 'models#edit_old', as: 'edit_old_model' + post 'models/:id/upload/image', to: 'models#upload', type: 'image' + post 'models/:id/upload/attachment', to: 'models#upload', type: 'attachment' # Categories - get 'categories', to: 'categories#index', as: 'categories' - post 'categories', to: 'categories#create' - get 'categories/new', to: 'categories#new', as: 'new_category' - get 'categories/:id/edit', to: 'categories#edit', as: 'edit_category' - put 'categories/:id', to: 'categories#update', as: 'update_category' - delete 'categories/:id', to: 'categories#destroy' - post 'categories/:id/upload/image', to: "categories#upload", type: "image" + get 'categories', to: 'categories#index', as: 'categories' + post 'categories', to: 'categories#create' + get 'categories/new', to: 'categories#new', as: 'new_category' + get 'categories/:id/edit', to: 'categories#edit', as: 'edit_category' + put 'categories/:id', to: 'categories#update', as: 'update_category' + delete 'categories/:id', to: 'categories#destroy' + post 'categories/:id/upload/image', to: 'categories#upload', type: 'image' # Options - get 'options', to: "options#index" - post 'options', to: "options#create", as: "create_option" - get 'options/new', to: "options#new", as: "new_option" - get 'options/:id/edit', to: "options#edit", as: "edit_option" - put 'options/:id', to: "options#update", as: "update_option" + get 'options', to: 'options#index' + post 'options', to: 'options#create', as: 'create_option' + get 'options/new', to: 'options#new', as: 'new_option' + get 'options/:id/edit', to: 'options#edit', as: 'edit_option' + put 'options/:id', to: 'options#update', as: 'update_option' # Items - get 'items', to: "items#index" - post 'items', to: "items#create", as: "create_item" - post 'items/create_package', to: "items#create_package", as: "create_package" - get 'items/new', to: "items#new", as: "new_item" - post 'items/store_attachment_react', to: "items#store_attachment_react", as: "item_store_attachment_react" - get 'items/current_locations', to: "items#current_locations" - get 'items/:id', to: "items#show" - put 'items/:id', to: "items#update", as: "update_item" - get 'items/:id/edit', to: "items#edit", as: "edit_item" - get 'items/:id/copy', to: "items#copy", as: "copy_item" - post 'items/:id/inspect', to: "items#inspect" - post 'items/:id/upload/attachment', to: "items#upload", type: "attachment" + get 'items', to: 'items#index' + post 'items', to: 'items#create', as: 'create_item' + post 'items/create_package', to: 'items#create_package', as: 'create_package' + get 'items/new', to: 'items#new', as: 'new_item' + post 'items/store_attachment_react', + to: 'items#store_attachment_react', as: 'item_store_attachment_react' + get 'items/current_locations', to: 'items#current_locations' + get 'items/:id', to: 'items#show' + put 'items/:id', to: 'items#update', as: 'update_item' + get 'items/:id/edit', to: 'items#edit', as: 'edit_item' + get 'items/:id/copy', to: 'items#copy', as: 'copy_item' + post 'items/:id/inspect', to: 'items#inspect' + post 'items/:id/upload/attachment', to: 'items#upload', type: 'attachment' # Partitions - get 'partitions', to: "partitions#index" + get 'partitions', to: 'partitions#index' # Groups - get 'groups', to: "entitlement_groups#index", as: "inventory_pool_groups" - get 'groups/:id/edit', to: "entitlement_groups#edit", as: "edit_inventory_pool_group" - get 'groups/new', to: "entitlement_groups#new", as: "new_inventory_pool_group" - post 'groups', to: "entitlement_groups#create" - put 'groups/:id', to: "entitlement_groups#update", as: "update_inventory_pool_group" - delete 'groups/:id', to: "entitlement_groups#destroy", as: "delete_inventory_pool_group" + get 'groups', to: 'entitlement_groups#index', as: 'inventory_pool_groups' + get 'groups/:id/edit', to: 'entitlement_groups#edit', as: 'edit_inventory_pool_group' + get 'groups/new', to: 'entitlement_groups#new', as: 'new_inventory_pool_group' + post 'groups', to: 'entitlement_groups#create' + put 'groups/:id', to: 'entitlement_groups#update', as: 'update_inventory_pool_group' + delete 'groups/:id', to: 'entitlement_groups#destroy', as: 'delete_inventory_pool_group' # ModelLinks - get 'model_links', to: "model_links#index" + get 'model_links', to: 'model_links#index' # Templates - get 'templates', to: "templates#index", as: "templates" - post 'templates', to: "templates#create" - get 'templates/new', to: "templates#new", as: "new_template" - get 'templates/:id/edit', to: "templates#edit", as: "edit_template" - put 'templates/:id', to: "templates#update", as: "update_template" - delete 'templates/:id', to: "templates#destroy", as: "delete_template" + get 'templates', to: 'templates#index', as: 'templates' + post 'templates', to: 'templates#create' + get 'templates/new', to: 'templates#new', as: 'new_template' + get 'templates/:id/edit', to: 'templates#edit', as: 'edit_template' + put 'templates/:id', to: 'templates#update', as: 'update_template' + delete 'templates/:id', to: 'templates#destroy', as: 'delete_template' # Users - get "users", to: "users#index", as: "inventory_pool_users" - get "users/new", to: "users#new", as: "new_inventory_pool_user" - post "users", to: "users#create", as: "create_inventory_pool_user" - get "users/:id/edit", to: "users#edit", as: "edit_inventory_pool_user" - put "users/:id", to: "users#update", as: "update_inventory_pool_user" + get 'users', to: 'users#index', as: 'inventory_pool_users' + get 'users/new', to: 'users#new', as: 'new_inventory_pool_user' + post 'users', to: 'users#create', as: 'create_inventory_pool_user' + get 'users/:id/edit', to: 'users#edit', as: 'edit_inventory_pool_user' + put 'users/:id', to: 'users#update', as: 'update_inventory_pool_user' - get 'users/:id/hand_over', to: "users#hand_over", as: "hand_over" - get 'users/:id/take_back', to: "users#take_back", as: "take_back" + get 'users/:id/hand_over', to: 'users#hand_over', as: 'hand_over' + get 'users/:id/take_back', to: 'users#take_back', as: 'take_back' # Access rights - get "access_rights", to: "access_rights#index" + get 'access_rights', to: 'access_rights#index' # Fields get 'fields', to: 'fields#index', as: 'fields' @@ -283,16 +287,16 @@ delete 'fields', to: 'fields#reset' # Search - post 'search', to: 'search#search', as: "search" - get 'search', to: 'search#results', as: "search_results" - get 'search/models', to: "search#models", as: "search_models" - get 'search/software', to: "search#software", as: "search_software" - get 'search/items', to: "search#items", as: "search_items" - get 'search/licenses', to: "search#licenses", as: "search_licenses" - get 'search/users', to: "search#users", as: "search_users" - get 'search/contracts', to: "search#contracts", as: "search_contracts" - get 'search/orders', to: "search#orders", as: "search_orders" - get 'search/options', to: "search#options", as: "search_options" + post 'search', to: 'search#search', as: 'search' + get 'search', to: 'search#results', as: 'search_results' + get 'search/models', to: 'search#models', as: 'search_models' + get 'search/software', to: 'search#software', as: 'search_software' + get 'search/items', to: 'search#items', as: 'search_items' + get 'search/licenses', to: 'search#licenses', as: 'search_licenses' + get 'search/users', to: 'search#users', as: 'search_users' + get 'search/contracts', to: 'search#contracts', as: 'search_contracts' + get 'search/orders', to: 'search#orders', as: 'search_orders' + get 'search/options', to: 'search#options', as: 'search_options' # Mail templates get 'mail_templates', to: 'mail_templates#index' @@ -300,16 +304,14 @@ put 'mail_templates/:type/:name', to: 'mail_templates#update' # Buildings - get 'buildings', to: 'buildings#index' - get 'buildings/:id/edit', to: 'buildings#edit', as: 'edit_inventory_pool_building' - delete 'buildings/:id', to: 'buildings#destroy', as: 'delete_inventory_pool_building' + get 'buildings', to: 'buildings#index' + get 'buildings/:id/edit', to: 'buildings#edit', as: 'edit_inventory_pool_building' + delete 'buildings/:id', to: 'buildings#destroy', as: 'delete_inventory_pool_building' # Suppliers - get 'suppliers', to: 'suppliers#index' - get 'suppliers/:id', to: 'suppliers#show', as: 'inventory_pool_supplier' - delete 'suppliers/:id', to: 'suppliers#destroy', as: 'delete_inventory_pool_supplier' + get 'suppliers', to: 'suppliers#index' + get 'suppliers/:id', to: 'suppliers#show', as: 'inventory_pool_supplier' + delete 'suppliers/:id', to: 'suppliers#destroy', as: 'delete_inventory_pool_supplier' end - end - end diff --git a/doc/add_access_rights_globally.rb b/doc/add_access_rights_globally.rb index 5c259ff4ca..9738cfd956 100644 --- a/doc/add_access_rights_globally.rb +++ b/doc/add_access_rights_globally.rb @@ -1,5 +1,4 @@ def add_access_right(user, inventory_pool, role = :customer) - existing = user.access_rights.where(inventory_pool_id: inventory_pool, role: role).first if existing return true @@ -12,5 +11,4 @@ def add_access_right(user, inventory_pool, role = :customer) return false end end - end diff --git a/doc/import_export/csv_export_of_items.rb b/doc/import_export/csv_export_of_items.rb index a14688d5d1..81d0aff455 100644 --- a/doc/import_export/csv_export_of_items.rb +++ b/doc/import_export/csv_export_of_items.rb @@ -1,101 +1 @@ - -#@exportable_items = Item.all -@exportable_items = Item.find(:conditions => { :inventory_code }) - -@exportable_items = Item.find(:all, :conditions => ["inventory_code LIKE ?", "AVZ%"]) - -item_array = [] -item_array << ['inventory_code', - 'inventory_pool', - 'serial_number', - 'model_name', - 'borrowable', - 'owner', - 'categories', - 'required_level', - 'invoice_number', - 'invoice_date', - 'last_check', - 'retired', - 'retired_reason', - 'price', - 'is_broken', - 'is_incomplete', - 'is_borrowable', - 'created_at', - 'updated_at', - 'needs_permission', - 'is_inventory_relevant', - 'responsible', - 'supplier'] - -@exportable_items.each do |i| - puts "Trying item " + i.inventory_code.to_s + " (ID: " + i.id.to_s + ")" - - if i.inventory_pool.nil? or i.inventory_pool.name.blank? - ip = "UNBEKANNT" - else - ip = i.inventory_pool.name - end - - if i.model.nil? or i.model.name.blank? - mod = "UNBEKANNT/VERAENDERT" - else - mod = i.model.name.gsub(/\"/, '""') - end - - if i.owner.nil? or i.owner.name.blank? - own = "UNBEKANNT" - else - own = i.owner.name - end - - unless i.model.categories.nil? or i.model.categories.count == 0 - categories = [] - i.model.categories.each do |c| - categories << c.name + "|" - end - end - - if i.supplier.blank? - supplier = "UNBEKANNT" - else - supplier = i.supplier.name - end - - item_array << [ i.inventory_code, - ip, - i.serial_number, - mod, - i.is_borrowable, - own, - categories, - i.required_level, - i.invoice_number, - i.invoice_date, - i.last_check, - i.retired, - i.retired_reason, - i.price, - i.is_broken, - i.is_incomplete, - i.is_borrowable, - i.created_at, - i.updated_at, - i.needs_permission, - i.is_inventory_relevant, - i.responsible, - supplier - ] - -end - - - - -require 'csv' -CSV.open("/tmp/alle_mit_avz_nummern.csv","w", { :col_sep => ";", :quote_char => "\"", :force_quotes => true } ) do |csv| - item_array.each do |i| - csv << i - end -end +#@exportable_items = Item.all = @exportable_items diff --git a/doc/import_export/csv_export_of_leihs1_reservations.rb b/doc/import_export/csv_export_of_leihs1_reservations.rb index 9f2e9127cd..8d5b533486 100644 --- a/doc/import_export/csv_export_of_leihs1_reservations.rb +++ b/doc/import_export/csv_export_of_leihs1_reservations.rb @@ -1,57 +1,35 @@ - res = Reservation.find_ausgeliehene(1) ueb = Reservation.find_ueberfaellige(1) avz_res = [] +res.each { |r| avz_res << r if r.geraetepark_id == 1 } -res.each do |r| - if r.geraetepark_id == 1 - avz_res << r - end -end - -ueb.each do |r| - if r.geraetepark_id == 1 - avz_res << r - end -end - - +ueb.each { |r| avz_res << r if r.geraetepark_id == 1 } csv_array = [] -csv_array << [ 'inventarcode', - 'modellbezeichnung', - 'person', - 'von', - 'bis'] - - +csv_array << ['inventarcode', 'modellbezeichnung', 'person', 'von', 'bis'] avz_res.each do |r| - - puts 'Trying reservation ' + r.id.to_s - - if r.pakets && r.pakets.count > 0 - puts '+++ Has packages' - r.pakets.each do |p| - p.gegenstands.each do |g| - csv_array << [ 'AVZ' + g.original_id.to_s, - g.modellbezeichnung, - r.user.name, - r.startdatum.strftime('%d.%m.%y'), - r.enddatum.strftime('%d.%m.%y') ] - end - end - end - - -end - - - -CSV.open('/tmp/leihs1_reservationen.csv','w', { col_sep: ';', quote_char: "\"", force_quotes: true } ) do |csv| - csv_array.each do |i| - csv << i + puts 'Trying reservation ' + r.id.to_s + + if r.pakets && r.pakets.count > 0 + puts '+++ Has packages' + r.pakets.each do |p| + p.gegenstands.each do |g| + csv_array << + [ + 'AVZ' + g.original_id.to_s, + g.modellbezeichnung, + r.user.name, + r.startdatum.strftime('%d.%m.%y'), + r.enddatum.strftime('%d.%m.%y') + ] + end + end end end + +CSV.open( + '/tmp/leihs1_reservationen.csv', 'w', { col_sep: ';', quote_char: '"', force_quotes: true } +) { |csv| csv_array.each { |i| csv << i } } diff --git a/doc/import_export/csv_import_of_items.rb b/doc/import_export/csv_import_of_items.rb index 19977f995c..af308b6a18 100644 --- a/doc/import_export/csv_import_of_items.rb +++ b/doc/import_export/csv_import_of_items.rb @@ -10,7 +10,7 @@ @errorlog = File.open('/tmp/import_errors.txt', 'w+') -items_to_import = CSV.open(import_file, col_sep: "\t", headers: true) +items_to_import = CSV.open(import_file, col_sep: 'undefined', headers: true) def log_error(error, item) @errorlog.puts "ERROR: #{error}. --- Item: #{item}" @@ -21,9 +21,9 @@ def validate_item(item) begin Model.find item['Leihs-Modellnummer'] - rescue + rescue StandardError errors = true - log_error "Model '#{item["Leihs-Modellname"]}' not found.", item + log_error "Model '#{item['Leihs-Modellname']}' not found.", item end if item['Verantwortliche Abteilung'].blank? @@ -33,7 +33,8 @@ def validate_item(item) responsible_ip = InventoryPool.where(name: item['Verantwortliche Abteilung']).first if responsible_ip.nil? errors = true - log_error "Responsible inventory pool '#{item["Verantwortliche Abteilung"]}' does not exist", item + log_error "Responsible inventory pool '#{item['Verantwortliche Abteilung']}' does not exist", + item end end @@ -44,11 +45,10 @@ def validate_item(item) owner_ip = InventoryPool.where(name: item['Besitzer']).first if owner_ip.nil? errors = true - log_error "Owner '#{item["Besitzer"]}' does not exist", item + log_error "Owner '#{item['Besitzer']}' does not exist", item end end - if errors @failures += 1 return false @@ -58,7 +58,7 @@ def validate_item(item) end items_to_import.each do |item| - next if not validate_item(item) + next if nvalidate_item(item) i = Item.new i.model = Model.find item['Leihs-Modellnummer'] i.inventory_code = item['Inv-Code:'] @@ -88,24 +88,25 @@ def validate_item(item) room = nil room = item['Raum'] unless item['Raum'].blank? - location = Location.find_or_create({'building_id' => b.id, 'room' => room}) + location = Location.find_or_create({ 'building_id' => b.id, 'room' => room }) i.location = location # Invoice i.invoice_number = item['Invoice Number'] - i.invoice_date = Date.strptime(item['Invoice Date'], '%m/%d/%Y') unless item['Invoice Date'].blank? - + unless item['Invoice Date'].blank? + i.invoice_date = Date.strptime(item['Invoice Date'], '%m/%d/%Y') + end i.responsible = item['Responsible person'] unless item['Responsible person'].blank? i.price = item['Initial Price'] unless item['Initial Price'].blank? - i.last_check = Date.strptime(item['letzte Inventur'], '%m/%d/%Y') unless item['letzte Inventur'].blank? + unless item['letzte Inventur'].blank? + i.last_check = Date.strptime(item['letzte Inventur'], '%m/%d/%Y') + end # Supplier i.supplier = Supplier.where(name: item['Lieferant']).first - if i.supplier.nil? - i.supplier = Supplier.create(name: item['Lieferant']) - end + i.supplier = Supplier.create(name: item['Lieferant']) if i.supplier.nil? # Properties i.properties[:anschaffungskategorie] = item['Anschaffungskategorie'] @@ -114,16 +115,15 @@ def validate_item(item) puts i - if i.save - # puts "Item imported correctly:" @successes += 1 - # puts i.inspect else @failures += 1 @errorlog.puts "Could not import item #{i.inventory_code}. Errors: #{i.errors.full_messages}" end + # puts "Item imported correctly:" + # puts i.inspect end puts '-----------------------------------------' @@ -131,5 +131,4 @@ def validate_item(item) puts "#{@successes} successes, #{@failures} failures" puts '-----------------------------------------' - @errorlog.close diff --git a/doc/import_export/csv_import_of_models.rb b/doc/import_export/csv_import_of_models.rb index f557099d34..b97f9e8bbf 100644 --- a/doc/import_export/csv_import_of_models.rb +++ b/doc/import_export/csv_import_of_models.rb @@ -1,10 +1,6 @@ - - - import_file = '/tmp/theater.csv' def create_model(name, category1, category2) - m = Model.find_by_product(name) if m.nil? c1 = Category.find_or_create_by_name(category1) unless category1.blank? @@ -16,13 +12,10 @@ def create_model(name, category1, category2) m.save end - return m end require 'csv' items_to_import = CSV.open(import_file, headers: false) -items_to_import.each do |item| - create_model(item[0], item[1], item[2]) -end +items_to_import.each { |item| create_model(item[0], item[1], item[2]) } diff --git a/doc/import_export/csv_import_of_options.rb b/doc/import_export/csv_import_of_options.rb index e07e6af7e8..ee34b4adec 100644 --- a/doc/import_export/csv_import_of_options.rb +++ b/doc/import_export/csv_import_of_options.rb @@ -1,23 +1,19 @@ - - - ip = InventoryPool.find(169) log = File.open('/tmp/optionen.log', 'a+') -CSV.open('/tmp/optionen.csv', 'r', { col_sep: "\t", quote_char: "\"", headers: true}).each do |csv| - if csv['price'] - price = BigDecimal.new(csv['price']) - else - price = 0.0 - end +CSV.open('/tmp/optionen.csv', 'r', { col_sep: 'undefined', quote_char: '"', headers: true }) + .each do |csv| + csv['price'] ? price = BigDecimal.new(csv['price']) : price = 0.0 - option = ip.options.find_or_create_by(inventory_code: csv['inventory_code'], product: csv['model_name'], price: price) + option = + ip.options.find_or_create_by( + inventory_code: csv['inventory_code'], product: csv['model_name'], price: price + ) if option log.puts "Success: #{csv['inventory_code']}" else log.puts "Error: #{csv['inventory_code']}: #{option.errors.full_messages}" end - end log.close diff --git a/doc/import_export/csv_import_of_users.rb b/doc/import_export/csv_import_of_users.rb index 6bff50a10a..574c85bd9d 100644 --- a/doc/import_export/csv_import_of_users.rb +++ b/doc/import_export/csv_import_of_users.rb @@ -1,4 +1,3 @@ - # The CSV file to import needs to be: # 1. Tab-separated. # 2. Use " as a quote char. @@ -15,15 +14,18 @@ def create_auth_for_user(user) password = SecureRandom.base64(6).tr('+/=lIO0', 'pqrsxyz') - dba = DatabaseAuthentication.create(login: user[:login], - password: password, - password_confirmation: password) + dba = + DatabaseAuthentication.create( + login: user[:login], password: password, password_confirmation: password + ) dba.user = user if dba.save @log.puts("DatabaseAuthentication for #{user} created. Password: #{password}") @passwords.puts("#{user.login} : #{password}") else - @log.puts("DatabaseAuthentication for #{user} could not be created. #{dba.errors.full_messages}") + @log.puts( + "DatabaseAuthentication for #{user} could not be created. #{dba.errors.full_messages}" + ) end end @@ -31,13 +33,12 @@ def create_auth_for_user(user) # created. def pools(pools_string) inventory_pools = [] - pool_names = pools_string.split(';').map{|string| string.strip} + pool_names = pools_string.split(';').map(&:strip) pool_names.each do |name| inventory_pool = InventoryPool.where(name: name).first if inventory_pool.nil? - inventory_pool = InventoryPool.create(name: name, - shortname: name[0..2].upcase, - email: 'pool@example.com') + inventory_pool = + InventoryPool.create(name: name, shortname: name[0..2].upcase, email: 'pool@example.com') end inventory_pools << inventory_pool end @@ -52,24 +53,24 @@ def give_role(user, role, inventory_pool) end end - def create_basic_elements(user, options = {}) - role = 'customer' - role = options[:role] if options[:role] - create_auth_for_user(user) - inventory_pools = pools(options[:inventory_pools]) - inventory_pools.each do |ip| - give_role(user, role, ip) - end + role = 'customer' + role = options[:role] if options[:role] + create_auth_for_user(user) + inventory_pools = pools(options[:inventory_pools]) + inventory_pools.each { |ip| give_role(user, role, ip) } end def create_user(options = {}) - user = User.new(email: options[:email], - login: options[:login], - firstname: options[:firstname], - lastname: options[:lastname], - phone: options[:phone], - authentication_system: AuthenticationSystem.where(class_name: 'DatabaseAuthentication').first) + user = + User.new( + email: options[:email], + login: options[:login], + firstname: options[:firstname], + lastname: options[:lastname], + phone: options[:phone], + authentication_system: AuthenticationSystem.where(class_name: 'DatabaseAuthentication').first + ) user.extended_info = {} user.extended_info['department'] = options[:department] user.extended_info['program'] = options[:program] @@ -82,14 +83,16 @@ def create_user(options = {}) end def csv_to_user_options(csv) - {email: csv['mail'], - login: csv['login'], - firstname: csv['GivenName'], - lastname: csv['sn'], - phone: csv['telephoneNumber'], - department: csv['department'], - program: csv['Program and year'], - inventory_pools: csv['Inventory pools']} + { + email: csv['mail'], + login: csv['login'], + firstname: csv['GivenName'], + lastname: csv['sn'], + phone: csv['telephoneNumber'], + department: csv['department'], + program: csv['Program and year'], + inventory_pools: csv['Inventory pools'] + } end @log = File.open('/tmp/user_import.log', 'a+') @@ -98,16 +101,14 @@ def csv_to_user_options(csv) # Import managers if File.exists?('/tmp/managers.csv') @log.puts('---', 'Importing managers from /tmp/managers.csv') - CSV.open('/tmp/managers.csv', 'r', { col_sep: "\t", quote_char: "\"", headers: true}).each do |csv| - create_user(csv_to_user_options(csv).merge(role: 'inventory_manager')) - end + CSV.open('/tmp/managers.csv', 'r', { col_sep: 'undefined', quote_char: '"', headers: true }) + .each { |csv| create_user(csv_to_user_options(csv).merge(role: 'inventory_manager')) } end if File.exists?('/tmp/customers.csv') @log.puts('---', 'Importing customers from /tmp/customers.csv') - CSV.open('/tmp/customers.csv', 'r', { col_sep: "\t", quote_char: "\"", headers: true}).each do |csv| - create_user(csv_to_user_options(csv)) - end + CSV.open('/tmp/customers.csv', 'r', { col_sep: 'undefined', quote_char: '"', headers: true }) + .each { |csv| create_user(csv_to_user_options(csv)) } end @log.close diff --git a/doc/import_export/exeter_import_of_items.rb b/doc/import_export/exeter_import_of_items.rb index c344478824..eb99ed5bce 100644 --- a/doc/import_export/exeter_import_of_items.rb +++ b/doc/import_export/exeter_import_of_items.rb @@ -11,16 +11,18 @@ @errorlog = File.open('/tmp/import_errors.txt', 'w+') @itemlog = File.open('/tmp/import_items.txt', 'w+') -items_to_import = CSV.open(import_file, col_sep: "\t", headers: true) +items_to_import = CSV.open(import_file, col_sep: 'undefined', headers: true) def log_error(error, item) @errorlog.puts "ERROR: #{error}. --- Item: #{item}" end def create_model(item) - m = Model.where(:product => item['Product'], - :version => item['Version'], - :manufacturer => item['Manufacturer']).first_or_create + m = + Model.where( + product: item['Product'], version: item['Version'], manufacturer: item['Manufacturer'] + ) + .first_or_create m.description = item['Description'] if item['Description'] if m.save return m @@ -30,9 +32,8 @@ def create_model(item) end def create_location(item) - b = Building.where(:name => item['Building']).first_or_create - Location.where(:building => b, - :room => item['Room']).first_or_create + b = Building.where(name: item['Building']).first_or_create + Location.where(building: b, room: item['Room']).first_or_create end items_to_import.each do |item| @@ -44,11 +45,9 @@ def create_location(item) next end i.model = create_model(item) - - category = Category.where(:name => item['Categories']).first_or_create - unless i.model.categories.include?(category) - i.model.categories << category - end + + category = Category.where(name: item['Categories']).first_or_create + i.model.categories << category unless i.model.categories.include?(category) i.inventory_code = item['Inventory Code'] i.name = item['Name'] @@ -66,11 +65,10 @@ def create_location(item) i.is_incomplete = false if item['Completeness'] == '1' # Ownership - owner_ip = InventoryPool.where(:name => 'Guild Music').first + owner_ip = InventoryPool.where(name: 'Guild Music').first i.owner = owner_ip i.inventory_pool = owner_ip - # Responsible department #unless item['Verantwortliche Abteilung'] == 'frei' # responsible_ip = InventoryPool.where(name: item['Verantwortliche Abteilung']).first @@ -78,14 +76,13 @@ def create_location(item) #end if i.save - # puts "Item imported correctly:" @successes += 1 @itemlog.puts(i.inspect) else @failures += 1 @errorlog.puts "Could not import item #{i.inventory_code}. Errors: #{i.errors.full_messages}" end - + # puts "Item imported correctly:" end puts '-----------------------------------------' @@ -93,6 +90,5 @@ def create_location(item) puts "#{@successes} successes, #{@failures} failures" puts '-----------------------------------------' - @errorlog.close @itemlog.close diff --git a/doc/import_export/hslu_csv_import_of_items.rb b/doc/import_export/hslu_csv_import_of_items.rb index aa6063111c..569fa277f0 100644 --- a/doc/import_export/hslu_csv_import_of_items.rb +++ b/doc/import_export/hslu_csv_import_of_items.rb @@ -2,25 +2,18 @@ # ./script/console # require 'doc/csv_import_of_items' - - - #import_file = "/tmp/items.csv" import_file = '/tmp/items2.csv' - @failures = 0 @successes = 0 def create_item(model_name, inventory_code, serial_number, manufacturer, category, accessory_string, note, price, invoice_date) - m = Model.find_by_product(model_name) - if m.nil? - m = create_model(model_name, category, manufacturer, accessory_string) - end - + m = create_model(model_name, category, manufacturer, accessory_string) if m.nil? + ip = InventoryPool.find_or_create_by_name('HSLU') - + i = Item.new i.model = m i.inventory_code = inventory_code @@ -32,7 +25,7 @@ def create_item(model_name, inventory_code, serial_number, manufacturer, categor i.inventory_pool = ip i.price = price i.invoice_date = invoice_date - + if i.save puts 'Item imported correctly:' @successes += 1 @@ -43,28 +36,26 @@ def create_item(model_name, inventory_code, serial_number, manufacturer, categor puts i.errors.full_messages puts i.inspect end - + puts '-----------------------------------------' puts 'DONE' puts "#{@successes} successes, #{@failures} failures" puts '-----------------------------------------' - end def create_model(name, category, manufacturer, accessory_string) - puts "creating model: #{name}, #{category}, #{manufacturer}, #{accessory_string}" - + if category.blank? c = Category.find_or_create_by_name('Keine Kategorie') - else + else c = Category.find_or_create_by_name(category) end - + m = Model.create(name: name, manufacturer: manufacturer) m.categories << c - unless accessory_string.blank? + unless accessory_string.blank? accessory_string.split('-').each do |string| unless string.blank? acc = Accessory.create(name: string.strip) @@ -90,32 +81,31 @@ def create_model(name, category, manufacturer, accessory_string) # 6: Defekt: (-> Notiz) items_to_import.each do |item| - model_name = "#{item["Gerätebezeichnung"]} #{item["Typenbezeichnung"]}" - + model_name = "#{item['Gerätebezeichnung']} #{item['Typenbezeichnung']}" + if model_name.blank? puts 'Skipping item with blank model name.' next end - - note = "#{item["Referenzdatei Inventar"]} #{item["Fehler Reparatur"]}" - + + note = "#{item['Referenzdatei Inventar']} #{item['Fehler Reparatur']}" + price = item['Preis_Neu'].to_f puts "price parsed to #{price}" # The purchase dates in the source file are only years, but Date.parse can't handle that, # so we add -01-01 to force to January 1. invoice_date = Date.parse("#{item['Kaufdatum'].strip}-01-01") unless item['Kaufdatum'].blank? puts "purchase date parsed to #{invoice_date}" - - create_item(model_name, - item['Inventarnummer_ID'], - item['Seriennummer'], - item['Marke'], - item['Gerätekategorie'], - item['Zubehör'], - note, - price, - invoice_date) -end - - + create_item( + model_name, + item['Inventarnummer_ID'], + item['Seriennummer'], + item['Marke'], + item['Gerätekategorie'], + item['Zubehör'], + note, + price, + invoice_date + ) +end diff --git a/doc/import_export/retire_items_from_csv.rb b/doc/import_export/retire_items_from_csv.rb index 5c9bb7c7fc..9d6361be31 100644 --- a/doc/import_export/retire_items_from_csv.rb +++ b/doc/import_export/retire_items_from_csv.rb @@ -10,7 +10,7 @@ @errorlog = File.open('/tmp/import_errors.txt', 'w+') -items_to_import = CSV.open(import_file, col_sep: "\t", headers: true) +items_to_import = CSV.open(import_file, col_sep: 'undefined', headers: true) def log_error(error, item) @errorlog.puts "ERROR: #{error}. --- Item: #{item}" @@ -32,7 +32,6 @@ def log_error(error, item) log_error("Item with inventory code #{ic} not found", ic) end #i.note = item["Note"] - end puts '-----------------------------------------' @@ -40,5 +39,4 @@ def log_error(error, item) puts "#{@successes} successes, #{@failures} failures" puts '-----------------------------------------' - @errorlog.close diff --git a/doc/other/adjust_project_numbers.rb b/doc/other/adjust_project_numbers.rb index dd42254ed5..6ed099be61 100644 --- a/doc/other/adjust_project_numbers.rb +++ b/doc/other/adjust_project_numbers.rb @@ -1,25 +1,23 @@ - # Works only on Rails 3, Ruby 1.9 require 'csv' def adjust_from_file(path) logfile = File.open('/tmp/import.log', 'w') - CSV.open(path, col_sep: "\t").each do |csv| - result = add_project_number_to_item(csv[0], csv[1]) - if result == true - msg = "Inventory code: #{csv[0]}, project number: #{csv[1]}" - puts msg - logfile.puts msg - else - msg = "Error processing: #{csv[0]}. Error was: #{result}" - puts msg - logfile.puts msg + CSV.open(path, col_sep: 'undefined').each do |csv| + result = add_project_number_to_item(csv[0], csv[1]) + if result == true + msg = "Inventory code: #{csv[0]}, project number: #{csv[1]}" + puts msg + logfile.puts msg + else + msg = "Error processing: #{csv[0]}. Error was: #{result}" + puts msg + logfile.puts msg end end logfile.close end - def add_project_number_to_item(inventory_code, project_number) inventory_code = inventory_code.split('/')[0] # Split package inventory codes, which are foo/bar @@ -27,11 +25,7 @@ def add_project_number_to_item(inventory_code, project_number) if item item.properties[:project_number] = project_number item.properties[:reference] = 'investment' - if item.save - return true - else - return item.errors.full_messages - end + item.save ? return true : return item.errors.full_messages else return "Item #{inventory_code} not found" end diff --git a/doc/other/barcode_maker.rb b/doc/other/barcode_maker.rb index 2509643684..946931b8bb 100755 --- a/doc/other/barcode_maker.rb +++ b/doc/other/barcode_maker.rb @@ -1,6 +1,5 @@ #!/usr/bin/ruby - # The EPS output needs Inkscape installed require 'rubygems' @@ -9,41 +8,40 @@ require 'barby/outputter/cairo_outputter' class BarcodeMaker - - def initialize(string) - @string = string - @height = 25 - @bc = Barby::Code128B.new(@string.to_s) - end - - def make_eps - puts "Making EPS for #{@string}" - make_svg - infile = "svg/barcode_#{@string}.svg" - outfile = "eps/barcode_#{@string}.eps" - #command = %x[inkscape -z -T -E #\{outfile\} #\{infile\}] - system "inkscape -z -T -E #{outfile} #{infile}" - end - - def make_svg - unless File.exists?("svg/barcode_#{@string}.svg") - puts "Making SVG for #{@string}" - f = File.open("svg/barcode_#{@string}.svg", 'w') - f.write @bc.to_svg(height: @height, margin: 5) - f.close - else - puts 'SVG already there' - end - end - + def initialize(string) + @string = string + @height = 25 + @bc = Barby::Code128B.new(@string.to_s) + end + + def make_eps + puts "Making EPS for #{@string}" + make_svg + infile = "svg/barcode_#{@string}.svg" + outfile = "eps/barcode_#{@string}.eps" + #command = %x[inkscape -z -T -E #\{outfile\} #\{infile\}] + system "inkscape -z -T -E #{outfile} #{infile}" + end + + def make_svg + unless File.exists?("svg/barcode_#{@string}.svg") + puts "Making SVG for #{@string}" + f = File.open("svg/barcode_#{@string}.svg", 'w') + f.write @bc.to_svg(height: @height, margin: 5) + f.close + else + puts 'SVG already there' + end + end end - - (25000...26000).each do |i| - puts "Making barcode #{i}" - foo = BarcodeMaker.new("AVZ#{i}") - foo.make_eps rescue 'EPS failed' - puts 'the world has ended' + puts "Making barcode #{i}" + foo = BarcodeMaker.new("AVZ#{i}") + begin + foo.make_eps + rescue StandardError + 'EPS failed' + end + puts 'the world has ended' end - diff --git a/doc/other/csv_mike_updater.rb b/doc/other/csv_mike_updater.rb index 807f327276..202726a522 100644 --- a/doc/other/csv_mike_updater.rb +++ b/doc/other/csv_mike_updater.rb @@ -1,20 +1,15 @@ - - require 'rubygems' - - unfound = [] require 'csv' CSV.foreach('/tmp/mike_update.csv', col_sep: ';', headers: :first_row) do |row| - owner = row[0] number = row[1] ip = row[6] date = row[8] - parsed_date = Date.strptime(date, '%m/%d/%Y') + parsed_date = Date.strptime(date, '%m/%d/%Y') ownerpool = InventoryPool.find_by_name(owner) responsible = InventoryPool.find_by_name(ip) @@ -39,8 +34,6 @@ #item.invoice_date = parsed_date item.save puts '-----------------' - end unfound = unfound.uniq - diff --git a/doc/other/merge_models.rb b/doc/other/merge_models.rb index 8d547273d1..1c5f94a50c 100644 --- a/doc/other/merge_models.rb +++ b/doc/other/merge_models.rb @@ -2,8 +2,19 @@ model_to = Model.find 8607 Model.transaction do - %w(items reservations partitions model_links accessories attachments properties models_compatibles).each do |relations| - Model.connection.execute "UPDATE #{relations} SET model_id = #{model_to.id} WHERE model_id = #{model_from.id}" + %w[ + items + reservations + partitions + model_links + accessories + attachments + properties + models_compatibles + ] + .each do |relations| + Model.connection.execute "UPDATE #{relations} SET model_id = #{model_to + .id} WHERE model_id = #{model_from.id}" end model_from.destroy diff --git a/engines/leihs_admin/app/controllers/leihs_admin/admin_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/admin_controller.rb index f3e612ca1b..50045c6db5 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/admin_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/admin_controller.rb @@ -2,26 +2,23 @@ module LeihsAdmin class AdminController < ApplicationController layout 'leihs_admin/admin' - before_action do - not_authorized!(redirect_path: main_app.root_path) unless admin? - end + before_action { not_authorized!(redirect_path: main_app.root_path) unless admin? } unless Rails.env.production? def top routes = Engine.routes.routes @index_names = - routes - .select do |r| + routes.select do |r| begin r.path.spec.left.memo.defaults[:action] == 'index' - rescue + rescue StandardError nil end end - .map(&:name) - .reject { |n| ['individual_audits', 'users'].include? n } - .push('settings') - .sort + .map(&:name) + .reject { |n| ['individual_audits', 'users'].include? n } + .push('settings') + .sort render 'leihs_admin/top' end diff --git a/engines/leihs_admin/app/controllers/leihs_admin/audits_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/audits_controller.rb index 1051af8085..bc52f37fba 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/audits_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/audits_controller.rb @@ -11,9 +11,7 @@ def index @end_date = end_date_param @search_term = search_term_param end - format.js do - render partial: 'leihs_admin/audits/audits', collection: @audits - end + format.js { render partial: 'leihs_admin/audits/audits', collection: @audits } end end @@ -21,24 +19,29 @@ def index # rubocop:disable Metrics/MethodLength def audits - Audit - .filter(start_date: Date.parse(start_date_param), - end_date: Date.parse(end_date_param), - auditable_id: id_param, - auditable_type: type_param, - user_id: user_id_param, - search_term: search_term_param) - .select(<<-SQL) - audits.request_uuid, + Audit.filter( + start_date: Date.parse(start_date_param), + end_date: Date.parse(end_date_param), + auditable_id: id_param, + auditable_type: type_param, + user_id: user_id_param, + search_term: search_term_param + ) + .select( + <<-SQL + audits.request_uuid, audits.user_id, array_agg(row_to_json(audits.*)) AS rows, MAX(audits.created_at) AS created_at SQL - .group(<<-SQL) - audits.request_uuid, + ) + .group( + <<-SQL + audits.request_uuid, audits.user_id, audits.created_at::date SQL + ) .reorder('created_at DESC') .offset(PER_PAGE * page_param) .limit(PER_PAGE) diff --git a/engines/leihs_admin/app/controllers/leihs_admin/buildings_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/buildings_controller.rb index 5b59019bf3..4742429806 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/buildings_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/buildings_controller.rb @@ -1,14 +1,11 @@ module LeihsAdmin class BuildingsController < AdminController - before_action only: [:edit, :update, :destroy] do @building = Building.find(params[:id]) end def index - respond_to do |format| - format.html { @buildings = Building.filter(params) } - end + respond_to { |format| format.html { @buildings = Building.filter(params) } } end def new @@ -18,8 +15,7 @@ def new def create @building = Building.create params[:building] if @building.persisted? - flash[:notice] = \ - _('Building together with a general room successfully created') + flash[:notice] = _('Building together with a general room successfully created') redirect_to action: :index else flash.now[:error] = @building.errors.full_messages.uniq.join(', ') @@ -27,8 +23,7 @@ def create end end - def edit - end + def edit; end def update if @building.update_attributes params[:building] @@ -49,6 +44,5 @@ def destroy end redirect_to action: :index end - end end diff --git a/engines/leihs_admin/app/controllers/leihs_admin/fields_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/fields_controller.rb index 36768f882a..284dfa5d34 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/fields_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/fields_controller.rb @@ -1,10 +1,11 @@ module LeihsAdmin class FieldsController < AdminController - def index - @grouped_fields = Field.unscoped.order(:position).sort_by do |f| - [Field::GROUPS_ORDER.index(f.data['group']) || 999, f.position] - end.group_by { |f| f.data['group'] } + @grouped_fields = + Field.unscoped.order(:position).sort_by do |f| + [Field::GROUPS_ORDER.index(f.data['group']) || 999, f.position] + end + .group_by { |f| f.data['group'] } end def batch_update @@ -29,9 +30,7 @@ def batch_update def get_active_status_value!(field, field_spec) case field_spec.require(:active) when '0' - if field.data['required'] - raise "Disabling a required field #{field.id} is not possible!" - end + raise "Disabling a required field #{field.id} is not possible!" if field.data['required'] false when '1' true diff --git a/engines/leihs_admin/app/controllers/leihs_admin/fields_editor_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/fields_editor_controller.rb index ff9f09ed3f..dddcbb31db 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/fields_editor_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/fields_editor_controller.rb @@ -1,6 +1,5 @@ module LeihsAdmin class FieldsEditorController < AdminController - def edit_react @props = { all_fields_path: fields_editor_all_fields_path, @@ -14,22 +13,12 @@ def edit_react def destroy Field.unscoped.find(params[:id]).destroy! - respond_to do |format| - format.json do - render(status: :ok, json: {}) - end - end + respond_to { |format| format.json { render(status: :ok, json: {}) } } end def groups - props = { - groups: Field.unscoped.all.map { |f| f.data['group'] }.uniq - } - respond_to do |format| - format.json do - render(status: :ok, json: props) - end - end + props = { groups: Field.unscoped.all.map { |f| f.data['group'] }.uniq } + respond_to { |format| format.json { render(status: :ok, json: props) } } end def single_field @@ -37,40 +26,26 @@ def single_field attribute = field.data['attribute'] property = attribute[1] - items_count = Item.where( - "items.properties::json->>'#{property}' is not null" - ).count + items_count = Item.where("items.properties::json->>'#{property}' is not null").count props = { field: presenterify_field(field), items_count: items_count, groups: Field.unscoped.all.map { |f| f.data['group'] }.uniq } - respond_to do |format| - format.json do - render(status: :ok, json: props) - end - end + respond_to { |format| format.json { render(status: :ok, json: props) } } end def all_fields fields = Field.unscoped.all.map { |f| presenterify_field(f) } - props = { - fields: fields - } - respond_to do |format| - format.json do - render(status: :ok, json: props) - end - end + props = { fields: fields } + respond_to { |format| format.json { render(status: :ok, json: props) } } end def new_react if Field.unscoped.where(id: params[:field][:id]).first respond_to do |format| - format.json do - render(status: :ok, json: { result: 'field-exists-already' }) - end + format.json { render(status: :ok, json: { result: 'field-exists-already' }) } end return end @@ -82,11 +57,7 @@ def new_react field.dynamic = true field.active = params[:field][:active] field.save! - respond_to do |format| - format.json do - render(status: :ok, json: { result: 'field-saved' }) - end - end + respond_to { |format| format.json { render(status: :ok, json: { result: 'field-saved' }) } } end def update_react @@ -96,11 +67,7 @@ def update_react field.position = params[:field][:position] field.active = params[:field][:active] field.save! - respond_to do |format| - format.json do - render(status: :ok, json: { result: 'field-saved' }) - end - end + respond_to { |format| format.json { render(status: :ok, json: { result: 'field-saved' }) } } end private diff --git a/engines/leihs_admin/app/controllers/leihs_admin/inventory_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/inventory_controller.rb index 920c29cfae..899079badc 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/inventory_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/inventory_controller.rb @@ -1,7 +1,6 @@ module LeihsAdmin # rubocop:disable Metrics/ClassLength class InventoryController < AdminController - def csv_export send_data InventoryPool.csv_export(nil, params), type: 'text/csv; charset=utf-8; header=present', @@ -10,8 +9,7 @@ def csv_export def excel_export send_data InventoryPool.excel_export(nil, params), - type: 'application/xlsx', - disposition: "filename=#{_('Inventory')}.xlsx" + type: 'application/xlsx', disposition: "filename=#{_('Inventory')}.xlsx" end def quick_csv_export @@ -29,17 +27,9 @@ def quick_csv_export def quick_excel_export objects = objects_for_quick_export header = header_for_export(objects) - data = Export.excel_string( - header, - objects, - worksheet_name: _('Inventory') - ) + data = Export.excel_string(header, objects, worksheet_name: _('Inventory')) - send_data( - data, - type: 'application/xlsx', - disposition: "filename=#{_('Inventory')}.xlsx" - ) + send_data(data, type: 'application/xlsx', disposition: "filename=#{_('Inventory')}.xlsx") end private @@ -66,25 +56,20 @@ def accessories_to_string(from_db) def compatibles_to_string(from_db) json = JSON.parse(from_db) json.map do |e| - if e['version'] - e['product'].to_s + ' ' + e['version'].to_s - else - e['product'].to_s - end - end.join('; ') + e['version'] ? e['product'].to_s + ' ' + e['version'].to_s : e['product'].to_s + end + .join('; ') end def properties_to_string(from_db) json = JSON.parse(from_db) - json.map do |e| - e['key'].to_s + ': ' + e['value'].to_s - end.join('; ') + json.map { |e| e['key'].to_s + ': ' + e['value'].to_s }.join('; ') end # rubocop:disable Metrics/MethodLength def item_objects_for_quick_export query = <<-SQL - + with prop_fields as ( @@ -223,64 +208,61 @@ def item_objects_for_quick_export SQL result = ActiveRecord::Base.connection.exec_query(query).to_hash - objects = result.map do |row| - - object = { - _('Type') => if row['type'] == 'Model' - 'Item' - elsif row['type'] == 'Software' - 'License' - else - 'Unknown' - end, - _('Product') => row['product'], - _('Version') => row['version'], - _('Inventory Code') => row['inventory_code'], - _('Created at') => row['created_at'], - _('Updated at') => row['updated_at'], - _('Manufacturer') => row['manufacturer'], - _('Building') => row['building_name'], - _('Room') => row['room_name'], - _('Shelf') => row['shelf'], - _('Description') => row['description'], - _('Technical Detail') => row['technical_detail'], - _('Internal Description') => row['internal_description'], - _('Important notes for hand over') => row['hand_over_note'], - _('Responsible department') => nil, - _('Initial Price') => nil, - _('Serial Number') => row['serial_number'], - _('Retired') => row['retired'], - _('Retired Reason') => row['retired_reason'], - _('Complete') => (row['is_incomplete'] ? false : true), - _('borrowable') => row['is_borrowable'], - _('Status note') => row['status_note'], - _('Relevant for inventory') => row['is_inventory_relevant'], - _('Owner') => row['owner_name'], - _('Last Checked') => row['last_check'], - _('Invoice Number') => row['invoice_number'], - _('Invoice Date') => row['invoice_date'], - _('Supplier') => row['supplier_name'], - _('Initial Price') => row['price'], - # _('Additional Data') => \ - # if row['field_properties'] - # JSON.parse(row['field_properties']).map do |e| - # e['label'].to_s + ': ' + e['value'].to_s - # end.join('; ') - # end, - _('Categories') => categories_to_string(row['categories']), - _('Accessories') => accessories_to_string(row['accessories']), - _('Compatibles') => compatibles_to_string(row['compatibles']), - _('Properties') => properties_to_string(row['properties']) - } - - if row['field_properties'] - JSON.parse(row['field_properties']).each do |p| - object[p['label']] = p['value'] + objects = + result.map do |row| + object = { + _('Type') => + if row['type'] == 'Model' + 'Item' + elsif row['type'] == 'Software' + 'License' + else + 'Unknown' + end, + _('Product') => row['product'], + _('Version') => row['version'], + _('Inventory Code') => row['inventory_code'], + _('Created at') => row['created_at'], + _('Updated at') => row['updated_at'], + _('Manufacturer') => row['manufacturer'], + _('Building') => row['building_name'], + _('Room') => row['room_name'], + _('Shelf') => row['shelf'], + _('Description') => row['description'], + _('Technical Detail') => row['technical_detail'], + _('Internal Description') => row['internal_description'], + _('Important notes for hand over') => row['hand_over_note'], + _('Responsible department') => nil, + _('Initial Price') => nil, + _('Serial Number') => row['serial_number'], + _('Retired') => row['retired'], + _('Retired Reason') => row['retired_reason'], + _('Complete') => (row['is_incomplete'] ? false : true), + _('borrowable') => row['is_borrowable'], + _('Status note') => row['status_note'], + _('Relevant for inventory') => row['is_inventory_relevant'], + _('Owner') => row['owner_name'], + _('Last Checked') => row['last_check'], + _('Invoice Number') => row['invoice_number'], + _('Invoice Date') => row['invoice_date'], + _('Supplier') => row['supplier_name'], + _('Initial Price') => row['price'], + _( + # end, + 'Categories' + ) => + categories_to_string(row['categories']), + _('Accessories') => accessories_to_string(row['accessories']), + _('Compatibles') => compatibles_to_string(row['compatibles']), + _('Properties') => properties_to_string(row['properties']) + } + + if row['field_properties'] + JSON.parse(row['field_properties']).each { |p| object[p['label']] = p['value'] } end - end - object - end + object + end objects end # rubocop:enable Metrics/MethodLength diff --git a/engines/leihs_admin/app/controllers/leihs_admin/inventory_pools_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/inventory_pools_controller.rb index b5a3e9fbe7..a547333c0f 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/inventory_pools_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/inventory_pools_controller.rb @@ -1,16 +1,16 @@ module LeihsAdmin class InventoryPoolsController < AdminController - def index @inventory_pools = InventoryPool.unscoped.search(params[:search_term]) - @inventory_pools = case params[:activity] - when nil, 'active' - @inventory_pools.where(is_active: true) - when 'inactive' - @inventory_pools.where(is_active: false) - else - @inventory_pools - end + @inventory_pools = + case params[:activity] + when nil, 'active' + @inventory_pools.where(is_active: true) + when 'inactive' + @inventory_pools.where(is_active: false) + else + @inventory_pools + end @inventory_pools = @inventory_pools.sort end @@ -79,11 +79,9 @@ def destroy def create_mail_templates!(inventory_pool) MailTemplate.where(is_template_template: true).each do |mt| - MailTemplate.create! \ - mt.attributes - .reject { |k, _| k == 'id' } - .merge(is_template_template: false, - inventory_pool_id: inventory_pool.id) + MailTemplate.create! mt.attributes.reject { |k, _| k == 'id' }.merge( + is_template_template: false, inventory_pool_id: inventory_pool.id + ) end end @@ -101,25 +99,17 @@ def inventory_managers_access_rights to_add = submitted_inventory_manager_ids - existing_inventory_manager_ids to_add.each do |id| user = User.find id - ar = \ - user - .access_rights - .find_or_initialize_by(inventory_pool: @inventory_pool) + ar = user.access_rights.find_or_initialize_by(inventory_pool: @inventory_pool) ar.update_attributes!(role: :inventory_manager, deleted_at: nil) end end def existing_inventory_manager_ids - @existing_inventory_manager_ids ||= \ - @inventory_pool \ - .users - .inventory_managers - .pluck(:id) - .sort + @existing_inventory_manager_ids ||= @inventory_pool.users.inventory_managers.pluck(:id).sort end def submitted_inventory_manager_ids - @submitted_inventory_manager_ids ||= \ + @submitted_inventory_manager_ids ||= if params[:inventory_managers] and params[:inventory_managers][:user_ids] params[:inventory_managers][:user_ids].sort else diff --git a/engines/leihs_admin/app/controllers/leihs_admin/mail_templates_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/mail_templates_controller.rb index 61cdda6174..88f41e1487 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/mail_templates_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/mail_templates_controller.rb @@ -1,25 +1,21 @@ module LeihsAdmin class MailTemplatesController < AdminController - def index - @template_templates = \ - MailTemplate::TEMPLATE_TYPES - .to_a - .sort { |x, y| "#{x.second}#{x.first}" <=> "#{y.second}#{y.first}" } + @template_templates = + MailTemplate::TEMPLATE_TYPES.to_a.sort do |x, y| + "#{x.second}#{x.first}" <=> "#{y.second}#{y.first}" + end end def edit - @mail_templates = MailTemplate.where(name: params[:name], - is_template_template: true) + @mail_templates = MailTemplate.where(name: params[:name], is_template_template: true) end def update @mail_templates = [] @errors = [] - params[:mail_templates].each do |p| - get_and_update_and_validate p - end + params[:mail_templates].each { |p| get_and_update_and_validate p } if @errors.empty? redirect_to '/admin/mail_templates' @@ -32,19 +28,17 @@ def update private def get_and_update_and_validate(p) - mt = \ - MailTemplate \ - .find_or_initialize_by( - inventory_pool_id: nil, - name: p[:name], - language: Language.find_by(locale_name: p[:language]), - format: p[:format]) + mt = + MailTemplate.find_or_initialize_by( + inventory_pool_id: nil, + name: p[:name], + language: Language.find_by(locale_name: p[:language]), + format: p[:format] + ) @mail_templates << mt - unless mt.update_attributes(body: p[:body]) - @errors << mt.errors.full_messages - end + @errors << mt.errors.full_messages unless mt.update_attributes(body: p[:body]) end end end diff --git a/engines/leihs_admin/app/controllers/leihs_admin/rooms_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/rooms_controller.rb index 97d0938fa8..75ca4c395a 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/rooms_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/rooms_controller.rb @@ -1,22 +1,11 @@ module LeihsAdmin class RoomsController < AdminController - def index - @rooms = \ - Room - .includes(:building) - .order('buildings.name ASC, lower(rooms.name) ASC') - if search_term_param - @rooms = @rooms.search(search_term_param) - end + @rooms = Room.includes(:building).order('buildings.name ASC, lower(rooms.name) ASC') + @rooms = @rooms.search(search_term_param) if search_term_param @rooms = @rooms.default_paginate(paginate_params) - respond_to do |format| - format.html - format.js do - render partial: 'leihs_admin/rooms/room', collection: @rooms - end - end + respond_to(&:html) end def new @@ -55,6 +44,7 @@ def update def destroy @room = Room.find(room_id_param) + begin @room.destroy flash[:success] = _('%s successfully deleted') % _('Room') @@ -81,6 +71,5 @@ def paginate_params def search_term_param params.fetch(:search_term, nil) end - end end diff --git a/engines/leihs_admin/app/controllers/leihs_admin/settings_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/settings_controller.rb index ad9f523293..bd1485d549 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/settings_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/settings_controller.rb @@ -1,6 +1,5 @@ module LeihsAdmin class SettingsController < AdminController - def edit @settings = app_settings || Setting.new end @@ -16,7 +15,5 @@ def update render :edit end end - end - end diff --git a/engines/leihs_admin/app/controllers/leihs_admin/statistics_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/statistics_controller.rb index 09931eb93b..535ee2cc8c 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/statistics_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/statistics_controller.rb @@ -1,43 +1,39 @@ module LeihsAdmin class StatisticsController < AdminController - before_action do - @statistics = ['Who borrowed the most things?', - 'Which inventory pool is busiest?', - 'Who bought the most items?', - 'Which item is busiest?', - 'Which model is busiest?', - 'Which inventory pool has the most contracts?'] + @statistics = [ + 'Who borrowed the most things?', + 'Which inventory pool is busiest?', + 'Who bought the most items?', + 'Which item is busiest?', + 'Which model is busiest?', + 'Which inventory pool has the most contracts?' + ] params[:start_date] ||= I18n.l 30.days.ago.to_date params[:end_date] ||= I18n.l Time.zone.today end - def index - end + def index; end def show - @list = case params[:id] - when 'Who borrowed the most things?'.parameterize - Statistics::Base.hand_overs([User, Model], params.to_unsafe_hash) - when 'Which inventory pool is busiest?'.parameterize - Statistics::Base.hand_overs([InventoryPool, Model], - params.to_unsafe_hash) - when 'Who bought the most items?'.parameterize - Statistics::Base.item_values([InventoryPool, Model], - params.to_unsafe_hash) - when 'Which item is busiest?'.parameterize - Statistics::Base.hand_overs([Item, User], params.to_unsafe_hash) - when 'Which model is busiest?'.parameterize - Statistics::Base.hand_overs([Model, Item], params.to_unsafe_hash) - when 'Which inventory pool has the most contracts?'.parameterize - Statistics::Base.contracts([InventoryPool, User], - params.to_unsafe_hash) - else - redirect_to admin.statistics_path - end + @list = + case params[:id] + when 'Who borrowed the most things?'.parameterize + Statistics::Base.hand_overs([User, Model], params.to_unsafe_hash) + when 'Which inventory pool is busiest?'.parameterize + Statistics::Base.hand_overs([InventoryPool, Model], params.to_unsafe_hash) + when 'Who bought the most items?'.parameterize + Statistics::Base.item_values([InventoryPool, Model], params.to_unsafe_hash) + when 'Which item is busiest?'.parameterize + Statistics::Base.hand_overs([Item, User], params.to_unsafe_hash) + when 'Which model is busiest?'.parameterize + Statistics::Base.hand_overs([Model, Item], params.to_unsafe_hash) + when 'Which inventory pool has the most contracts?'.parameterize + Statistics::Base.contracts([InventoryPool, User], params.to_unsafe_hash) + else + redirect_to admin.statistics_path + end end - end - end diff --git a/engines/leihs_admin/app/controllers/leihs_admin/suppliers_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/suppliers_controller.rb index 72121d6622..8249be9d73 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/suppliers_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/suppliers_controller.rb @@ -1,6 +1,5 @@ module LeihsAdmin class SuppliersController < AdminController - before_action only: [:show, :edit, :update, :destroy] do @supplier = Supplier.find(params[:id]) end @@ -9,8 +8,8 @@ def index filters = params.permit(:search_term, :pool_id) @suppliers = Supplier.filter(**filters.to_h.symbolize_keys) @suppliers_total_count = Supplier.all.count - @pools_with_suppliers = InventoryPool.joins(:items) - .where.not('items.supplier_id': nil).distinct.order(:name) + @pools_with_suppliers = + InventoryPool.joins(:items).where.not(:"items.supplier_id" => nil).distinct.order(:name) end def new @@ -29,11 +28,7 @@ def create end def show - @items = \ - @supplier \ - .items - .includes(:model, :inventory_pool) - .group_by(&:inventory_pool) + @items = @supplier.items.includes(:model, :inventory_pool).group_by(&:inventory_pool) end alias edit show @@ -58,7 +53,5 @@ def destroy end redirect_to action: :index end - end - end diff --git a/engines/leihs_admin/app/controllers/leihs_admin/users_controller.rb b/engines/leihs_admin/app/controllers/leihs_admin/users_controller.rb index 0da0a83167..af29739e81 100644 --- a/engines/leihs_admin/app/controllers/leihs_admin/users_controller.rb +++ b/engines/leihs_admin/app/controllers/leihs_admin/users_controller.rb @@ -1,16 +1,10 @@ module LeihsAdmin class UsersController < AdminController - def index @role = params.permit(:role)[:role] @users = User.filter params, current_inventory_pool - respond_to do |format| - format.json do - render json: @users - end - end + respond_to { |format| format.json { render json: @users } } end - end end diff --git a/engines/leihs_admin/app/helpers/leihs_admin/application_helper.rb b/engines/leihs_admin/app/helpers/leihs_admin/application_helper.rb index 4ce297336c..cc128a9258 100644 --- a/engines/leihs_admin/app/helpers/leihs_admin/application_helper.rb +++ b/engines/leihs_admin/app/helpers/leihs_admin/application_helper.rb @@ -11,6 +11,5 @@ def sign_out_path '/sign-out' end end - end end diff --git a/engines/leihs_admin/config/routes.rb b/engines/leihs_admin/config/routes.rb index 3931a6c9b5..8c42343b3b 100644 --- a/engines/leihs_admin/config/routes.rb +++ b/engines/leihs_admin/config/routes.rb @@ -1,28 +1,27 @@ LeihsAdmin::Engine.routes.draw do - root to: redirect('/admin/inventory_pools') - - unless Rails.env.production? - get 'top', to: 'admin#top' - end - resources :buildings, except: :show + get 'top', to: 'admin#top' unless Rails.env.production? + + resources :buildings, except: :show resources :inventory_pools, except: :show - resources :locations, only: :destroy - resources :rooms, except: :show - resources :statistics, only: [:index, :show] - resources :suppliers, except: [] - resources :users, only: :index + resources :locations, only: :destroy + resources :rooms, except: :show + resources :statistics, only: [:index, :show] + resources :suppliers, except: [] + resources :users, only: :index # Audits - get 'audits', to: 'audits#index' + get 'audits', to: 'audits#index' get ':type/:id/audits', to: 'audits#index', as: 'individual_audits' # Export inventory of all inventory pools - get 'inventory/csv', :to => 'inventory#csv_export', :as => 'global_inventory_csv_export' - get 'inventory/excel', :to => 'inventory#excel_export', :as => 'global_inventory_excel_export' - get 'inventory/quick_csv', :to => 'inventory#quick_csv_export', :as => 'global_inventory_quick_csv_export' - get 'inventory/quick_excel', :to => 'inventory#quick_excel_export', :as => 'global_inventory_quick_excel_export' + get 'inventory/csv', to: 'inventory#csv_export', as: 'global_inventory_csv_export' + get 'inventory/excel', to: 'inventory#excel_export', as: 'global_inventory_excel_export' + get 'inventory/quick_csv', + to: 'inventory#quick_csv_export', as: 'global_inventory_quick_csv_export' + get 'inventory/quick_excel', + to: 'inventory#quick_excel_export', as: 'global_inventory_quick_excel_export' # Fields get 'fields', to: 'fields#index' @@ -32,7 +31,8 @@ delete 'fields_editor/:id', to: 'fields_editor#destroy' get 'fields_editor/all_fields', to: 'fields_editor#all_fields' get 'fields_editor/groups', to: 'fields_editor#groups' - get 'fields_editor/single_field/(:id)', to: 'fields_editor#single_field', :as => 'fields_editor_single_field' + get 'fields_editor/single_field/(:id)', + to: 'fields_editor#single_field', as: 'fields_editor_single_field' get 'fields_editor/edit_react', to: 'fields_editor#edit_react' put 'fields_editor/new_react', to: 'fields_editor#new_react' post 'fields_editor/update_react', to: 'fields_editor#update_react' @@ -47,5 +47,5 @@ put 'mail_templates/:dir/:name', to: 'mail_templates#update' # Languages - get 'languages', to: 'languages#index' + get 'languages', to: 'languages#index' end diff --git a/engines/leihs_admin/lib/leihs_admin.rb b/engines/leihs_admin/lib/leihs_admin.rb index 4a28d83c86..8db22734b3 100644 --- a/engines/leihs_admin/lib/leihs_admin.rb +++ b/engines/leihs_admin/lib/leihs_admin.rb @@ -1,4 +1,3 @@ require 'leihs_admin/engine' -module LeihsAdmin -end +module LeihsAdmin; end diff --git a/engines/leihs_admin/lib/leihs_admin/engine.rb b/engines/leihs_admin/lib/leihs_admin/engine.rb index b1eb50e649..6b0ae3f987 100644 --- a/engines/leihs_admin/lib/leihs_admin/engine.rb +++ b/engines/leihs_admin/lib/leihs_admin/engine.rb @@ -7,9 +7,7 @@ class Engine < ::Rails::Engine isolate_namespace LeihsAdmin initializer 'engine.assets.precompile' do |app| - app.config.assets.precompile += %w(leihs_admin/admin.css - leihs_admin/admin.js) + app.config.assets.precompile += %w[leihs_admin/admin.css leihs_admin/admin.js] end - end end diff --git a/engines/leihs_admin/spec/steps/audits_steps.rb b/engines/leihs_admin/spec/steps/audits_steps.rb index 0ee5cb2934..bc9692d2a6 100644 --- a/engines/leihs_admin/spec/steps/audits_steps.rb +++ b/engines/leihs_admin/spec/steps/audits_steps.rb @@ -16,9 +16,7 @@ module AuditsSteps include ::Spec::LoginSteps step 'I see the list of audits' do - within '.pages' do - expect(page).to have_selector '.panel' - end + within '.pages' doexpect(page).to have_selector '.panel'end end step 'there is a user whose name contains :term' do |term| @@ -26,40 +24,38 @@ module AuditsSteps end step 'there is an item whose inventory code contains :term' do |term| - @item = FactoryGirl.create(:item, - inventory_code: term, - shelf: Faker::Lorem.word) + @item = FactoryGirl.create(:item, inventory_code: term, shelf: Faker::Lorem.word) end step "there is a 'create' audit which contains :term " \ - "in column 'audited_changes'" do |term| + "in column 'audited_changes'" do |term| FactoryGirl.create(:item, shelf: term) end step "there is a 'create' audit for a user " \ - 'whose name contains :term' do |term| + 'whose name contains :term' do |term| expect(Audit.find_by(action: 'create', auditable_id: @user.id)).to be end step "there is a 'create' audit performed by a user " \ - 'whose name contains :term' do |term| + 'whose name contains :term' do |term| item = FactoryGirl.create(:item) item.audits.first.update_attributes(user: @user) end step "there is a 'create' audit for an item " \ - 'whose inventory code contains :term' do |term| + 'whose inventory code contains :term' do |term| @audit = Audit.find_by(action: 'create', auditable_id: @item.id) expect(@audit).to be end step "there is an 'update' audit for an item whose " \ - 'inventory code contains :term' do |term| + 'inventory code contains :term' do |term| @item.update_attributes(shelf: Faker::Lorem.word) end step "there is a 'create' audit for a model " \ - 'whose name contains :term' do |term| + 'whose name contains :term' do |term| FactoryGirl.create(:model, product: term) end @@ -77,17 +73,18 @@ module AuditsSteps step 'I scroll down until I see all audits' do # rubocop:disable Lint/Loop - begin - counter = all('.panel').count - scroll_down 10000 - end until all('.panel').count == counter + + until all('.panel').count == counter + begin + counter = all('.panel').count + scroll_down 10000 + end + end # rubocop:enable Lint/Loop end step 'I see :count audits' do |count| - within '.pages' do - expect(all('.panel').count).to be == count - end + within '.pages' doexpect(all('.panel').count).to be == countend end step 'the end date is set to today' do @@ -95,8 +92,7 @@ module AuditsSteps end step 'the start date is set to one month ago' do - expect(find("input[name='start_date']").value) - .to be == I18n.l(30.days.ago.to_date) + expect(find("input[name='start_date']").value).to be == I18n.l(30.days.ago.to_date) end step 'I see the request with the new audit at the top' do @@ -118,8 +114,7 @@ module AuditsSteps end step 'I see the inventory code of the item on its audit entry' do - expect(find(".row[data-id='#{@audit.id}']")) - .to have_content @item.inventory_code + expect(find(".row[data-id='#{@audit.id}']")).to have_content @item.inventory_code end step 'there exists a new audit for a model' do @@ -128,8 +123,7 @@ module AuditsSteps end step 'I see the model name of the model on its audit entry' do - expect(find(".row[data-id='#{@audit.id}']")) - .to have_content @model.name + expect(find(".row[data-id='#{@audit.id}']")).to have_content @model.name end step 'there exists a new audit for a user' do @@ -138,8 +132,7 @@ module AuditsSteps end step 'I see the user name of the user on its audit entry' do - expect(find(".row[data-id='#{@audit.id}']")) - .to have_content @user.name + expect(find(".row[data-id='#{@audit.id}']")).to have_content @user.name end step 'there is a label method defined for every audited entity' do @@ -149,16 +142,15 @@ module AuditsSteps end step 'I see 1 audit for the item' do + end step 'I click on the label link of the item' do - within(".row[data-id='#{@audit.id}']") do - find('a').click - end + within(".row[data-id='#{@audit.id}']") { find('a').click } end step 'an individual audits page opens for the audits of this item' do - expect(current_path).to be == \ + expect(current_path).to be == admin.individual_audits_path(@item.model_name.singular, @item.id) end @@ -178,6 +170,4 @@ module AuditsSteps end end -RSpec.configure do |config| - config.include LeihsAdmin::Spec::AuditsSteps, leihs_admin_audits: true -end +RSpec.configure { |config| config.include LeihsAdmin::Spec::AuditsSteps, leihs_admin_audits: true } diff --git a/engines/leihs_admin/spec/steps/buildings_steps.rb b/engines/leihs_admin/spec/steps/buildings_steps.rb index a69f5dcde3..3b3d72b316 100644 --- a/engines/leihs_admin/spec/steps/buildings_steps.rb +++ b/engines/leihs_admin/spec/steps/buildings_steps.rb @@ -4,12 +4,8 @@ require_relative 'shared/personas_dump_steps' placeholder :whether_providing do - match('not providing') do - false - end - match('providing') do - true - end + match('not providing') { false } + match('providing') { true } end module LeihsAdmin @@ -22,17 +18,13 @@ module BuildingSteps step 'I see a list of buildings' do within '.list-of-lines' do - Building.limit(5).each do |building| - find('.row > .col-sm-3', text: building.name) - end + Building.limit(5).each { |building| find('.row > .col-sm-3', text: building.name) } end end step 'I see a list of all buildings' do within '.list-of-lines' do - Building.all.each do |building| - find(".row[data-id='#{building.id}']") - end + Building.all.each { |building| find(".row[data-id='#{building.id}']") } end end @@ -51,28 +43,24 @@ module BuildingSteps step 'the first row contains rooms count of the building' do @first_row ||= first('.list-of-lines .row') @first_building ||= Building.find(@first_row['data-id']) - expect(@first_row) - .to have_content "#{@first_building.rooms.count} #{_('rooms')}" + expect(@first_row).to have_content "#{@first_building.rooms.count} #{_('rooms')}" end step 'the first row contains items count of the building' do @first_row ||= first('.list-of-lines .row') @first_building ||= Building.find(@first_row['data-id']) - expect(@first_row) - .to have_content "#{@first_building.items.count} #{_('items')}" + expect(@first_row).to have_content "#{@first_building.items.count} #{_('items')}" end step 'the general building row contains the general label' do @general_building ||= Building.general - @general_row ||= \ - find(".list-of-lines .row[data-id='#{@general_building.id}']") + @general_row ||= find(".list-of-lines .row[data-id='#{@general_building.id}']") expect(@general_row).to have_content _('general') end step 'the general building row is highlighted' do @general_building ||= Building.general - @general_row ||= \ - find(".list-of-lines .row[data-id='#{@general_building.id}']") + @general_row ||= find(".list-of-lines .row[data-id='#{@general_building.id}']") expect(@general_row.native.attribute(:class)).to include 'text-warning' end @@ -82,28 +70,25 @@ module BuildingSteps end step 'I create a new building :whether_providing ' \ - 'all required values' do |whether_providing| + 'all required values' do |whether_providing| find('.btn', text: _('Create %s') % _('Building')).click unless whether_providing - # not providing building[name] + else @name = Faker::Address.street_address @code = Faker::Address.building_number find("input[name='building[name]']").set @name find("input[name='building[code]']").set @code end + # not providing building[name] end step 'I see the :adjective building' do |arg1 = nil| - within '.list-of-lines' do - find('.row > .col-sm-3', text: @name) - end + within '.list-of-lines' dofind('.row > .col-sm-3', text: @name)end end step 'I see the building form' do - within 'form' do - find("input[name='building[name]']") - end + within 'form' dofind("input[name='building[name]']")end end step 'I edit an existing building' do @@ -119,9 +104,10 @@ module BuildingSteps step 'there is a deletable building' do @building = Building.all.detect(&:can_destroy?) - @building ||= FactoryGirl.create(:building, - name: Faker::Address.street_address, - code: Faker::Address.building_number) + @building ||= + FactoryGirl.create( + :building, name: Faker::Address.street_address, code: Faker::Address.building_number + ) expect(@building).not_to be_nil expect(@building.can_destroy?).to be true end @@ -138,9 +124,7 @@ module BuildingSteps step "I don't see the deleted building" do within '.list-of-lines' do - expect( - has_no_selector?('.row > .col-sm-4', text: @building.name) - ).to be true + expect(has_no_selector?('.row > .col-sm-4', text: @building.name)).to be true end end @@ -158,8 +142,7 @@ module BuildingSteps end step 'its general room was deleted from the database too' do - expect(Room.find_by(building_id: @building.id, general: true)) - .not_to be + expect(Room.find_by(building_id: @building.id, general: true)).not_to be end end end diff --git a/engines/leihs_admin/spec/steps/delegation_steps.rb b/engines/leihs_admin/spec/steps/delegation_steps.rb index bcb3d245f2..488e9aca54 100644 --- a/engines/leihs_admin/spec/steps/delegation_steps.rb +++ b/engines/leihs_admin/spec/steps/delegation_steps.rb @@ -21,23 +21,18 @@ module DelegationSteps step 'the delegation has no access rights to any inventory pool' do expect( - AccessRight - .where(user_id: @delegation.id) - .where(role: [:customer, - :group_manager, - :lending_manager, - :inventory_manager]) - .exists? + AccessRight.where(user_id: @delegation.id).where( + role: [:customer, :group_manager, :lending_manager, :inventory_manager] + ) + .exists? ).to be false end step 'I click on the dropdown toggle for the delegation' do - find('.list-of-lines .row', text: @delegation.name) - .find('.dropdown-toggle') - .click + find('.list-of-lines .row', text: @delegation.name).find('.dropdown-toggle').click end - step 'the delegation doesn\'t exist anymore' do + step "the delegation doesn't exist anymore" do expect(User.find_by_id(@delegation.id)).not_to be end diff --git a/engines/leihs_admin/spec/steps/fields_steps.rb b/engines/leihs_admin/spec/steps/fields_steps.rb index 06ade45a54..56317a8173 100644 --- a/engines/leihs_admin/spec/steps/fields_steps.rb +++ b/engines/leihs_admin/spec/steps/fields_steps.rb @@ -18,37 +18,30 @@ module FieldsSteps end step 'I see all fields' do - Field.unscoped.all.map(&:id).each do |field_id| - expect(page).to have_content field_id - end + Field.unscoped.all.map(&:id).each { |field_id| expect(page).to have_content field_id } end step 'the data of all fields is readonly' do - within 'form' do - expect(current_scope).not_to have_selector "input[type='text']" - end + within 'form' doexpect(current_scope).not_to have_selector "input[type='text']"end end step 'the activate checkbox of a non-required field is enabled' do - field = Field.unscoped.all.detect { |f| not f.data['required'] } - expect(find("input[name='fields[#{field.id}][active]']")) - .not_to be_disabled + field = Field.unscoped.all.detect { |f| nf.data['required'] } + expect(find("input[name='fields[#{field.id}][active]']")).not_to be_disabled end step 'the activate checkbox of a required field is disabled' do field = Field.unscoped.all.detect { |f| f.data['required'] } - expect(find("input[name='fields[#{field.id}][active]']")) - .to be_disabled + expect(find("input[name='fields[#{field.id}][active]']")).to be_disabled end step 'I store the information about the active state of all fields' do - @fields = \ - Field.unscoped.all.map { |f| f.attributes.slice('id', 'active') } + @fields = Field.unscoped.all.map { |f| f.attributes.slice('id', 'active') } end step 'there is at least one inactive field' do unless Field.unscoped.find_by_active(false) - field = Field.unscoped.all.detect { |f| not f.data['required'] } + field = Field.unscoped.all.detect { |f| nf.data['required'] } field.update_attributes!(active: false) end expect(Field.unscoped.find_by_active(false)).to be @@ -59,8 +52,8 @@ module FieldsSteps expect(@active_field.active).to be false ########################################################################### # these elements sometimes cover stuff we want to click - execute_script %($('header').remove()) - execute_script %($('footer').remove()) + execute_script "$('header').remove()" + execute_script "$('footer').remove()" sleep 1 ########################################################################### uncheck("fields[#{@active_field.id}][active]") @@ -71,8 +64,8 @@ module FieldsSteps expect(@inactive_field).to be ########################################################################### # these elements sometimes cover stuff we want to click - execute_script %($('header').remove()) - execute_script %($('footer').remove()) + execute_script "$('header').remove()" + execute_script "$('footer').remove()" sleep 1 ########################################################################### check("fields[#{@inactive_field.id}][active]") @@ -83,33 +76,28 @@ module FieldsSteps end step 'I see a success message that ' \ - 'the fields have been updated successfully' do + 'the fields have been updated successfully' do find('.alert-success', text: _('Fields have been updated successfully.')) end step 'the formerly active field is now inactive' do - expect(find("input[name='fields[#{@active_field.id}][active]']")) - .not_to be_checked + expect(find("input[name='fields[#{@active_field.id}][active]']")).not_to be_checked end step 'the formerly inactive field is now active' do - expect(find("input[name='fields[#{@inactive_field.id}][active]']")) - .to be_checked + expect(find("input[name='fields[#{@inactive_field.id}][active]']")).to be_checked end step 'all other fields remained unchanged' do - @fields - .reject { |f| [@inactive_field.id, @active_field.id].include? f['id'] } + @fields.reject { |f| [@inactive_field.id, @active_field.id].include? f['id'] } .each do |field| - expect(find("input[name='fields[#{field['id']}][active]']").checked?) - .to be field['active'] + expect(find("input[name='fields[#{field['id']}][active]']").checked?).to be field[ + 'active' + ] end end end end end -RSpec.configure do |config| - config.include(LeihsAdmin::Spec::FieldsSteps, - leihs_admin_fields: true) -end +RSpec.configure { |config| config.include(LeihsAdmin::Spec::FieldsSteps, leihs_admin_fields: true) } diff --git a/engines/leihs_admin/spec/steps/inventory_csv_steps.rb b/engines/leihs_admin/spec/steps/inventory_csv_steps.rb index 54637183e4..8e040ad996 100644 --- a/engines/leihs_admin/spec/steps/inventory_csv_steps.rb +++ b/engines/leihs_admin/spec/steps/inventory_csv_steps.rb @@ -19,6 +19,5 @@ module InventoryCsvSteps end RSpec.configure do |config| - config.include(LeihsAdmin::Spec::InventoryCsvSteps, - leihs_admin_inventory_csv: true) + config.include(LeihsAdmin::Spec::InventoryCsvSteps, leihs_admin_inventory_csv: true) end diff --git a/engines/leihs_admin/spec/steps/inventory_pools_steps.rb b/engines/leihs_admin/spec/steps/inventory_pools_steps.rb index e2379c8b17..d65b07d478 100644 --- a/engines/leihs_admin/spec/steps/inventory_pools_steps.rb +++ b/engines/leihs_admin/spec/steps/inventory_pools_steps.rb @@ -5,9 +5,7 @@ require_relative 'shared/personas_dump_steps' placeholder :input_label do - match(/(.*)/) do |value| - value - end + match(/(.*)/) { |value| value } end module LeihsAdmin @@ -36,7 +34,7 @@ module InventoryPoolsSteps end step 'I create a new inventory pool in the ' \ - 'admin area\'s inventory pool tab' do + "admin area's inventory pool tab" do expect(current_path).to eq admin.inventory_pools_path click_link _('Create %s') % _('Inventory pool') end @@ -48,17 +46,16 @@ module InventoryPoolsSteps end step 'the inventory pool is saved' do - @inventory_pool = \ - InventoryPool - .find_by_name_and_shortname_and_email('test', 'test', 'test@test.ch') + @inventory_pool = + InventoryPool.find_by_name_and_shortname_and_email('test', 'test', 'test@test.ch') expect(@inventory_pool).to be end step 'I see the list of all active inventory pools sorted alphabetically' do expect(has_content?(_('List of Inventory Pools'))).to be true within '.list-of-lines' do - expect(InventoryPool.where(is_active: true).sort.map(&:name)) - .to be == all('.row > .col-sm-6').map(&:text) + expect(InventoryPool.where(is_active: true).sort.map(&:name)).to be == + all('.row > .col-sm-6').map(&:text) end end @@ -67,7 +64,7 @@ module InventoryPoolsSteps find '.list-of-lines' end - step 'I don\'t enter :must_field' do |must_field| + step "I don't enter :must_field" do |must_field| step 'I enter name, shortname and email address' within('.form-group .col-sm-6 strong', match: :first, text: must_field) do find(:xpath, './../..').find('input').set '' @@ -79,26 +76,28 @@ module InventoryPoolsSteps expect(has_no_selector?('.success')).to be true end - step 'I edit in the admin area\'s inventory pool tab ' \ - 'an existing inventory pool' do + step "I edit in the admin area's inventory pool tab " \ + 'an existing inventory pool' do @current_inventory_pool = InventoryPool.first expect(has_content?(_('List of Inventory Pools'))).to be true - find('.row', match: :prefer_exact, text: @current_inventory_pool.name) - .click_link _('Edit') + find('.row', match: :prefer_exact, text: @current_inventory_pool.name).click_link _('Edit') end step 'I change name, shortname and email address' do - all('.row .col-sm-6 strong', text: _('Name')) - .first.find(:xpath, './../..').find('input').set 'test' - all('.row .col-sm-6 strong', text: _('Short Name')) - .first.find(:xpath, './../..').find('input').set 'test' - all('.row .col-sm-6 strong', text: _('E-Mail')) - .first.find(:xpath, './../..').find('input').set 'test@test.ch' + all('.row .col-sm-6 strong', text: _('Name')).first.find(:xpath, './../..').find( + 'input' + ).set 'test' + all('.row .col-sm-6 strong', text: _('Short Name')).first.find(:xpath, './../..').find( + 'input' + ).set 'test' + all('.row .col-sm-6 strong', text: _('E-Mail')).first.find(:xpath, './../..').find( + 'input' + ).set 'test@test.ch' end step 'I delete an existing inventory pool ' \ - 'in the admin area\'s inventory pool tab' do - @current_inventory_pool = \ + "in the admin area's inventory pool tab" do + @current_inventory_pool = InventoryPool.find(&:can_destroy?) || FactoryGirl.create(:inventory_pool) visit admin.inventory_pools_path within('.row', text: @current_inventory_pool.name) do @@ -113,8 +112,7 @@ module InventoryPoolsSteps end step 'the inventory pool is removed from the list' do - find('#flash .success', - text: _('%s successfully deleted') % _('Inventory Pool')) + find('#flash .success', text: _('%s successfully deleted') % _('Inventory Pool')) expect(has_no_content?(@current_inventory_pool.name)).to be true end @@ -123,17 +121,14 @@ module InventoryPoolsSteps end step 'the list of inventory pools is sorted alphabetically' do - names = \ - all('div.dropdown-holder:nth-child(1) .dropdown .dropdown-item') - .map(&:text) + names = all('div.dropdown-holder:nth-child(1) .dropdown .dropdown-item').map(&:text) expect(names.map(&:downcase).sort).to eq names.map(&:downcase) end step 'I see all managed inventory pools' do if @current_user.inventory_pools.managed.exists? within '#ip-dropdown-menu' do - @current_user.inventory_pools.managed.each \ - { |ip| has_content? ip.name } + @current_user.inventory_pools.managed.each { |ip| has_content? ip.name } end end end @@ -142,11 +137,9 @@ module InventoryPoolsSteps find('nav.navbar .navbar-right > .dropdown', match: :first).click end - step 'I don\'t fill in :input_label' do |input_label| + step "I don't fill in :input_label" do |input_label| expect( - find('.form-group', text: input_label, match: :prefer_exact) - .find('input') - .value + find('.form-group', text: input_label, match: :prefer_exact).find('input').value ).to be_blank end @@ -154,56 +147,47 @@ module InventoryPoolsSteps InventoryPool.limit(rand(2..4)).each do |inventory_pool| inventory_pool.update_attributes automatic_access: true end - inventory_pool = \ - @current_user - .inventory_pools - .managed - .where.not(automatic_access: true) - .first - if inventory_pool - inventory_pool.update_attributes automatic_access: true - end - @inventory_pools_with_automatic_access = \ - InventoryPool.where(automatic_access: true) + inventory_pool = + @current_user.inventory_pools.managed.where.not(automatic_access: true).first + inventory_pool.update_attributes automatic_access: true if inventory_pool + @inventory_pools_with_automatic_access = InventoryPool.where(automatic_access: true) expect(@inventory_pools_with_automatic_access.count).to be > 1 end step 'I have created a user with ' \ - 'login :login and password :password' do |login, password| + 'login :login and password :password' do |login, password| visit admin.new_user_path - fill_in_user_information(firstname: 'test', - lastname: 'test', - email: 'test@test.ch', - login: login, - password: password, - password_confirmation: password) + fill_in_user_information( + firstname: 'test', + lastname: 'test', + email: 'test@test.ch', + login: login, + password: password, + password_confirmation: password + ) expect(has_content?(_('List of Users'))).to be true @user = User.find_by_login(login) expect(DatabaseAuthentication.find_by_user_id(@user.id)).not_to be_nil end - step 'the newly created user has \'customer\'-level access to all ' \ - 'inventory pools that grant automatic access' do - expect(@user.access_rights.count) - .to eq @inventory_pools_with_automatic_access.count - expect(@user.access_rights.pluck(:inventory_pool_id)) - .to eq @inventory_pools_with_automatic_access.pluck(:id) + step "the newly created user has 'customer'-level access to all " \ + 'inventory pools that grant automatic access' do + expect(@user.access_rights.count).to eq @inventory_pools_with_automatic_access.count + expect( + @user.access_rights.pluck(:inventory_pool_id) + ).to eq @inventory_pools_with_automatic_access.pluck(:id) expect(@user.access_rights.all? { |ar| ar.role == :customer }).to be true end step "each line displays the inventory pool's name" do within '.list-of-lines' do - InventoryPool.all.each do |ip| - find '.row', match: :prefer_exact, text: ip.name - end + InventoryPool.all.each { |ip| find '.row', match: :prefer_exact, text: ip.name } end end step "each line displays the inventory pool's short name" do within '.list-of-lines' do - InventoryPool.all.each do |ip| - find '.row', match: :prefer_exact, text: ip.shortname - end + InventoryPool.all.each { |ip| find '.row', match: :prefer_exact, text: ip.shortname } end end @@ -221,59 +205,52 @@ module InventoryPoolsSteps end step 'the inventory pool has ' \ - "but doesn't own an unretired item" do - FactoryGirl.create(:item, - inventory_pool: @inventory_pool, - owner: FactoryGirl.create(:inventory_pool)) + "but doesn't own an unretired item" do + FactoryGirl.create( + :item, inventory_pool: @inventory_pool, owner: FactoryGirl.create(:inventory_pool) + ) end step 'the inventory pool owns ' \ - "but doesn't have an unretired item" do - FactoryGirl.create(:item, - inventory_pool: FactoryGirl.create(:inventory_pool), - owner: @inventory_pool) + "but doesn't have an unretired item" do + FactoryGirl.create( + :item, inventory_pool: FactoryGirl.create(:inventory_pool), owner: @inventory_pool + ) end step 'there exists an active inventory pool' do - @active_inventory_pool = FactoryGirl.create(:inventory_pool, - is_active: true) + @active_inventory_pool = FactoryGirl.create(:inventory_pool, is_active: true) end step 'there exists an inactive inventory pool' do - @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, - is_active: false) + @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, is_active: false) end step 'there exists an inventory pool with :order_type' do |order_type| @inventory_pool = FactoryGirl.create(:inventory_pool) case order_type when 'unsubmitted order' - FactoryGirl.create(:reservation, - status: :unsubmitted, - inventory_pool: @inventory_pool) + FactoryGirl.create(:reservation, status: :unsubmitted, inventory_pool: @inventory_pool) when 'submitted order' user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) - order = FactoryGirl.create(:order, - user: user, - inventory_pool: @inventory_pool, - state: :submitted) - FactoryGirl.create(:reservation, - status: :submitted, - order: order, - inventory_pool: @inventory_pool) + order = + FactoryGirl.create( + :order, user: user, inventory_pool: @inventory_pool, state: :submitted + ) + FactoryGirl.create( + :reservation, status: :submitted, order: order, inventory_pool: @inventory_pool + ) when 'approved order' user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) - order = FactoryGirl.create(:order, - user: user, - inventory_pool: @inventory_pool, - state: :approved) - FactoryGirl.create(:reservation, - status: :approved, - order: order, - inventory_pool: @inventory_pool) + order = + FactoryGirl.create( + :order, user: user, inventory_pool: @inventory_pool, state: :approved + ) + FactoryGirl.create( + :reservation, status: :approved, order: order, inventory_pool: @inventory_pool + ) when 'signed contract' - FactoryGirl.create(:open_contract, - inventory_pool: @inventory_pool) + FactoryGirl.create(:open_contract, inventory_pool: @inventory_pool) end end @@ -286,8 +263,7 @@ module InventoryPoolsSteps end step 'I see an error message regarding the deactivation of inventory pool' do - expect(find('#flash .error').text) - .to match /Inventory pool can't be deactivated/ + expect(find('#flash .error').text).to match /Inventory pool can't be deactivated/ end step 'the inventory pool remains active' do @@ -303,13 +279,12 @@ module InventoryPoolsSteps end step 'there exists an inactive inventory pool ' \ - 'I have access to as :role' do |role| - @inactive_inventory_pool = \ - FactoryGirl.create(:inventory_pool, is_active: false) - FactoryGirl.create(:access_right, - user: @current_user, - inventory_pool: @inactive_inventory_pool, - role: role.sub(' ', '_')) + 'I have access to as :role' do |role| + @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, is_active: false) + FactoryGirl.create( + :access_right, + user: @current_user, inventory_pool: @inactive_inventory_pool, role: role.sub(' ', '_') + ) end step 'I click on the sections dropdown toggle' do @@ -329,8 +304,7 @@ module InventoryPoolsSteps step 'the inventory pool does not have any unretired items' do @inventory_pool.items.each do |item| - item.update_attributes(retired: Date.today, - retired_reason: Faker::Lorem.sentence) + item.update_attributes(retired: Date.today, retired_reason: Faker::Lorem.sentence) end end @@ -360,10 +334,12 @@ module InventoryPoolsSteps end step 'the user had access to the pool as inventory manager' do - FactoryGirl.create(:access_right, - inventory_pool: @active_inventory_pool, - deleted_at: Date.yesterday, - role: :inventory_manager) + FactoryGirl.create( + :access_right, + inventory_pool: @active_inventory_pool, + deleted_at: Date.yesterday, + role: :inventory_manager + ) end step 'I open the edit page for the active inventory pool' do @@ -391,18 +367,18 @@ module InventoryPoolsSteps rejected: :order } template_types.each do |name, type| - mt = MailTemplate.find_by!(name: name, - type: type, - is_template_template: true) + mt = MailTemplate.find_by!(name: name, type: type, is_template_template: true) Language.all.each do |language| expect( - MailTemplate.find_by(inventory_pool_id: @inventory_pool.id, - is_template_template: false, - language_id: language.id, - name: name, - type: type, - format: 'text', - body: mt.body) + MailTemplate.find_by( + inventory_pool_id: @inventory_pool.id, + is_template_template: false, + language_id: language.id, + name: name, + type: type, + format: 'text', + body: mt.body + ) ).to be end end @@ -412,19 +388,31 @@ module InventoryPoolsSteps def fill_in_user_information(attrs) selector = @current_inventory_pool ? '.row.emboss' : '.form-group' - find(selector, match: :prefer_exact, text: _('Last name')) - .find('input').set attrs[:firstname] if attrs[:lastname] - find(selector, match: :prefer_exact, text: _('First name')) - .find('input').set attrs[:firstname] if attrs[:firstname] - find(selector, match: :prefer_exact, text: _('E-Mail')) - .find('input').set attrs[:email] if attrs[:email] - find(selector, match: :prefer_exact, text: _('Login')) - .find('input').set attrs[:login] if attrs[:login] - find(selector, match: :prefer_exact, text: _('Password')) - .find('input').set attrs[:password] if attrs[:password] + if attrs[:lastname] + find(selector, match: :prefer_exact, text: _('Last name')).find('input').set attrs[ + :firstname + ] + end + if attrs[:firstname] + find(selector, match: :prefer_exact, text: _('First name')).find('input').set attrs[ + :firstname + ] + end + if attrs[:email] + find(selector, match: :prefer_exact, text: _('E-Mail')).find('input').set attrs[:email] + end + if attrs[:login] + find(selector, match: :prefer_exact, text: _('Login')).find('input').set attrs[:login] + end + if attrs[:password] + find(selector, match: :prefer_exact, text: _('Password')).find('input').set attrs[ + :password + ] + end if attrs[:password_confirmation] - find(selector, match: :prefer_exact, text: _('Password Confirmation')) - .find('input').set attrs[:password_confirmation] + find(selector, match: :prefer_exact, text: _('Password Confirmation')).find( + 'input' + ).set attrs[:password_confirmation] end click_button _('Save') end @@ -433,6 +421,5 @@ def fill_in_user_information(attrs) end RSpec.configure do |config| - config.include(LeihsAdmin::Spec::InventoryPoolsSteps, - leihs_admin_inventory_pools: true) + config.include(LeihsAdmin::Spec::InventoryPoolsSteps, leihs_admin_inventory_pools: true) end diff --git a/engines/leihs_admin/spec/steps/languages_steps.rb b/engines/leihs_admin/spec/steps/languages_steps.rb index a7707c720e..fc4ebca512 100644 --- a/engines/leihs_admin/spec/steps/languages_steps.rb +++ b/engines/leihs_admin/spec/steps/languages_steps.rb @@ -12,12 +12,11 @@ module LanguagesSteps include ::Spec::LoginSteps step 'I see a table of configured languages as follows' do |table| - displayed_table = find('.container table.table') - .all('tr').map { |tr| tr.all('th, td').map(&:text) } + displayed_table = + find('.container table.table').all('tr').map { |tr| tr.all('th, td').map(&:text) } expect(displayed_table).to eq table.raw end - end end end diff --git a/engines/leihs_admin/spec/steps/maintenance_mode_steps.rb b/engines/leihs_admin/spec/steps/maintenance_mode_steps.rb index 02dc3cc5e1..8e412e8b93 100644 --- a/engines/leihs_admin/spec/steps/maintenance_mode_steps.rb +++ b/engines/leihs_admin/spec/steps/maintenance_mode_steps.rb @@ -3,9 +3,7 @@ require_relative 'shared/personas_dump_steps' placeholder :section_name do - match /(manage section|borrow section)/ do |section| - section - end + match /(manage section|borrow section)/ do |section| sectionend end module LeihsAdmin @@ -24,15 +22,15 @@ module MaintenanceModeSteps selector = @current_inventory_pool ? '.row.emboss' : '.form-group' case function_name when 'Disable manage section' - input_field = \ - find(selector, text: :disable_manage_section, match: :first) - .find("input[name='setting[#{:disable_manage_section}]']", - match: :first) + input_field = + find(selector, text: :disable_manage_section, match: :first).find( + "input[name='setting[#{:disable_manage_section}]']", match: :first + ) when 'Disable borrow section' - input_field = \ - find(selector, text: :disable_borrow_section, match: :first) - .find("input[name='setting[#{:disable_borrow_section}]']", - match: :first) + input_field = + find(selector, text: :disable_borrow_section, match: :first).find( + "input[name='setting[#{:disable_borrow_section}]']", match: :first + ) else raise end @@ -53,12 +51,11 @@ module MaintenanceModeSteps step 'I log out' case section_name when 'manage section' - step %(I am Mike) - expect(current_path) - .to eq manage_maintenance_path(@current_inventory_pool) + step 'I am Mike' + expect(current_path).to eq manage_maintenance_path(@current_inventory_pool) @section = _('Manage section') when 'borrow section' - step %(I am Normin) + step 'I am Normin' expect(current_path).to eq borrow_maintenance_path @section = _('Borrow section') else @@ -67,8 +64,7 @@ module MaintenanceModeSteps end step 'users see the note that was defined' do - expect(has_selector?('h1', text: _('%s not available') % @section)) - .to be true + expect(has_selector?('h1', text: _('%s not available') % @section)).to be true expect(has_content?(@disable_message)).to be true end @@ -77,15 +73,13 @@ module MaintenanceModeSteps selector = @current_inventory_pool ? '.row.emboss' : '.form-group' case section_name when 'manage section' - find(selector, text: :disable_manage_section_message, match: :first) - .find("textarea[name='setting[#{:disable_manage_section_message}]']", - match: :first) - .set @disable_message + find(selector, text: :disable_manage_section_message, match: :first).find( + "textarea[name='setting[#{:disable_manage_section_message}]']", match: :first + ).set @disable_message when 'borrow section' - find(selector, text: :disable_borrow_section_message, match: :first) - .find("textarea[name='setting[#{:disable_borrow_section_message}]']", - match: :first) - .set @disable_message + find(selector, text: :disable_borrow_section_message, match: :first).find( + "textarea[name='setting[#{:disable_borrow_section_message}]']", match: :first + ).set @disable_message else raise end @@ -95,12 +89,10 @@ module MaintenanceModeSteps case section_name when 'manage section' expect(Setting.first.disable_manage_section).to eq @disable - expect(Setting.first.disable_manage_section_message.to_s) - .to eq @disable_message + expect(Setting.first.disable_manage_section_message.to_s).to eq @disable_message when 'borrow section' expect(Setting.first.disable_borrow_section).to eq @disable - expect(Setting.first.disable_borrow_section_message.to_s) - .to eq @disable_message + expect(Setting.first.disable_borrow_section_message.to_s).to eq @disable_message else raise end @@ -111,13 +103,11 @@ module MaintenanceModeSteps case section_name when 'manage section' - Setting.first.update_attributes \ - disable_manage_section: true, - disable_manage_section_message: @disable_message + Setting.first.update_attributes disable_manage_section: true, + disable_manage_section_message: @disable_message when 'borrow section' - Setting.first.update_attributes \ - disable_borrow_section: true, - disable_borrow_section_message: @disable_message + Setting.first.update_attributes disable_borrow_section: true, + disable_borrow_section_message: @disable_message else raise end @@ -128,15 +118,15 @@ module MaintenanceModeSteps selector = @current_inventory_pool ? '.row.emboss' : '.form-group' case function_name when 'disable manage section' - input_field = \ - find(selector, text: :disable_manage_section, match: :first) - .find("input[name='setting[#{:disable_manage_section}]']", - match: :first) + input_field = + find(selector, text: :disable_manage_section, match: :first).find( + "input[name='setting[#{:disable_manage_section}]']", match: :first + ) when 'disable borrow section' - input_field = \ - find(selector, text: :disable_borrow_section, match: :first) - .find("input[name='setting[#{:disable_borrow_section}]']", - match: :first) + input_field = + find(selector, text: :disable_borrow_section, match: :first).find( + "input[name='setting[#{:disable_borrow_section}]']", match: :first + ) else raise end @@ -150,10 +140,10 @@ module MaintenanceModeSteps step 'I log out' case section_name when 'manage section' - step %(I am Mike) + step 'I am Mike' expect(current_path).to eq manage_inventory_path(@current_inventory_pool) when 'borrow section' - step %(I am Normin) + step 'I am Normin' expect(current_path).to eq borrow_root_path else raise @@ -161,14 +151,12 @@ module MaintenanceModeSteps end step 'the note entered for the ":section_name" ' \ - 'is still saved' do |section_name| + 'is still saved' do |section_name| case section_name when 'manage section' - expect(Setting.first.reload.disable_manage_section_message) - .to eq @disable_message + expect(Setting.first.reload.disable_manage_section_message).to eq @disable_message when 'borrow section' - expect(Setting.first.reload.disable_borrow_section_message) - .to eq @disable_message + expect(Setting.first.reload.disable_borrow_section_message).to eq @disable_message else raise end @@ -184,8 +172,7 @@ module MaintenanceModeSteps toggle = first('.topbar .dropdown', text: @current_user.try(:lastname)) if toggle toggle.click - sign_out_button = first(".topbar form[action='/sign-out'] button", - visible: :all) + sign_out_button = first(".topbar form[action='/sign-out'] button", visible: :all) sign_out_button.click else visit root_path @@ -196,6 +183,5 @@ module MaintenanceModeSteps end RSpec.configure do |config| - config.include(LeihsAdmin::Spec::MaintenanceModeSteps, - leihs_admin_maintenance_mode: true) + config.include(LeihsAdmin::Spec::MaintenanceModeSteps, leihs_admin_maintenance_mode: true) end diff --git a/engines/leihs_admin/spec/steps/rooms_steps.rb b/engines/leihs_admin/spec/steps/rooms_steps.rb index ece37b94c1..2dba00278c 100644 --- a/engines/leihs_admin/spec/steps/rooms_steps.rb +++ b/engines/leihs_admin/spec/steps/rooms_steps.rb @@ -13,8 +13,7 @@ module RoomsSteps include ::Spec::FactorySteps include ::Spec::LoginSteps - step 'there exists a room :room for building :building' \ - do |room_name, building_name| + step 'there exists a room :room for building :building' do |room_name, building_name| building = Building.find_by_name(building_name) building ||= FactoryGirl.create(:building, name: building_name) @room = FactoryGirl.create(:room, name: room_name, building: building) @@ -30,10 +29,9 @@ module RoomsSteps step 'I see the list of rooms sorted in the following manner:' do |table| table.hashes.each_with_index do |h, i| - expect(all('.list-of-lines .row .col-sm-3:nth-child(1)')[i].text) - .to be == h['room_name'] - expect(all('.list-of-lines .row .col-sm-3:nth-child(2)')[i].text) - .to be == h['building_name'] + expect(all('.list-of-lines .row .col-sm-3:nth-child(1)')[i].text).to be == h['room_name'] + expect(all('.list-of-lines .row .col-sm-3:nth-child(2)')[i].text).to be == + h['building_name'] end end @@ -43,8 +41,7 @@ module RoomsSteps building_name = row.find('div:nth-child(2)', match: :first).text building = Building.find_by_name(building_name) room = Room.find_by(name: room_name, building_id: building.id) - expect(row.find('div:nth-child(4)', match: :first).text) - .to match /^#{room.items.count}/ + expect(row.find('div:nth-child(4)', match: :first).text).to match /^#{room.items.count}/ end end @@ -65,14 +62,11 @@ module RoomsSteps end step 'the edit button' do - all('.list-of-lines .row').each do |row| - row.find('[href]', text: _('Edit')) - end + all('.list-of-lines .row').each { |row| row.find('[href]', text: _('Edit')) } end step 'I click on the edit button for the row of the room' do - button = \ - find(".list-of-lines .row [href='#{admin.edit_room_path(@room)}']") + button = find(".list-of-lines .row [href='#{admin.edit_room_path(@room)}']") button.click end @@ -107,19 +101,16 @@ module RoomsSteps end step 'a second room with name :room and ' \ - 'building :building was not created' do |room, building| + 'building :building was not created' do |room, building| expect( - Room.includes(:building) - .where(name: room, buildings: { name: building }) - .count + Room.includes(:building).where(name: room, buildings: { name: building }).count ).to be == 1 end step 'the room with name :room and ' \ - 'building :building was not created' do |room, building| + 'building :building was not created' do |room, building| expect( - Room.includes(:building) - .find_by(name: room, buildings: { name: building }) + Room.includes(:building).find_by(name: room, buildings: { name: building }) ).not_to be end @@ -128,9 +119,7 @@ module RoomsSteps end step 'the room was saved successfully' do - Room.find_by(name: @new_name, - description: @new_description, - building: @building) + Room.find_by(name: @new_name, description: @new_description, building: @building) end step 'I click on create room button' do @@ -143,14 +132,12 @@ module RoomsSteps end step "I don't see the delete button on the row for the room" do - row = \ - find('.list-of-lines .row', text: "#{@room.name} #{@room.building.name}") + row = find('.list-of-lines .row', text: "#{@room.name} #{@room.building.name}") expect(row).not_to have_content _('Delete') end step 'I click on the delete button for the room' do - row = \ - find('.list-of-lines .row', text: "#{@room.name} #{@room.building.name}") + row = find('.list-of-lines .row', text: "#{@room.name} #{@room.building.name}") row.find("[data-toggle='dropdown']").click row.find("a[data-method='delete']").click end @@ -161,9 +148,7 @@ module RoomsSteps step 'I click on the edit button for the row of the general room' do @room ||= Room.general.first - within(".list-of-lines .row[data-id='#{@room.id}']") do - click_on _('Edit') - end + within(".list-of-lines .row[data-id='#{@room.id}']") { click_on _('Edit') } end step 'I search for the name of a general room' do @@ -187,9 +172,7 @@ module RoomsSteps step 'there are no items for the general room' do room = FactoryGirl.create(:room) - Item.where(room_id: @room.id).each do |item| - item.update_column(:room_id, room.id) - end + Item.where(room_id: @room.id).each { |item| item.update_column(:room_id, room.id) } end step 'I scrool down until I see the line for the general room' do @@ -203,6 +186,4 @@ module RoomsSteps end end -RSpec.configure do |config| - config.include LeihsAdmin::Spec::RoomsSteps, leihs_admin_rooms: true -end +RSpec.configure { |config| config.include LeihsAdmin::Spec::RoomsSteps, leihs_admin_rooms: true } diff --git a/engines/leihs_admin/spec/steps/settings_steps.rb b/engines/leihs_admin/spec/steps/settings_steps.rb index 905c793730..08c72c170d 100644 --- a/engines/leihs_admin/spec/steps/settings_steps.rb +++ b/engines/leihs_admin/spec/steps/settings_steps.rb @@ -11,15 +11,13 @@ module SettingsSteps step 'I save the settings' do # NOTE: fixed navbar scrolling hack: - page.execute_script %[ $(".navbar").remove() ] + page.execute_script ' $(".navbar").remove() ' find("button.btn.btn-success[type='submit']").click end step 'the settings are persisted' do check_flash_message(:notice, _('Successfully set.')) - @new_settings.each_pair do |k, v| - expect(Setting.first.send(k).presence).to eq v.presence - end + @new_settings.each_pair { |k, v| expect(Setting.first.send(k).presence).to eq v.presence } end step 'I go to the settings page' do @@ -34,8 +32,7 @@ module SettingsSteps fill_in form_field, with: text end - step 'the logo in the footer (in :text) :boolish link:optional_text' \ - do |section, has_link, optional_text| + step 'the logo in the footer (in :text) :boolish link:optional_text' do |section, has_link, optional_text| href = optional_text.strip.delete('"') case section.to_sym when :admin @@ -76,19 +73,20 @@ def check_flash_message(type, text) @new_settings = {} within("form#edit_setting[action='/admin/settings']") do table.raw.flatten.each do |k| + # TODO: @new_settings[k] + begin case k - when \ - 'email_signature', - 'external_base_url', - 'ldap_config', - 'mail_delivery_method', - 'smtp_address', - 'smtp_domain', - 'smtp_openssl_verify_mode', - 'smtp_password', - 'smtp_username', - 'user_image_url' + when 'email_signature', + 'external_base_url', + 'ldap_config', + 'mail_delivery_method', + 'smtp_address', + 'smtp_domain', + 'smtp_openssl_verify_mode', + 'smtp_password', + 'smtp_username', + 'user_image_url' field = find("input[name='setting[#{k}]']") expect(Setting.first.send(k).to_s).to eq field.value @new_settings[k] = new_value = Faker::Lorem.word @@ -102,19 +100,15 @@ def check_flash_message(type, text) expect(Setting.first.send(k).to_s).to eq field.value @new_settings[k] = new_value = Faker::Internet.email field.set new_value - when \ - 'contract_lending_party_string', - 'contract_terms', - 'custom_head_tag' + when 'contract_lending_party_string', 'contract_terms', 'custom_head_tag' field = find("textarea[name='setting[#{k}]']") expect(Setting.first.send(k).to_s).to eq field.value @new_settings[k] = new_value = Faker::Lorem.paragraph field.set new_value - when 'deliver_received_order_notifications', \ - 'smtp_enable_starttls_auto' + when 'deliver_received_order_notifications', 'smtp_enable_starttls_auto' field = find("input[name='setting[#{k}]']") expect(Setting.first.send(k)).to eq field.checked? - # TODO: @new_settings[k] + field.click when 'smtp_port' field = find("input[name='setting[#{k}]']") @@ -130,7 +124,7 @@ def check_flash_message(type, text) raise format('%s not found', k) end rescue Selenium::WebDriver::Error::UnknownError - page.execute_script %[ $(".navbar").remove() ] + page.execute_script ' $(".navbar").remove() ' retry end end @@ -143,11 +137,7 @@ def check_flash_message(type, text) step 'the following settings are disabled:' do |table| within("form#edit_setting[action='/admin/settings']") do table.raw.flatten.each do |k| - f = find( - %w[input textarea select] - .map { |s| "#{s}[name='setting[#{k}]']" } - .join(',') - ) + f = find(%w[input textarea select].map { |s| "#{s}[name='setting[#{k}]']" }.join(',')) expect(f).to be_disabled end end diff --git a/engines/leihs_admin/spec/steps/shared/common_steps.rb b/engines/leihs_admin/spec/steps/shared/common_steps.rb index 8f9d385243..627a1856d6 100644 --- a/engines/leihs_admin/spec/steps/shared/common_steps.rb +++ b/engines/leihs_admin/spec/steps/shared/common_steps.rb @@ -43,15 +43,11 @@ module CommonSteps end step 'I click on :label inside the dropdown menu' do |label| - within '.dropdown-menu' do - click_on _(label) - end + within '.dropdown-menu' doclick_on _(label)end end step 'I see :label option in the dropdown menu' do |label| - within '.dropdown-menu' do - expect(page).to have_content _(label) - end + within '.dropdown-menu' doexpect(page).to have_content _(label)end end def scroll_to_top diff --git a/engines/leihs_admin/spec/steps/shared/personas_dump_steps.rb b/engines/leihs_admin/spec/steps/shared/personas_dump_steps.rb index 575c8ab712..b55b2617c4 100644 --- a/engines/leihs_admin/spec/steps/shared/personas_dump_steps.rb +++ b/engines/leihs_admin/spec/steps/shared/personas_dump_steps.rb @@ -4,9 +4,7 @@ module LeihsAdmin module Spec module PersonasDumpSteps - step 'personas dump is loaded' do - ::Dataset.restore_dump - end + step 'personas dump is loaded' do::Dataset.restore_dumpend end end end diff --git a/engines/leihs_admin/spec/steps/statistics_steps.rb b/engines/leihs_admin/spec/steps/statistics_steps.rb index acd254174e..9126abd9c0 100644 --- a/engines/leihs_admin/spec/steps/statistics_steps.rb +++ b/engines/leihs_admin/spec/steps/statistics_steps.rb @@ -14,24 +14,22 @@ module StatisticsSteps end step 'I select the statistics subsection ' \ - ':subsection_title' do |subsection_title| + ':subsection_title' do |subsection_title| click_link(subsection_title) end step 'I see by default the last ' \ - ':number_of_days days\' statistics' do |number_of_days| + ":number_of_days days' statistics" do |number_of_days| from_date = Date.parse(all('input.datepicker').first.value) to_date = Date.parse(all('input.datepicker')[1].value) expect((to_date - from_date).days).to eq(Integer(number_of_days).days) end step 'I set the time frame to ' \ - ':from_day/:from_month - :to_day/:to_month ' \ - 'of the current year' do |from_day, from_month, to_day, to_month| - start_date = \ - Date.parse("#{from_day}/#{from_month}/#{Date.today.strftime('%Y')}") - end_date = \ - Date.parse("#{to_day}/#{to_month}/#{Date.today.strftime('%Y')}") + ':from_day/:from_month - :to_day/:to_month ' \ + 'of the current year' do |from_day, from_month, to_day, to_month| + start_date = Date.parse("#{from_day}/#{from_month}/#{Date.today.strftime('%Y')}") + end_date = Date.parse("#{to_day}/#{to_month}/#{Date.today.strftime('%Y')}") all('input.datepicker').first.set start_date all('input.datepicker')[1].set end_date end @@ -40,7 +38,7 @@ module StatisticsSteps @date1 = 1.month.ago.to_formatted_s(:db) @date2 = Date.today.to_formatted_s(:db) sql = <<-SQL - SELECT inventory_pools.id, + SELECT inventory_pools.id, SUM(reservations.quantity) AS quantity, inventory_pools.name AS label FROM "inventory_pools" @@ -56,24 +54,20 @@ module StatisticsSteps SQL @inventory_pools = ActiveRecord::Base.connection.exec_query(sql).to_hash within '.list-of-lines' do - @inventory_pools.each do |ip| - expect(page).to have_content ip['label'] - end + @inventory_pools.each { |ip| expect(page).to have_content ip['label'] } end end step 'I expand an inventory pool' do @inventory_pool = @inventory_pools.first - within('.list-of-lines .row', - text: @inventory_pool['name'], - match: :first) do + within('.list-of-lines .row', text: @inventory_pool['name'], match: :first) do find('.toggle').click end end step 'I see all models which this inventory pool is responsible for' do sql = <<-SQL - SELECT models.id, + SELECT models.id, SUM(reservations.quantity) AS quantity, CONCAT_WS(' ', models.manufacturer, @@ -84,7 +78,9 @@ module StatisticsSteps WHERE ("reservations"."type" = 'ItemLine' AND "reservations"."item_id" IS NOT NULL AND "reservations"."returned_date" IS NOT NULL) - AND "reservations"."inventory_pool_id" = '#{@inventory_pool['id']}' + AND "reservations"."inventory_pool_id" = '#{@inventory_pool[ + 'id' + ]}' AND ("reservations"."start_date" >= '#{@date1}') AND ("reservations"."returned_date" <= '#{@date2}') GROUP BY models.id, @@ -95,9 +91,7 @@ module StatisticsSteps @models = ActiveRecord::Base.connection.exec_query(sql).to_hash within '.list-of-lines .children' do - @models.each do |model| - find('.row', text: model['name'], match: :first) - end + @models.each { |model| find('.row', text: model['name'], match: :first) } end end @@ -116,7 +110,7 @@ module StatisticsSteps @date2 = Date.today.to_formatted_s(:db) sql = <<-SQL - SELECT users.id, + SELECT users.id, SUM(reservations.quantity) AS quantity, CONCAT_WS(' ', users.firstname, users.lastname) AS label FROM "users" @@ -133,24 +127,18 @@ module StatisticsSteps @users = ActiveRecord::Base.connection.exec_query(sql).to_hash within '.list-of-lines' do - @users.each do |user| - expect(page).to have_content user['label'] - end + @users.each { |user| expect(page).to have_content user['label'] } end end step 'I expand the first user' do @user = @users.first - within('.list-of-lines .row', - text: @user['name'], - match: :first) do - find('.toggle').click - end + within('.list-of-lines .row', text: @user['name'], match: :first) { find('.toggle').click } end step 'I see all models which the users has borrowed' do sql = <<-SQL - SELECT models.id, + SELECT models.id, SUM(reservations.quantity) AS quantity, CONCAT_WS(' ', models.manufacturer, @@ -161,7 +149,9 @@ module StatisticsSteps WHERE ("reservations"."type" = 'ItemLine' AND "reservations"."item_id" IS NOT NULL AND "reservations"."returned_date" IS NOT NULL) - AND "reservations"."user_id" = '#{@user['id']}' + AND "reservations"."user_id" = '#{@user[ + 'id' + ]}' AND ("reservations"."start_date" >= '#{@date1}') AND ("reservations"."returned_date" <= '#{@date2}') GROUP BY models.id, @@ -172,22 +162,22 @@ module StatisticsSteps @models = ActiveRecord::Base.connection.exec_query(sql).to_hash within '.list-of-lines .children' do - @models.each do |model| - find('.row', text: model['name'], match: :first) - end + @models.each { |model| find('.row', text: model['name'], match: :first) } end end step 'I see all models for which this inventory pool owns items' do sql = <<-SQL - SELECT models.id, + SELECT models.id, COUNT(items.id) AS quantity, SUM(items.price) AS price, models.product AS label FROM "models" INNER JOIN "items" ON "items"."model_id" = "models"."id" WHERE ("items"."price" > 0) - AND "items"."owner_id" = '#{@inventory_pool['id']}' + AND "items"."owner_id" = '#{@inventory_pool[ + 'id' + ]}' AND ("items"."created_at" >= '#{@date1}') AND ("items"."created_at" <= '#{@date2}') GROUP BY items.model_id, @@ -198,14 +188,12 @@ module StatisticsSteps @models = ActiveRecord::Base.connection.exec_query(sql).to_hash within '.list-of-lines .children' do - @models.each do |model| - find('.row', text: model['name'], match: :first) - end + @models.each { |model| find('.row', text: model['name'], match: :first) } end end step 'for each model a sum of the purchase price of all matching items ' \ - 'in this inventory pool' do + 'in this inventory pool' do within '.list-of-lines .children' do @models.each do |model| within('.row', text: model['label'], match: :first) do @@ -221,7 +209,7 @@ module StatisticsSteps @date1 = 1.month.ago.to_formatted_s(:db) @date2 = Date.today.to_formatted_s(:db) sql = <<-SQL - SELECT inventory_pools.id, + SELECT inventory_pools.id, COUNT(items.id) AS quantity, SUM(items.price) AS price, inventory_pools.name AS label @@ -236,14 +224,12 @@ module StatisticsSteps SQL @inventory_pools = ActiveRecord::Base.connection.exec_query(sql).to_hash within '.list-of-lines' do - @inventory_pools.each do |ip| - expect(page).to have_content ip['label'] - end + @inventory_pools.each { |ip| expect(page).to have_content ip['label'] } end end step 'for each model the number of items ' \ - 'of this model in that inventory pool' do + 'of this model in that inventory pool' do within '.list-of-lines .children' do @models.each do |model| within('.row', text: model['label'], match: :first) do diff --git a/engines/leihs_admin/spec/steps/suppliers_steps.rb b/engines/leihs_admin/spec/steps/suppliers_steps.rb index 900f127d91..4f6fa5e9f7 100644 --- a/engines/leihs_admin/spec/steps/suppliers_steps.rb +++ b/engines/leihs_admin/spec/steps/suppliers_steps.rb @@ -20,26 +20,23 @@ module SuppliersSteps end step 'I create a new supplier :whether_providing ' \ - 'all required values' do |whether_providing| + 'all required values' do |whether_providing| find('.btn', text: _('Create %s') % _('Supplier')).click unless whether_providing - # not providing supplier[name] 9 + else @name = Faker::Address.street_address find("input[name='supplier[name]']").set @name end + # not providing supplier[name] 9 end step 'I see the :new_or_existing supplier' do |_| - within '.list-of-lines' do - find('.row > .col-sm-6', text: @name) - end + within '.list-of-lines' dofind('.row > .col-sm-6', text: @name)end end step 'I see the supplier form' do - within 'form' do - find("input[name='supplier[name]']") - end + within 'form' dofind("input[name='supplier[name]']")end end step 'I edit an existing supplier' do @@ -63,8 +60,8 @@ module SuppliersSteps # NOTE: removing header and footer # they are causing problems on Cider => covering the element # we want to click on - page.execute_script %($('header').remove();) - page.execute_script %($('footer').remove();) + page.execute_script "$('header').remove();" + page.execute_script "$('footer').remove();" ############################################################ within '.list-of-lines' do @@ -80,8 +77,7 @@ module SuppliersSteps step "I don't see the deleted supplier" do within '.list-of-lines' do - expect(has_no_selector?('.row > .col-sm-6', text: @supplier.name)) - .to be true + expect(has_no_selector?('.row > .col-sm-6', text: @supplier.name)).to be true end end end diff --git a/factories/access_right_factory.rb b/factories/access_right_factory.rb index ef60d1f00d..eec026e487 100644 --- a/factories/access_right_factory.rb +++ b/factories/access_right_factory.rb @@ -1,9 +1,7 @@ FactoryGirl.define do - factory :access_right do role { :customer } user inventory_pool end - end diff --git a/factories/accessory_factory.rb b/factories/accessory_factory.rb index 6fb7d6be47..62da311114 100644 --- a/factories/accessory_factory.rb +++ b/factories/accessory_factory.rb @@ -1,8 +1,6 @@ FactoryGirl.define do - factory :accessory do model name { Faker::Name.name } end - end diff --git a/factories/authentication_system_factory.rb b/factories/authentication_system_factory.rb index 75334d5849..d01b2a756d 100644 --- a/factories/authentication_system_factory.rb +++ b/factories/authentication_system_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :authentication_system do name Faker::Lorem.words(1).join.capitalize class_name { name } diff --git a/factories/authentication_system_user_factory.rb b/factories/authentication_system_user_factory.rb index 2164e3f34d..23b7a41173 100644 --- a/factories/authentication_system_user_factory.rb +++ b/factories/authentication_system_user_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :authentication_system_user do association :user authentication_system_id 'password' diff --git a/factories/building_factory.rb b/factories/building_factory.rb index c9d840f015..a0a76064e7 100644 --- a/factories/building_factory.rb +++ b/factories/building_factory.rb @@ -1,8 +1,6 @@ FactoryGirl.define do - factory :building do name { Faker::Lorem.words(3).join.capitalize } code { Faker::Lorem.words(3).join[0..2] } end - end diff --git a/factories/category_factory.rb b/factories/category_factory.rb index 34749e1ef0..cc07bde0a3 100644 --- a/factories/category_factory.rb +++ b/factories/category_factory.rb @@ -1,7 +1 @@ -FactoryGirl.define do - - factory :category do - name Faker::Lorem.words(3).join.capitalize - end - -end +doname Faker::Lorem.words(3).join.capitalizeend diff --git a/factories/contract_factory.rb b/factories/contract_factory.rb index d27d9faa5d..610bb59c40 100644 --- a/factories/contract_factory.rb +++ b/factories/contract_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :contract do note { Faker::Lorem.paragraph } purpose { Faker::Lorem.sentence } @@ -7,21 +6,16 @@ inventory_pool { FactoryGirl.create(:inventory_pool) } user do user = FactoryGirl.create(:user) - unless AccessRight.find_by(user: user, - inventory_pool: inventory_pool, - deleted_at: nil) - FactoryGirl.create(:access_right, - user: user, - inventory_pool: inventory_pool, - role: :customer) + unless AccessRight.find_by(user: user, inventory_pool: inventory_pool, deleted_at: nil) + FactoryGirl.create( + :access_right, user: user, inventory_pool: inventory_pool, role: :customer + ) end user end transient do - items do - Array.new(3).map { |_| FactoryGirl.create(:item) } - end + items { Array.new(3).map { |_| FactoryGirl.create(:item) } } contact_person nil start_date nil end_date nil @@ -31,13 +25,13 @@ state :open after :build do |c, evaluator| - order = FactoryGirl.create(:order, - user: c.user, - inventory_pool: c.inventory_pool, - state: :approved) + order = + FactoryGirl.create( + :order, user: c.user, inventory_pool: c.inventory_pool, state: :approved + ) evaluator.items.each do |item| - c.reservations << \ + c.reservations << FactoryGirl.build( :reservation, status: :signed, @@ -59,13 +53,13 @@ state :closed after :build do |c, evaluator| - order = FactoryGirl.create(:order, - user: c.user, - inventory_pool: c.inventory_pool, - state: :approved) + order = + FactoryGirl.create( + :order, user: c.user, inventory_pool: c.inventory_pool, state: :approved + ) evaluator.items.each do |item| - c.reservations << \ + c.reservations << FactoryGirl.build( :reservation, status: :closed, @@ -83,5 +77,4 @@ end end end - end diff --git a/factories/group_factory.rb b/factories/group_factory.rb index eda7ec9e5f..bade826962 100644 --- a/factories/group_factory.rb +++ b/factories/group_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :group, class: EntitlementGroup do name { Faker::Name.name } association :inventory_pool diff --git a/factories/image_factory.rb b/factories/image_factory.rb index 6adce24160..b36ec1e087 100644 --- a/factories/image_factory.rb +++ b/factories/image_factory.rb @@ -1,13 +1,10 @@ FactoryGirl.define do - trait :shared_attachment_attributes do filename { Faker::Lorem.word } content_type 'image/jpeg' size 1_000_000 - transient do - filepath 'features/data/images/image1.jpg' - end + transient { filepath 'features/data/images/image1.jpg' } after(:build) do |image, evaluator| file = File.open(evaluator.filepath) @@ -24,17 +21,12 @@ shared_attachment_attributes trait :another do - transient do - filepath 'features/data/images/image2.jpg' - end + transient { filepath 'features/data/images/image2.jpg' } end trait :with_thumbnail do after(:create) do |image, evaluator| - create(:image, - thumbnail: true, - filepath: evaluator.filepath, - parent_id: image.id) + create(:image, thumbnail: true, filepath: evaluator.filepath, parent_id: image.id) end end end diff --git a/factories/inventory_pool_factory.rb b/factories/inventory_pool_factory.rb index 0ed4727d68..28b0a4a266 100644 --- a/factories/inventory_pool_factory.rb +++ b/factories/inventory_pool_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :inventory_pool do |i| name { Faker::Lorem.words(4).join.capitalize } description { Faker::Lorem.sentence } @@ -12,11 +11,9 @@ after(:create) do |inventory_pool| MailTemplate.where(is_template_template: true).each do |mt| - MailTemplate.create! \ - mt.attributes - .reject { |k, _| k == 'id' } - .merge(is_template_template: false, - inventory_pool_id: inventory_pool.id) + MailTemplate.create! mt.attributes.reject { |k, _| k == 'id' }.merge( + is_template_template: false, inventory_pool_id: inventory_pool.id + ) end end @@ -24,11 +21,9 @@ after(:create) do |inventory_pool, evaluator| rand(3..6).times do user = FactoryGirl.create :user - user.access_rights.create(inventory_pool: inventory_pool, - role: :customer) + user.access_rights.create(inventory_pool: inventory_pool, role: :customer) end end end end - end diff --git a/factories/item_factory.rb b/factories/item_factory.rb index 34e726ab15..cf0c4218a5 100644 --- a/factories/item_factory.rb +++ b/factories/item_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - trait :shared_item_license_attributes do sequence(:inventory_code) { |n| "#{Faker::Lorem.characters(20)}#{n}" } serial_number { Faker::Lorem.characters(20) } @@ -14,12 +13,8 @@ room after(:build) do |item| - if item.properties? - item.properties = item.properties.with_indifferent_access - end - if item.is_inventory_relevant - item.properties[:anschaffungskategorie] ||= 'AV-Technik' - end + item.properties = item.properties.with_indifferent_access if item.properties? + item.properties[:anschaffungskategorie] ||= 'AV-Technik' if item.is_inventory_relevant end end @@ -29,9 +24,7 @@ model { FactoryGirl.create :model } supplier { FactoryGirl.create :supplier } invoice_date do - Time.zone.local((Time.zone.now.year - rand(5) - 1), - (rand(12) + 1), - (rand(31) + 1)).to_date + Time.zone.local((Time.zone.now.year - rand(5) - 1), (rand(12) + 1), (rand(31) + 1)).to_date end price { rand(1500).round(2) } is_broken 0 @@ -45,12 +38,13 @@ model { FactoryGirl.create :software } properties do - { license_type: 'single_workplace', + { + license_type: 'single_workplace', activation_type: 'serial_number', operating_system: ['windows', 'linux'], installation: ['citrix', 'web'], procured_by: [true, false].sample ? User.all.sample.to_s : nil - } + } end end end diff --git a/factories/language_factory.rb b/factories/language_factory.rb index 9fa3620aa1..ba09e87a14 100644 --- a/factories/language_factory.rb +++ b/factories/language_factory.rb @@ -2,28 +2,27 @@ module LanguageFactory module_function def create - languages = [{ name: 'Deutsch', locale_name: 'de-CH' }, - { name: 'English (UK)', locale_name: 'en-GB' }, - { name: 'English (US)', locale_name: 'en-US' }] + languages = [ + { name: 'Deutsch', locale_name: 'de-CH' }, { name: 'English (UK)', locale_name: 'en-GB' }, { + name: 'English (US)', locale_name: 'en-US' + } + ] languages.delete_if { |l| Language.find_by_locale_name(l[:locale_name]) } if languages.empty? Language.first else - FactoryGirl.create(:language, - name: languages.first[:name], - locale_name: languages.first[:locale_name]) + FactoryGirl.create( + :language, name: languages.first[:name], locale_name: languages.first[:locale_name] + ) end end - end FactoryGirl.define do - factory :language do active { true } name { Faker::Lorem.words(1).join } locale_name { name[0..1].downcase } default { Language.find_by_default(true).blank? } end - end diff --git a/factories/model_factory.rb b/factories/model_factory.rb index 7d62f9191f..84fded803a 100644 --- a/factories/model_factory.rb +++ b/factories/model_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - sequence :version trait :shared_model_software_attributes do @@ -32,16 +31,15 @@ end after(:create) do |model, evaluator| 3.times do - model.items << \ - FactoryGirl.create(:item, - is_borrowable: evaluator.is_borrowable, - inventory_pool: evaluator.inventory_pool) + model.items << + FactoryGirl.create( + :item, + is_borrowable: evaluator.is_borrowable, inventory_pool: evaluator.inventory_pool + ) end end end - end factory :software, traits: [:shared_model_software_attributes] - end diff --git a/factories/model_group_factory.rb b/factories/model_group_factory.rb index 458099e1d4..90ad50499a 100644 --- a/factories/model_group_factory.rb +++ b/factories/model_group_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :model_group do name { Faker::Name.name } type { (rand(0..4) == 4) ? 'Template' : 'Categorie' } diff --git a/factories/model_link_factory.rb b/factories/model_link_factory.rb index ef12bc9084..54ac43d7fa 100644 --- a/factories/model_link_factory.rb +++ b/factories/model_link_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :model_link do model_group { FactoryGirl.create :model_group } model { FactoryGirl.create :model } diff --git a/factories/option_factory.rb b/factories/option_factory.rb index e1ceba687c..2e71dfbc4b 100644 --- a/factories/option_factory.rb +++ b/factories/option_factory.rb @@ -1,10 +1,7 @@ FactoryGirl.define do - factory :option do inventory_pool { FactoryGirl.create :inventory_pool } - inventory_code do - "#{Faker::Lorem.words(3).join.slice(0, 3)}#{rand(9999) + 1000}" - end + inventory_code { "#{Faker::Lorem.words(3).join.slice(0, 3)}#{rand(9999) + 1000}" } manufacturer { nil } product { Faker::Commerce.product_name } version diff --git a/factories/order_factory.rb b/factories/order_factory.rb index 9c09d8e746..6c9d791cbf 100644 --- a/factories/order_factory.rb +++ b/factories/order_factory.rb @@ -1,9 +1,7 @@ FactoryGirl.define do - factory :order do inventory_pool user { FactoryGirl.create(:customer, inventory_pool: inventory_pool) } purpose { Faker::Lorem.sentence } end - end diff --git a/factories/package_factory.rb b/factories/package_factory.rb index b9e919f110..1ccfa1eba3 100644 --- a/factories/package_factory.rb +++ b/factories/package_factory.rb @@ -1,17 +1,13 @@ FactoryGirl.define do - factory :package_model, parent: :model do is_package true factory :package_model_with_items do - transient do - inventory_pool { FactoryGirl.create :inventory_pool } - end + transient { inventory_pool { FactoryGirl.create :inventory_pool } } after(:create) do |package, evaluator| 3.times do - package.items << \ - FactoryGirl.create(:package_item_with_parts, - owner: evaluator.inventory_pool) + package.items << + FactoryGirl.create(:package_item_with_parts, owner: evaluator.inventory_pool) end end end @@ -20,14 +16,8 @@ factory :package_item, parent: :item do factory :package_item_with_parts do after(:create) do |item, evaluator| - 3.times do - item.children << \ - FactoryGirl.create(:item, - owner: evaluator.owner, - parent: item) - end + 3.times { item.children << FactoryGirl.create(:item, owner: evaluator.owner, parent: item) } end end end - end diff --git a/factories/reservation_factory.rb b/factories/reservation_factory.rb index 95835d2b33..353abaef8c 100644 --- a/factories/reservation_factory.rb +++ b/factories/reservation_factory.rb @@ -1,14 +1,14 @@ FactoryGirl.define do - trait :shared_reservations_attributes do inventory_pool user do u1 = inventory_pool.users.customers.sample - u1 ||= begin - u2 = FactoryGirl.create :user - u2.access_rights.create(inventory_pool: inventory_pool, role: :customer) - u2 - end + u1 ||= + begin + u2 = FactoryGirl.create :user + u2.access_rights.create(inventory_pool: inventory_pool, role: :customer) + u2 + end u1 end status { :unsubmitted } @@ -27,7 +27,8 @@ inventory_pool.models.shuffle.detect do |model| av = model.availability_in(inventory_pool) av.entitlements[nil] > 0 and av.running_reservations.empty? - end || FactoryGirl.create(:model_with_items, inventory_pool: inventory_pool) + end || + FactoryGirl.create(:model_with_items, inventory_pool: inventory_pool) end trait :with_assigned_item do @@ -36,19 +37,19 @@ end trait :with_purpose do - transient do - purpose { Faker::Lorem.sentence } - end + transient { purpose { Faker::Lorem.sentence } } status :submitted after :build do |reservation, evaluator| unless reservation.status == :unsubmitted - reservation.order = \ - FactoryGirl.create(:order, - user: reservation.user, - inventory_pool: reservation.inventory_pool, - state: reservation.status, - purpose: evaluator.purpose) + reservation.order = + FactoryGirl.create( + :order, + user: reservation.user, + inventory_pool: reservation.inventory_pool, + state: reservation.status, + purpose: evaluator.purpose + ) end end end @@ -59,8 +60,7 @@ quantity { 1 } option do - inventory_pool.options.sample || - FactoryGirl.create(:option, inventory_pool: inventory_pool) + inventory_pool.options.sample || FactoryGirl.create(:option, inventory_pool: inventory_pool) end end end diff --git a/factories/room_factory.rb b/factories/room_factory.rb index dfcd743d11..32af247710 100644 --- a/factories/room_factory.rb +++ b/factories/room_factory.rb @@ -1,8 +1,6 @@ FactoryGirl.define do - factory :room do name { Faker::Lorem.words(3).join.capitalize } building end - end diff --git a/factories/setting_factory.rb b/factories/setting_factory.rb index e2ff93a883..e0595beb92 100644 --- a/factories/setting_factory.rb +++ b/factories/setting_factory.rb @@ -1,7 +1,6 @@ # coding: UTF-8 FactoryGirl.define do - factory :setting do smtp_address { 'smtp.zhdk.ch' } smtp_port { 25 } @@ -10,28 +9,25 @@ local_currency_string { 'CHF' } contract_terms do 'Die Benutzerin/der Benutzer ist bei unsachgemässer Handhabung oder ' \ - 'Verlust schadenersatzpflichtig. Sie/Er verpflichtet sich, das Material ' \ - 'sorgfältig zu behandeln und gereinigt zu retournieren. Bei ' \ - 'mangelbehafteter oder verspäteter Rückgabe kann eine Ausleihsperre ' \ - '(bis zu 6 Monaten) verhängt werden. Das geliehene Material bleibt ' \ - 'jederzeit uneingeschränktes Eigentum der Zürcher Hochschule der Künste ' \ - 'und darf ausschliesslich für schulische Zwecke eingesetzt werden. ' \ - 'Mit ihrer/seiner Unterschrift akzeptiert die Benutzerin/der Benutzer ' \ - "diese Bedingungen sowie die 'Richtlinie zur Ausleihe von Sachen' der " \ - 'ZHdK und etwaige abteilungsspezifische Ausleih-Richtlinien.' + 'Verlust schadenersatzpflichtig. Sie/Er verpflichtet sich, das Material ' \ + 'sorgfältig zu behandeln und gereinigt zu retournieren. Bei ' \ + 'mangelbehafteter oder verspäteter Rückgabe kann eine Ausleihsperre ' \ + '(bis zu 6 Monaten) verhängt werden. Das geliehene Material bleibt ' \ + 'jederzeit uneingeschränktes Eigentum der Zürcher Hochschule der Künste ' \ + 'und darf ausschliesslich für schulische Zwecke eingesetzt werden. ' \ + 'Mit ihrer/seiner Unterschrift akzeptiert die Benutzerin/der Benutzer ' \ + "diese Bedingungen sowie die 'Richtlinie zur Ausleihe von Sachen' der " \ + 'ZHdK und etwaige abteilungsspezifische Ausleih-Richtlinien.' end - contract_lending_party_string { "Your\nAddress\nHere" } + contract_lending_party_string { 'YourundefinedAddressundefinedHere' } email_signature { 'Das PZ-leihs Team' } default_email { 'sender@example.com' } deliver_received_order_notifications { false } - user_image_url do - 'http://www.zhdk.ch/?person/foto&width=100&compressionlevel=0&id={:id}' - end + user_image_url { 'http://www.zhdk.ch/?person/foto&width=100&compressionlevel=0&id={:id}' } logo_url { '/assets/image-logo-zhdk.png' } disable_manage_section { false } disable_manage_section_message { '' } disable_borrow_section { false } disable_borrow_section_message { '' } end - end diff --git a/factories/supplier_factory.rb b/factories/supplier_factory.rb index 66c1a03354..aba74dedd4 100644 --- a/factories/supplier_factory.rb +++ b/factories/supplier_factory.rb @@ -1,7 +1,5 @@ FactoryGirl.define do factory :supplier do - name do - "#{Faker::Lorem.words(3).shuffle.join(' ')}_#{Faker::Lorem.characters(16)}" - end + name { "#{Faker::Lorem.words(3).shuffle.join(' ')}_#{Faker::Lorem.characters(16)}" } end end diff --git a/factories/template_factory.rb b/factories/template_factory.rb index 6c41277c88..0f7a6eefe6 100644 --- a/factories/template_factory.rb +++ b/factories/template_factory.rb @@ -1,13 +1,8 @@ FactoryGirl.define do - factory :template do name { Faker::Name.name } type { 'Template' } - after(:build) do |template| - 3.times do - template.model_links << FactoryGirl.build(:model_link) - end - end + after(:build) { |template| 3.times { template.model_links << FactoryGirl.build(:model_link) } } end end diff --git a/factories/user_factory.rb b/factories/user_factory.rb index 57b3e1e80b..865f381908 100644 --- a/factories/user_factory.rb +++ b/factories/user_factory.rb @@ -1,12 +1,8 @@ FactoryGirl.define do - factory :user do # make sure the login has at least 3 chars login do - [Faker::Internet.user_name, - Faker::Lorem.characters(8), - (100..9999).to_a.sample] - .join('_') + [Faker::Internet.user_name, Faker::Lorem.characters(8), (100..9999).to_a.sample].join('_') end firstname { Faker::Name.first_name } lastname { Faker::Name.last_name } @@ -28,43 +24,27 @@ city { Faker::Address.city } country { Faker::Address.country } zip { "#{country[0]}-#{Faker::Address.zip_code}".squish } - language do - Language.find_by_default(true) || create(:language, locale_name: 'en-GB') - end + language { Language.find_by_default(true) || create(:language, locale_name: 'en-GB') } delegator_user { nil } - after(:create) do |user| - unless user.delegation? - create :authentication_system_user, user: user - end - end + after(:create) { |user| create :authentication_system_user, user: user unless user.delegation? } factory :delegation do delegator_user { FactoryGirl.create(:user) } end - [:customer, - :group_manager, - :lending_manager, - :inventory_manager].each do |role| + [:customer, :group_manager, :lending_manager, :inventory_manager].each do |role| factory role do - transient do - inventory_pool nil - end + transient { inventory_pool nil } after(:create) do |user, evaluator| - create(:access_right, - user: user, - inventory_pool: evaluator.inventory_pool, - role: role) + create(:access_right, user: user, inventory_pool: evaluator.inventory_pool, role: role) end end end factory :admin do - after(:create) do |user, evaluator| - user.update_attributes! is_admin: true - end + after(:create) { |user, evaluator| user.update_attributes! is_admin: true } end end end diff --git a/factories/user_session_factory.rb b/factories/user_session_factory.rb index f55bf817fe..792fcf5244 100644 --- a/factories/user_session_factory.rb +++ b/factories/user_session_factory.rb @@ -1,5 +1 @@ -FactoryGirl.define do - factory :user_session do - token_hash { Digest::SHA256.hexdigest SecureRandom.uuid } - end -end +dotoken_hash { Digest::SHA256.hexdigest SecureRandom.uuid } diff --git a/factories/workday_factory.rb b/factories/workday_factory.rb index 4557c6ef0d..1639e2d2e5 100644 --- a/factories/workday_factory.rb +++ b/factories/workday_factory.rb @@ -1,5 +1,4 @@ FactoryGirl.define do - factory :workday do inventory_pool monday { rand > 0.5 } @@ -10,5 +9,4 @@ saturday { rand > 0.5 } sunday { rand > 0.5 } end - end diff --git a/features/step_definitions/acknowledge_steps.rb b/features/step_definitions/acknowledge_steps.rb index 9fa12d77c0..5d64b3ab67 100644 --- a/features/step_definitions/acknowledge_steps.rb +++ b/features/step_definitions/acknowledge_steps.rb @@ -5,7 +5,7 @@ # @response = response # end -When "$who chooses $name's order" do | who, name | +When "$who chooses $name's order" do |who, name| order = @orders.detect { |o| o.user.login == name } get manage_edit_order_path(@inventory_pool, order) response.should render_template('backend/acknowledge/show') @@ -14,12 +14,14 @@ end When "$who rejects order with reason '$reason'" do |who, reason| - post "/manage/#{@inventory_pool.id}/orders/#{@order.id}/reject", {comment: reason} + post "/manage/#{@inventory_pool.id}/orders/#{@order.id}/reject", { comment: reason } @order = assigns(:order) expect(@orders).not_to be_nil expect(@order).not_to be_nil @response = response - expect(response.redirect_url).to eq "http://www.example.com/backend/inventory_pools/#{@inventory_pool.id}/acknowledge" + expect( + response.redirect_url + ).to eq "http://www.example.com/backend/inventory_pools/#{@inventory_pool.id}/acknowledge" end # When "$who adds $quantity item '$model'" do |who, quantity, model| @@ -33,7 +35,6 @@ # expect(@response.redirect_url).to include("backend/inventory_pools/#{@inventory_pool.id}/acknowledge/#{@order.id}") # end - When "$who adds a personal message: '$message'" do |who, message| @comment = message end @@ -60,7 +61,7 @@ # expect(@order).not_to be_nil # end -Then /^(.*) see(s)? ([0-9]+) order(s?)$/ do | who, foo, size, s | +Then /^(.*) see(s)? ([0-9]+) order(s?)$/ do |who, foo, size, s| find('.table-overview .fresh') end @@ -78,8 +79,12 @@ # @order.user.id.should == user.id #end -Then 'Swap Item screen opens' do - expect(@response.redirect_url).to include("/backend/inventory_pools/#{@inventory_pool.id}/models?layout=modal&reservation_id=#{@reservation_id}&source_path=%2Fbackend%2Finventory_pools%2F#{@inventory_pool.id}%2Facknowledge%2F#{@order.id}%2Fswap_model_line%3Fline_id%3D#{@reservation_id}") +Then 'Swap Item screen opens' do + expect(@response.redirect_url).to include( + "/backend/inventory_pools/#{@inventory_pool + .id}/models?layout=modal&reservation_id=#{@reservation_id}&source_path=%2Fbackend%2Finventory_pools%2F#{@inventory_pool + .id}%2Facknowledge%2F#{@order.id}%2Fswap_model_line%3Fline_id%3D#{@reservation_id}" + ) end Then 'a choice of $size item appears' do |size| @@ -93,8 +98,11 @@ end Then "all '$what' order reservations are marked as invalid" do |what| - # TODO: VERY ugly - we need have_tag "td.valid_false" - expect(@response.body).to match /valid_false/ + expect( + # TODO: VERY ugly - we need have_tag "td.valid_false" + @response + .body + ).to match /valid_false/ end Then /the order should( not)? be approvable(.*)/ do |arg1, reason| diff --git a/features/step_definitions/automatic_email_delivery_steps.rb b/features/step_definitions/automatic_email_delivery_steps.rb index 28c05d19eb..af469b6a4c 100644 --- a/features/step_definitions/automatic_email_delivery_steps.rb +++ b/features/step_definitions/automatic_email_delivery_steps.rb @@ -4,7 +4,7 @@ setting = Setting.first # Need to have these settings, otherwise we can't save. Ouch, coupling. - if not setting + if nsetting setting = Setting.new setting[:local_currency_string] = 'GBP' setting[:email_signature] = 'Cheers,' @@ -37,7 +37,9 @@ expect(ActionMailer::Base.deliveries.empty?).to be false expect(@current_user.notifications.reload.empty?).to be false - expect(ActionMailer::Base.deliveries.detect {|x| x.to.include? @current_user.email}.nil?).to be false + expect( + ActionMailer::Base.deliveries.detect { |x| x.to.include? @current_user.email }.nil? + ).to be false end Then(/^the day after the take back I receive a remember email$/) do @@ -49,7 +51,7 @@ expect(ActionMailer::Base.deliveries.empty?).to be false expect(@current_user.notifications.reload.empty?).to be false - expect(ActionMailer::Base.deliveries.detect {|x| x.to == @current_user.emails }.nil?).to be false + expect(ActionMailer::Base.deliveries.detect { |x| x.to == @current_user.emails }.nil?).to be false end Then(/^for each further day I receive an additional remember email$/) do @@ -64,6 +66,5 @@ expect(ActionMailer::Base.deliveries.empty?).to be false expect(@current_user.notifications.reload.empty?).to be false - expect(ActionMailer::Base.deliveries.detect {|x| x.to == @current_user.emails }.nil?).to be false + expect(ActionMailer::Base.deliveries.detect { |x| x.to == @current_user.emails }.nil?).to be false end - diff --git a/features/step_definitions/availability_inventory_pool_steps.rb b/features/step_definitions/availability_inventory_pool_steps.rb index 5a3f25c9f5..d2ea0c612d 100644 --- a/features/step_definitions/availability_inventory_pool_steps.rb +++ b/features/step_definitions/availability_inventory_pool_steps.rb @@ -1,8 +1,6 @@ Given 'this model has $number item$s in inventory pool $ip' do |number, s, ip| inventory_pool = InventoryPool.find_by_name(ip) - number.to_i.times do | i | - FactoryGirl.create(:item, owner: inventory_pool, model: @model) - end + number.to_i.times { |i| FactoryGirl.create(:item, owner: inventory_pool, model: @model) } expect(inventory_pool.items.where(model_id: @model.id).count).to eq number.to_i end @@ -18,10 +16,12 @@ Then "he sees the '$model' model" do |model| m = Model.find_by_name(model) - expect(@models_json.map{|x| x['label']}.include?(m.name)).to be true + expect(@models_json.map { |x| x['label'] }.include?(m.name)).to be true end -Then /^this user has (\d+) unsubmitted reservations, which (\d+) are available$/ do |all_n, available_n| +Then / + ^this user has (\d+) unsubmitted reservations, which (\d+) are available$ + / do |all_n, available_n| reservations = @user.reservations.unsubmitted expect(reservations.size).to eq all_n.to_i reservations = reservations.select &:available? diff --git a/features/step_definitions/availability_steps.rb b/features/step_definitions/availability_steps.rb index d590dcafd8..81e53cb559 100644 --- a/features/step_definitions/availability_steps.rb +++ b/features/step_definitions/availability_steps.rb @@ -1,25 +1,27 @@ Given "$number reservations exist for model '$model'" do |number, model| - # used by "0 reservations exist for model 'NEC 245'" + end Given "a reservation exists for $quantity '$model' from $from to $to" do |quantity, model, from, to| model = Model.find_by_name(model) - inventory_pool = model.inventory_pools.select{|ip| ip.open_on?(to_date(from)) and ip.open_on?(to_date(to))}.sample + inventory_pool = + model.inventory_pools.select { |ip| ip.open_on?(to_date(from)) and ip.open_on?(to_date(to)) } + .sample user = inventory_pool.users.sample @reservations = [] - order = FactoryGirl.create(:order, - user: user, - inventory_pool: inventory_pool, - state: :submitted) + order = FactoryGirl.create(:order, user: user, inventory_pool: inventory_pool, state: :submitted) quantity.to_i.times do - @reservations << user.item_lines.create(inventory_pool: inventory_pool, - status: :submitted, - quantity: 1, - user: user, - order: order, - model: model, - start_date: to_date(from), - end_date: to_date(to)) + @reservations << + user.item_lines.create( + inventory_pool: inventory_pool, + status: :submitted, + quantity: 1, + user: user, + order: order, + model: model, + start_date: to_date(from), + end_date: to_date(to) + ) end expect(@reservations.size).to be >= quantity.to_i expect(model.availability_in(inventory_pool.reload).running_reservations.size).to be >= 1 @@ -27,30 +29,29 @@ Given "a contract exists for $quantity '$model' from $from to $to" do |quantity, model, from, to| model = Model.find_by_name(model) - inventory_pool = model.inventory_pools.detect { |ip| ip.open_on?(to_date(from)) && ip.open_on?(to_date(to)) } + inventory_pool = + model.inventory_pools.detect { |ip| ip.open_on?(to_date(from)) && ip.open_on?(to_date(to)) } user = inventory_pool.users.first @reservations = [] - order = FactoryGirl.create(:order, - user: user, - inventory_pool: inventory_pool, - state: :approved) + order = FactoryGirl.create(:order, user: user, inventory_pool: inventory_pool, state: :approved) quantity.to_i.times do - @reservations << user.item_lines.create(inventory_pool: inventory_pool, - user: user, - status: :approved, - quantity: 1, - model: model, - item: model.items.in_stock.where(inventory_pool_id: inventory_pool).first, - start_date: to_date(from), - end_date: to_date(to), - order: order) + @reservations << + user.item_lines.create( + inventory_pool: inventory_pool, + user: user, + status: :approved, + quantity: 1, + model: model, + item: model.items.in_stock.where(inventory_pool_id: inventory_pool).first, + start_date: to_date(from), + end_date: to_date(to), + order: order + ) end expect(@reservations.size).to be >= quantity.to_i expect(model.availability_in(inventory_pool.reload).running_reservations.size).to be >= 1 end - - Given 'the maintenance period for this model is $days days' do |days| @model.maintenance_period = days.to_i @model.save @@ -66,17 +67,18 @@ end Given 'the $who signs the contract' do |who| - contract = Contract.sign!(User.find_by_login(who), - @current_inventory_pool, - @reservations.first.user, - @reservations, - Faker::Lorem.sentence) + contract = + Contract.sign!( + User.find_by_login(who), + @current_inventory_pool, + @reservations.first.user, + @reservations, + Faker::Lorem.sentence + ) expect(contract.valid?).to be true expect(contract.persisted?).to be true expect(contract.reservations == @reservations).to be true - @reservations.each do |line| - expect(line.status).to eq :signed - end + @reservations.each { |line| expect(line.status).to eq :signed } end # TODO merge with next step @@ -88,37 +90,58 @@ # TODO merge with previous step When "$who checks availability for '$what' on $date" do |who, model, date| #date = to_date(date) - @current_user = User.find_by_login(who) + @current_user = + User.find_by_login(who) end Then 'it should always be available' do - expect(@model.availability_in(@inventory_pool).maximum_available_in_period_for_groups(Date.today, Availability::ETERNITY, @user.entitlement_group_ids)).to be > 0 + expect( + @model.availability_in(@inventory_pool).maximum_available_in_period_for_groups( + Date.today, Availability::ETERNITY, @user.entitlement_group_ids + ) + ).to be > 0 end Then '$quantity should be available from $from to $to' do |quantity, from, to| - from = to_date( from ) - to = to_date( to ) - expect(@model.availability_in(@inventory_pool).maximum_available_in_period_for_groups(from, to, @user.entitlement_group_ids)).to eq quantity.to_i + from = to_date(from) + to = to_date(to) + expect( + @model.availability_in(@inventory_pool).maximum_available_in_period_for_groups( + from, to, @user.entitlement_group_ids + ) + ).to eq quantity.to_i end Then 'the maximum available quantity on $date is $quantity' do |date, quantity| date = to_date(date) - expect(@model.availability_in(@inventory_pool).maximum_available_in_period_for_groups(date, date, @user.entitlement_group_ids)).to eq quantity.to_i + expect( + @model.availability_in(@inventory_pool).maximum_available_in_period_for_groups( + date, date, @user.entitlement_group_ids + ) + ).to eq quantity.to_i end Then 'if I check the maximum available quantity for $date it is $quantity on $current_date' do |date, quantity, current_date| date = to_date(date) - Dataset.back_to_date( to_date(current_date) ) + Dataset.back_to_date(to_date(current_date)) @inventory_pool.reload - expect(@model.availability_in(@inventory_pool).maximum_available_in_period_for_groups(date, date, @user.entitlement_group_ids)).to eq quantity.to_i + expect( + @model.availability_in(@inventory_pool).maximum_available_in_period_for_groups( + date, date, @user.entitlement_group_ids + ) + ).to eq quantity.to_i Dataset.back_to_date @inventory_pool.reload end Then 'the maximum available quantity from $start_date to $end_date is $quantity' do |start_date, end_date, quantity| start_date = to_date(start_date) - end_date = to_date(end_date) - expect(@model.availability_in(@inventory_pool).maximum_available_in_period_for_groups(start_date, end_date, @user.entitlement_group_ids)).to eq quantity.to_i + end_date = to_date(end_date) + expect( + @model.availability_in(@inventory_pool).maximum_available_in_period_for_groups( + start_date, end_date, @user.entitlement_group_ids + ) + ).to eq quantity.to_i end # When "I check the availability changes for '$model'" do |model| @@ -136,15 +159,17 @@ end # the following is extremely markup structure dependent -Then /^([^ ]*) reservation(.*)? should show an influence on the borrowability on (.*)/ do |number,plural,date| +Then / + ^([^ ]*) reservation(.*)? should show an influence on the borrowability on (.*) + / do |number, plural, date| number = to_number(number) # find header line, that contains the date th = page.first('th', text: "Borrowable #{date}") # parent 'tr' element - tr_head = th.first(:xpath,'..') + tr_head = th.first(:xpath, '..') # next 'tr' element - tr = tr_head.first(:xpath,'following-sibling::*') + tr = tr_head.first(:xpath, 'following-sibling::*') # all list entries inside that 'tr' element - expect(tr.all('li').count()).to eq number + expect(tr.all('li').count).to eq number end diff --git a/features/step_definitions/borrow/availability_steps.rb b/features/step_definitions/borrow/availability_steps.rb index aba48aa994..3eeffe0225 100644 --- a/features/step_definitions/borrow/availability_steps.rb +++ b/features/step_definitions/borrow/availability_steps.rb @@ -12,22 +12,27 @@ When(/^I add a model to an order$/) do @inventory_pool ||= @current_user.inventory_pools.first # OPTIMIZE - @new_reservation = FactoryGirl.create(:reservation, - user: @current_user, - delegated_user: @delegated_user, - status: :unsubmitted, - inventory_pool: @inventory_pool) + @new_reservation = + FactoryGirl.create( + :reservation, + user: @current_user, + delegated_user: @delegated_user, + status: :unsubmitted, + inventory_pool: @inventory_pool + ) expect(@new_reservation.reload.available?).to be true end When(/^I add the same model to an order$/) do (@new_reservation.maximum_available_quantity + 1).times do - FactoryGirl.create(:reservation, - status: :unsubmitted, - inventory_pool: @inventory_pool, - start_date: @new_reservation.start_date, - end_date: @new_reservation.end_date, - model_id: @new_reservation.model_id) + FactoryGirl.create( + :reservation, + status: :unsubmitted, + inventory_pool: @inventory_pool, + start_date: @new_reservation.start_date, + end_date: @new_reservation.end_date, + model_id: @new_reservation.model_id + ) end end @@ -44,38 +49,39 @@ ####################################################################### Given(/^(a|\d+) model(?:s)? (?:is|are) not available$/) do |n| - n = case n - when 'a' - 1 - else - n.to_i - end + n = + case n + when 'a' + 1 + else + n.to_i + end reservations = @current_user.reservations.unsubmitted - available_lines, unavailable_lines = reservations.partition {|line| line.available? } + available_lines, unavailable_lines = reservations.partition(&:available?) available_lines.take(n - unavailable_lines.size).each do |line| (line.maximum_available_quantity + 1).times do user = FactoryGirl.create(:customer, inventory_pool: line.inventory_pool) - FactoryGirl.create(:item_line, - status: :submitted, - inventory_pool: line.inventory_pool, - model: line.model, - user: user, - order: FactoryGirl.build(:order, - state: :submitted, - inventory_pool: line.inventory_pool, - user: user), - start_date: line.start_date, - end_date: line.end_date) + FactoryGirl.create( + :item_line, + status: :submitted, + inventory_pool: line.inventory_pool, + model: line.model, + user: user, + order: + FactoryGirl.build( + :order, state: :submitted, inventory_pool: line.inventory_pool, user: user + ), + start_date: line.start_date, + end_date: line.end_date + ) end end - expect(@current_user.reservations.unsubmitted.select{|line| not line.available?}.size).to eq n + expect(@current_user.reservations.unsubmitted.select { |line| nline.available? }.size).to eq n end -When(/^I perform some activity$/) do - visit borrow_root_path -end +When(/^I perform some activity$/) { visit borrow_root_path } Then(/^I am redirected to the timeout page$/) do expect(current_path).to eq borrow_order_timed_out_path @@ -84,28 +90,28 @@ ####################################################################### Then(/^the models in my order (are released|remain blocked)$/) do |arg1| - expect(@current_user.reservations.unsubmitted.all? { |line| - case arg1 - when 'are released' - not line.inventory_pool.running_reservations.detect { |l| l.id == line.id } - when 'remain blocked' - line.inventory_pool.running_reservations.detect { |l| l.id == line.id } - end - }).to be true + expect( + @current_user.reservations.unsubmitted.all? do |line| + case arg1 + when 'are released' + nline.inventory_pool.running_reservations.detect { |l| l.id == line.id } + when 'remain blocked' + line.inventory_pool.running_reservations.detect { |l| l.id == line.id } + end + end + ).to be true end ####################################################################### Given(/^all models are available$/) do - expect(@current_user.reservations.unsubmitted.all? {|line| line.available? }).to be true + expect(@current_user.reservations.unsubmitted.all?(&:available?)).to be true end -Then(/^I can continue my order process$/) do - expect(current_path).to eq borrow_root_path -end +Then(/^I can continue my order process$/) { expect(current_path).to eq borrow_root_path } When(/^a take back contains only options$/) do - @customer = @current_inventory_pool.users.detect {|u| u.visits.take_back.empty? } + @customer = @current_inventory_pool.users.detect { |u| u.visits.take_back.empty? } expect(@customer).not_to be_nil step 'I open a hand over for this customer' step 'I add an option to the hand over by providing an inventory code' @@ -120,19 +126,16 @@ expect(find('#status').has_content? _('Availability loaded')).to be true end -Given(/^the model "(.*)" has following partitioning in inventory pool "(.*)":$/) do |arg1, arg2, table| +Given( + /^the model "(.*)" has following partitioning in inventory pool "(.*)":$/ +) do |arg1, arg2, table| @model = Model.find_by_name arg1 @inventory_pool = InventoryPool.find_by_name arg2 table.hashes.each do |h| - group_id = if h['group'] == 'General' - nil - else - EntitlementGroup.find_by(name: h['group']).id - end - partitions = Entitlement.with_generals(model_ids: [@model.id], - inventory_pool_id: @inventory_pool.id).select do |partition| - partition.entitlement_group_id == group_id - end + group_id = h['group'] == 'General' ? nil : EntitlementGroup.find_by(name: h['group']).id + partitions = + Entitlement.with_generals(model_ids: [@model.id], inventory_pool_id: @inventory_pool.id) + .select { |partition| partition.entitlement_group_id == group_id } expect(partitions.count).to eq 1 expect(partitions.first.quantity).to eq h['quantity'].to_i end @@ -153,7 +156,12 @@ end Then(/^the maximum available quantity of this model for me is (\d+)$/) do |n| - m = @model.availability_in(@inventory_pool).maximum_available_in_period_summed_for_groups(Date.today+99.years, Date.today+99.years, @current_user.entitlement_groups.reload.map(&:id)) + m = + @model.availability_in(@inventory_pool).maximum_available_in_period_summed_for_groups( + Date.today + 99.years, + Date.today + 99.years, + @current_user.entitlement_groups.reload.map(&:id) + ) expect(m).to eq n.to_i end @@ -161,27 +169,60 @@ av = @model.availability_in(@inventory_pool.reload) # NOTE reload is to refresh the running_lines association date = av.changes.to_a.last.first quantity_in_general = av.entitlements[EntitlementGroup::GENERAL_GROUP_ID] - quantity_not_in_general = av.entitlements.values.sum - av.entitlements[EntitlementGroup::GENERAL_GROUP_ID] - - quantity_not_in_general.times.map { FactoryGirl.create :reservation, status: :approved, user: @current_user, inventory_pool: @inventory_pool, model: @model, start_date: date, end_date: date } + quantity_not_in_general = + av.entitlements.values.sum - av.entitlements[EntitlementGroup::GENERAL_GROUP_ID] + + quantity_not_in_general.times.map do + FactoryGirl.create :reservation, + status: :approved, + user: @current_user, + inventory_pool: @inventory_pool, + model: @model, + start_date: date, + end_date: date + end av = @model.availability_in(@inventory_pool.reload) # NOTE reload is to refresh the running_lines association - expect(av.changes[date][EntitlementGroup::GENERAL_GROUP_ID][:in_quantity]).to eq quantity_in_general - - FactoryGirl.create :reservation, status: :approved, user: @current_user, inventory_pool: @inventory_pool, model: @model, start_date: date, end_date: date + expect( + av.changes[date][EntitlementGroup::GENERAL_GROUP_ID][:in_quantity] + ).to eq quantity_in_general + + FactoryGirl.create :reservation, + status: :approved, + user: @current_user, + inventory_pool: @inventory_pool, + model: @model, + start_date: date, + end_date: date av = @model.availability_in(@inventory_pool.reload) # NOTE reload is to refresh the running_lines association - expect(av.changes[date][EntitlementGroup::GENERAL_GROUP_ID][:in_quantity]).to eq quantity_in_general - 1 + expect( + av.changes[date][EntitlementGroup::GENERAL_GROUP_ID][:in_quantity] + ).to eq quantity_in_general - 1 end When(/^I have (\d+) approved reservations for this model in this inventory pool$/) do |arg1| @date = Date.today + 1.year - @reservations = arg1.to_i.times.map { FactoryGirl.create :reservation, status: :approved, user: @current_user, inventory_pool: @inventory_pool, model: @model, start_date: @date, end_date: @date } + @reservations = + arg1.to_i.times.map do + FactoryGirl.create :reservation, + status: :approved, + user: @current_user, + inventory_pool: @inventory_pool, + model: @model, + start_date: @date, + end_date: @date + end @av = @model.availability_in(@inventory_pool.reload) # NOTE reload is to refresh the running_lines association end Then(/^(\d+) of these reservations (is|are) allocated to group "(.*?)"$/) do |arg1, arg2, arg3| - group_id = arg3 == "General" ? EntitlementGroup::GENERAL_GROUP_ID : EntitlementGroup.find_by_name(arg3).id + group_id = + arg3 == 'General' ? EntitlementGroup::GENERAL_GROUP_ID : EntitlementGroup.find_by_name(arg3).id expect(@av.changes[@date][group_id][:running_reservations].size).to eq arg1.to_i - expect(@av.changes[@date][group_id][:running_reservations].all? {|id| @reservations.map(&:id).include? id }).to be true + expect( + @av.changes[@date][group_id][:running_reservations].all? do |id| + @reservations.map(&:id).include? id + end + ).to be true end Then(/^all these reservations are available$/) do diff --git a/features/step_definitions/borrow/breadcrumb_navigation_steps.rb b/features/step_definitions/borrow/breadcrumb_navigation_steps.rb index 898110d64b..b6a0f0cee3 100644 --- a/features/step_definitions/borrow/breadcrumb_navigation_steps.rb +++ b/features/step_definitions/borrow/breadcrumb_navigation_steps.rb @@ -21,9 +21,7 @@ end When(/^I choose a subcategory$/) do - within('[data-category_id]', match: :first) do - find('.dropdown-holder').hover - end + within('[data-category_id]', match: :first) { find('.dropdown-holder').hover } @category_el = find('a.dropdown-item', match: :first) @category_name = @category_el.text @category = Category.find_by_name @category_name @@ -31,7 +29,9 @@ end Then(/^that category opens$/) do - expect((Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id']).to eq @category.id + expect( + (Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id'] + ).to eq @category.id end When(/^I pick a second-level category from the results of the explorative search$/) do @@ -52,9 +52,7 @@ expect(tabs.length).to eq 2 end -When(/^I open a model$/) do - find('.line[data-id]', match: :first).click -end +When(/^I open a model$/) { find('.line[data-id]', match: :first).click } Then(/^I see the whole path I traversed to get to the model$/) do #step 'die Kategorie ist das zweite und letzte Element der Brotkrumennavigation' @@ -71,12 +69,15 @@ end When(/^I am listing some available models$/) do - @category = Category.find do |c| - c.models.any? do |m| - m.availability_in(@current_user.inventory_pools.first) - .maximum_available_in_period_summed_for_groups( - Date.today, Date.today, @current_user.entitlement_group_ids) >= 1 + @category = + Category.find do |c| + c.models.any? do |m| + m.availability_in(@current_user.inventory_pools.first) + .maximum_available_in_period_summed_for_groups( + Date.today, Date.today, @current_user.entitlement_group_ids + ) >= + 1 + end end - end visit borrow_models_path(category_id: @category.id) end diff --git a/features/step_definitions/borrow/calendar2_steps.rb b/features/step_definitions/borrow/calendar2_steps.rb index cfb127fbcc..bc1d11f621 100644 --- a/features/step_definitions/borrow/calendar2_steps.rb +++ b/features/step_definitions/borrow/calendar2_steps.rb @@ -26,30 +26,31 @@ end end -When(/^I close the calendar$/) do - within '.modal' do - find('.modal-close').click - end -end +When(/^I close the calendar$/) { within '.modal' dofind('.modal-close').clickend } -Then(/^the dialog window closes$/) do - expect(has_no_selector?('#booking-calendar')).to be true -end +Then(/^the dialog window closes$/) { expect(has_no_selector?('#booking-calendar')).to be true } When(/^I try to add a model to the order that is not available$/) do start_date = Date.today end_date = Date.today + 14 @quantity = 3 - inventory_pool = @current_user.inventory_pools.detect do |ip| - @model = @current_user.models.borrowable.detect do |m| - m.availability_in(ip).maximum_available_in_period_summed_for_groups(start_date, end_date, @current_user.entitlement_group_ids) < @quantity and - m.total_borrowable_items_for_user_and_pool(@current_user, ip) >= @quantity + inventory_pool = + @current_user.inventory_pools.detect do |ip| + @model = + @current_user.models.borrowable.detect do |m| + m.availability_in(ip).maximum_available_in_period_summed_for_groups( + start_date, end_date, @current_user.entitlement_group_ids + ) < + @quantity and + m.total_borrowable_items_for_user_and_pool(@current_user, ip) >= @quantity + end end - end visit borrow_model_path(@model) find("[data-create-order-line][data-model-id='#{@model.id}']").click - step "I set the start date in the calendar to '%s'" % I18n.l(inventory_pool.next_open_date(start_date)) - step "I set the end date in the calendar to '%s'" % I18n.l(inventory_pool.next_open_date(end_date)) + step "I set the start date in the calendar to '%s'" % + I18n.l(inventory_pool.next_open_date(start_date)) + step "I set the end date in the calendar to '%s'" % + I18n.l(inventory_pool.next_open_date(end_date)) step "I set the quantity in the calendar to #{@quantity}" end @@ -76,7 +77,6 @@ expect(models.include? @model).to be false end - Then(/^the error lets me know that the chosen model is not available in that time range$/) do within '.modal' do find('#booking-calendar-errors', text: _('Item is not available in that time range')) @@ -84,9 +84,9 @@ end When(/^I add an item from the model list$/) do - visit borrow_models_path(category_id: Category.find {|c| !c.models.active.blank?}) + visit borrow_models_path(category_id: Category.find { |c| !c.models.active.blank? }) @model_name = find('.line .line-col.col3of6', match: :first).text - @model = Model.find {|m| [m.name, m.product].include? @model_name} + @model = Model.find { |m| [m.name, m.product].include? @model_name } find('.line .button', match: :first).click end @@ -107,9 +107,11 @@ When(/^everything I input into the calendar is valid$/) do within '.modal #booking-calendar-inventory-pool' do find('option', match: :first) - @inventory_pool = InventoryPool.find all('option').detect{|o| o.selected?}['data-id'] + @inventory_pool = InventoryPool.find all('option').detect(&:selected?)['data-id'] end - @quantity = 1 + @current_user.reservations.unsubmitted.select{|line| line.model == @model}.sum(&:quantity) + @quantity = + 1 + + @current_user.reservations.unsubmitted.select { |line| line.model == @model }.sum(&:quantity) #step "ich setze die Anzahl im Kalendar auf #{1}" step "I set the quantity in the calendar to #{1}" @@ -119,12 +121,18 @@ #step "the booking calendar is closed" end -Then(/^the model has been added to the order with the respective start and end date, quantity and inventory pool$/) do +Then( + / + ^the model has been added to the order with the respective start and end date, quantity and inventory pool$ + / +) do sleep 2 within '#current-order-lines' do find('.line', text: "#{@quantity}x #{@model.name}") end - expect(@current_user.reservations.unsubmitted.detect{|line| line.model == @model}).not_to be_nil + expect( + @current_user.reservations.unsubmitted.detect { |line| line.model == @model } + ).not_to be_nil end Then(/^the current start date is today$/) do @@ -140,21 +148,22 @@ end Then(/^the quantity is 1$/) do - within ".modal[role='dialog']" do - find("#booking-calendar-quantity[value='1']") - end + within ".modal[role='dialog']" dofind("#booking-calendar-quantity[value='1']")end end Then(/^all inventory pools are shown that have items of this model$/) do within '.modal #booking-calendar-inventory-pool' do - ips = @current_user.inventory_pools.select do |ip| - @model.total_borrowable_items_for_user_and_pool(@current_user, ip) - end + ips = + @current_user.inventory_pools.select do |ip| + @model.total_borrowable_items_for_user_and_pool(@current_user, ip) + end ips_in_dropdown = all('option').map(&:text) ips.each do |ip| - ips_in_dropdown.include?(ip.name + " (#{@model.total_borrowable_items_for_user_and_pool(@current_user, ip)})") + ips_in_dropdown.include?( + ip.name + " (#{@model.total_borrowable_items_for_user_and_pool(@current_user, ip)})" + ) end end end @@ -163,13 +172,13 @@ find('#start-date').click find('#start-date').set I18n.l(Date.today + 1) find('#end-date').click - find('#end-date').set I18n.l(Date.today + 2) - sleep 2 # needed because cider flappiness + find('#end-date').set I18n.l(Date.today + 2) # needed because cider flappiness + sleep 2 end When(/^I add an item to my order that is available in the selected time span$/) do @model_name = find('.line:not(.grayed-out) .line-col.col3of6', match: :first).text - @model = Model.find {|m| [m.name, m.product].include? @model_name} + @model = Model.find { |m| [m.name, m.product].include? @model_name } find('.line .button', match: :first).click end @@ -180,23 +189,22 @@ end Then(/^the end date is equal to the preselected end date$/) do - within '.modal' do - expect(find('#booking-calendar-end-date').value).to eq I18n.l(Date.today + 2) - end + within '.modal' doexpect(find('#booking-calendar-end-date').value).to eq I18n.l(Date.today + 2)end end Given(/^there is a model for which an order exists$/) do - @model = @current_user.inventory_pools.flat_map(&:reservations).select do |cl| - cl.is_a?(ItemLine) and cl.start_date > Date.today and cl.model.categories.exists? # NOTE cl.start_date.future? doesn't work properly because timezone - end.sample.model + @model = + @current_user.inventory_pools.flat_map(&:reservations).select do |cl| + cl.is_a?(ItemLine) and cl.start_date > Date.today and cl.model.categories.exists? # NOTE cl.start_date.future? doesn't work properly because timezone + end + .sample + .model end When(/^I add this model from the model list$/) do visit borrow_models_path(category_id: @model.categories.first) find('#model-list-search input').set @model.name - within('.line', match: :prefer_exact, text: @model.name) do - find('.button').click - end + within('.line', match: :prefer_exact, text: @model.name) { find('.button').click } end def get_selected_inventory_pool @@ -209,35 +217,40 @@ def get_selected_inventory_pool changes = av.available_total_quantities changes.each_with_index do |change, i| - current_calendar_date = Date.parse(find('.fc-day:not(.fc-other-month)', match: :first)['data-date']) + current_calendar_date = + Date.parse(find('.fc-day:not(.fc-other-month)', match: :first)['data-date']) current_change_date = change[0] - while current_calendar_date.month != current_change_date.month do + while current_calendar_date.month != current_change_date.month find('.fc-button-next').click - current_calendar_date = Date.parse(find('.fc-day:not(.fc-other-month)', match: :first)['data-date']) + current_calendar_date = + Date.parse(find('.fc-day:not(.fc-other-month)', match: :first)['data-date']) end # iterate days between this change and the next one - next_change = changes[i+1] + next_change = changes[i + 1] if next_change - days_between_changes = (next_change[0]-change[0]).to_i + days_between_changes = (next_change[0] - change[0]).to_i next_date = change[0] last_month = next_date.month days_between_changes.times do - if next_date.month != last_month - find('.fc-button-next').click - end + find('.fc-button-next').click if next_date.month != last_month last_month = next_date.month - change_date_el = find('.fc-widget-content:not(.fc-other-month) .fc-day-number', - match: :prefer_exact, - text: /#{next_date.day}/).first(:xpath, '../..') + change_date_el = + find( + '.fc-widget-content:not(.fc-other-month) .fc-day-number', + match: :prefer_exact, text: /#{next_date.day}/ + ) + .first(:xpath, '../..') next unless @current_inventory_pool.open_on? change_date_el[:"data-date"].to_date # check borrower availability - quantity_for_borrower = av.maximum_available_in_period_summed_for_groups(next_date, - next_date, - @current_user.entitlement_group_ids) + quantity_for_borrower = + av.maximum_available_in_period_summed_for_groups( + next_date, next_date, @current_user.entitlement_group_ids + ) + begin change_date_el.find('.fc-day-content', text: quantity_for_borrower) - rescue + rescue StandardError binding.pry end next_date += 1.day @@ -275,9 +288,7 @@ def get_selected_inventory_pool find(".fc-widget-content[data-date='#{end_date}']") end -When(/^I jump back and forth between months$/) do - find('.fc-button-next').click -end +When(/^I jump back and forth between months$/) { find('.fc-button-next').click } Then(/^the calendar shows the currently selected month$/) do find('.fc-header-title', text: I18n.l(Date.today.next_month, format: '%B %Y')) @@ -292,7 +303,7 @@ def get_selected_inventory_pool @holiday = @inventory_pool.holidays.first find('.fc-day-content', match: :first) holiday_not_found = all('.fc-day-content', text: @holiday.name).empty? - while holiday_not_found do + while holiday_not_found find('.fc-button-next').click find('.fc-day-content', match: :first) holiday_not_found = all('.fc-day-content', text: @holiday.name).empty? @@ -316,7 +327,10 @@ def get_selected_inventory_pool end Then(/^only those inventory pools are selectable that have capacities for the chosen model$/) do - @inventory_pools = @model.inventory_pools.reject {|ip| @model.total_borrowable_items_for_user_and_pool(@current_user, ip) <= 0 } + @inventory_pools = + @model.inventory_pools.reject do |ip| + @model.total_borrowable_items_for_user_and_pool(@current_user, ip) <= 0 + end within '.modal #booking-calendar-inventory-pool' do all('option').each do |option| expect(@inventory_pools.include?(InventoryPool.find(option['data-id']))).to be true @@ -336,7 +350,11 @@ def get_selected_inventory_pool within '.modal #booking-calendar-inventory-pool' do all('option').each do |option| inventory_pool = InventoryPool.find(option['data-id']) - expect(option.text[/#{@model.total_borrowable_items_for_user_and_pool(@current_user, inventory_pool)}/]).to be + expect( + option.text[ + /#{@model.total_borrowable_items_for_user_and_pool(@current_user, inventory_pool)}/ + ] + ).to be end end end @@ -345,7 +363,7 @@ def get_selected_inventory_pool max_quantity = nil within '.modal #booking-calendar-inventory-pool' do expect(has_selector?('option')).to be true - inventory_pool = InventoryPool.find(all('option').detect{|o| o.selected?}['data-id']) + inventory_pool = InventoryPool.find(all('option').detect(&:selected?)['data-id']) max_quantity = @model.total_borrowable_items_for_user_and_pool(@current_user, inventory_pool) end find('#booking-calendar-quantity').set (max_quantity + 1).to_s @@ -353,8 +371,7 @@ def get_selected_inventory_pool end Then(/^the booking calendar shows an error message$/) do - find('.modal #booking-calendar-errors', - text: _('Item is not available in that time range.')) + find('.modal #booking-calendar-errors', text: _('Item is not available in that time range.')) end Then(/^the add button is disabled$/) do @@ -368,22 +385,22 @@ def get_selected_inventory_pool Given(/^I reduce the selected inventory pools$/) do el = find('#ip-selector') - inventory_pool_ids = el.all('.dropdown-item[data-id]', visible: false).map{|i| i[:"data-id"]} + inventory_pool_ids = el.all('.dropdown-item[data-id]', visible: false).map { |i| i[:"data-id"] } el.click el.find("input[type='checkbox']", match: :first).click inventory_pool_ids.shift - @inventory_pools = inventory_pool_ids.map{|id| InventoryPool.find id} + @inventory_pools = inventory_pool_ids.map { |id| InventoryPool.find id } end -Given(/^I add a model to the order that is available across all the still remaining inventory pools$/) do - within "#model-list" do +Given( + /^I add a model to the order that is available across all the still remaining inventory pools$/ +) do + within '#model-list' do expect(has_selector?('.line[data-id]', visible: true)).to be true all('.line[data-id]').each do |line| next if line['data-id'].blank? model = Model.find line['data-id'] - if @inventory_pools.all?{|ip| ip.models.include?(model)} - @model = model - end + @model = model if @inventory_pools.all? { |ip| ip.models.include?(model) } end expect(@model).not_to be_nil find(:xpath, "(//*[@id='ip-selector']//input)[2]", visible: true).click @@ -400,10 +417,11 @@ def get_selected_inventory_pool end When(/^a model exists that is only available to a group$/) do - @model = Model.all.detect do |m| - partitions = Entitlement.with_generals(model_ids: [m.id]) - partitions.count > 1 and partitions.find{|p| p.entitlement_group_id == nil}.quantity == 0 - end + @model = + Model.all.detect do |m| + partitions = Entitlement.with_generals(model_ids: [m.id]) + partitions.count > 1 and partitions.find { |p| p.entitlement_group_id == nil }.quantity == 0 + end expect(@model.blank?).to be false @partition = @model.entitlements.first end @@ -448,9 +466,7 @@ def get_selected_inventory_pool end Then(/^I see the inventory pool selector$/) do - within '#ip-selector' do - expect(has_selector?('.dropdown', visible: false)).to be true - end + within '#ip-selector' doexpect(has_selector?('.dropdown', visible: false)).to be trueend end Then(/^I see filters for start and end date$/) do diff --git a/features/step_definitions/borrow/calendar_steps.rb b/features/step_definitions/borrow/calendar_steps.rb index 46dabf3cd9..c4df3136a7 100644 --- a/features/step_definitions/borrow/calendar_steps.rb +++ b/features/step_definitions/borrow/calendar_steps.rb @@ -1,38 +1,55 @@ When(/^I open the calendar of a model$/) do - model = @current_user.models.borrowable.where('models.id' => @inventory_pool.models.select('models.id')).first + model = + @current_user.models.borrowable.where('models.id' => @inventory_pool.models.select('models.id')) + .first visit borrow_model_path(model) find("[data-create-order-line][data-model-id='#{model.id}']").click end Given(/^the current inventory pool has reached maximum amount of visits$/) do if @current_inventory_pool.workday.reached_max_visits.empty? - # NOTE set max visits to 1 for all days - @current_inventory_pool.workday.update_attributes(max_visits: (0..6).inject({}) { |h, n| h[n] = 1; h }) + @current_inventory_pool.workday.update_attributes( + max_visits: (0..6).inject({}) { |h, n| h[n] = 1; h } + ) end + # NOTE set max visits to 1 for all days + expect(@current_inventory_pool.workday.reached_max_visits).not_to be_empty end -When(/^I open the calendar of a model related to an inventory pool for which has reached maximum amount of visits$/) do - @inventory_pool = @current_user.inventory_pools.detect { |ip| not ip.workday.reached_max_visits.empty? } - @inventory_pool ||= @current_user.inventory_pools.detect do |ip| - if ip.visits.where(is_approved: true).where('date >= ?', Date.today) +When( + / + ^I open the calendar of a model related to an inventory pool for which has reached maximum amount of visits$ + / +) do + @inventory_pool = + @current_user.inventory_pools.detect { |ip| nip.workday.reached_max_visits.empty? } + @inventory_pool ||= + @current_user.inventory_pools.detect do |ip| + if ip.visits.where(is_approved: true).where('date >= ?', Date.today) + ip.workday.update_attributes(max_visits: (0..6).inject({}) { |h, n| h[n] = 1; h }) + true + else + false + end # NOTE set max visits to 1 for all days - ip.workday.update_attributes(max_visits: (0..6).inject({}) { |h, n| h[n] = 1; h }) - true - else - false end - end step 'I open the calendar of a model' end -When(/^I open the calendar of a model related to an inventory pool for which the number of days between order submission and hand over is defined as (\d+)$/) do |arg1| - @inventory_pool = @current_user.inventory_pools.detect { |ip| ip.workday.reservation_advance_days == arg1.to_i } - @inventory_pool ||= begin - ip = @current_user.inventory_pools.first - ip.workday.update_attributes(reservation_advance_days: arg1.to_i) - ip - end +When( + / + ^I open the calendar of a model related to an inventory pool for which the number of days between order submission and hand over is defined as (\d+)$ + / +) do |arg1| + @inventory_pool = + @current_user.inventory_pools.detect { |ip| ip.workday.reservation_advance_days == arg1.to_i } + @inventory_pool ||= + begin + ip = @current_user.inventory_pools.first + ip.workday.update_attributes(reservation_advance_days: arg1.to_i) + ip + end step 'I open the calendar of a model' end @@ -45,32 +62,33 @@ end Then(/^(the|no) availability number is shown (.*)$/) do |arg1, arg2| - dates = case arg2 - when 'on this specific date' - (@current_inventory_pool || @inventory_pool).workday.reached_max_visits - when 'for today' - Date.today - when 'for tomorrow' - Date.tomorrow - when 'for the next open day after tomorrow' - (@current_inventory_pool || @inventory_pool).next_open_date(Date.tomorrow + 1.day) - else - raise - end + dates = + case arg2 + when 'on this specific date' + (@current_inventory_pool || @inventory_pool).workday.reached_max_visits + when 'for today' + Date.today + when 'for tomorrow' + Date.tomorrow + when 'for the next open day after tomorrow' + (@current_inventory_pool || @inventory_pool).next_open_date(Date.tomorrow + 1.day) + else + raise + end within '.modal' do Array(dates).each do |date| - while has_no_selector?(".fc-widget-content[data-date='#{date}']") do + while has_no_selector?(".fc-widget-content[data-date='#{date}']") find('.fc-button-next').click end within ".fc-widget-content[data-date='#{date}']" do text = find('.fc-day-content').text case arg1 - when 'the' - expect(text).not_to be_empty - when 'no' - expect(text).to be_empty - else - raise + when 'the' + expect(text).not_to be_empty + when 'no' + expect(text).to be_empty + else + raise end end end @@ -78,23 +96,22 @@ end When(/^I specify (.*) as (start|end) date$/) do |arg1, arg2| - @date = case arg1 - when 'today' - Date.today - when 'tomorrow' - Date.tomorrow - when 'this date' - (@current_inventory_pool || @inventory_pool).workday.reached_max_visits.sample - else - raise - end - step "I set the #{arg2} date in the calendar to '#{I18n::l(@date)}'" + @date = + case arg1 + when 'today' + Date.today + when 'tomorrow' + Date.tomorrow + when 'this date' + (@current_inventory_pool || @inventory_pool).workday.reached_max_visits.sample + else + raise + end + step "I set the #{arg2} date in the calendar to '#{I18n.l(@date)}'" end Then(/^I receive an error message within the modal$/) do - within '.modal #booking-calendar-errors' do - find('.red') - end + within '.modal #booking-calendar-errors' dofind('.red')end end Then /^the start or end date of that line is changed$/ do @@ -102,21 +119,24 @@ expect([@line.start_date, @line.end_date]).to include @date end -Then /^the (start|end) date in the booking calendar becomes red and I see a (closed|not possible|too early) day warning?$/ do |arg1, arg2| +Then / + ^the (start|end) date in the booking calendar becomes red and I see a (closed|not possible|too early) day warning?$ + / do |arg1, arg2| date = Date.parse find(".modal #booking-calendar-#{arg1}-date").value within '.modal' do el = find(".fc-widget-content[data-date='#{date}']").native.style('background-color') # NOTE our red definition is #FF4C4D == rgba(255, 76, 77, 1) expect(el).to eq 'rgba(255, 76, 77, 1)' - s = case arg2 - when 'closed' - _("Inventory pool is closed on #{arg1} date") - when 'not possible' - _("Booking is no longer possible on this #{arg1} date") - when 'too early' - _('No orders are possible on this start date') - end + s = + case arg2 + when 'closed' + _("Inventory pool is closed on #{arg1} date") + when 'not possible' + _("Booking is no longer possible on this #{arg1} date") + when 'too early' + _('No orders are possible on this start date') + end find('.red', text: s) end end diff --git a/features/step_definitions/borrow/explorative_search_steps.rb b/features/step_definitions/borrow/explorative_search_steps.rb index c185d39fbb..ec9fc6cc07 100644 --- a/features/step_definitions/borrow/explorative_search_steps.rb +++ b/features/step_definitions/borrow/explorative_search_steps.rb @@ -1,41 +1,56 @@ # -*- encoding : utf-8 -*- -Then(/^I see the explorative search$/) do - find '#explorative-search' -end +Then(/^I see the explorative search$/) { find '#explorative-search' } Then(/^it contains the currently selected category's direct children and their children$/) do - @children = @category.children.reject {|c| Model.from_category_and_all_its_descendants(@category).active.blank?} - @grand_children = @children.map(&:children).flatten.reject {|c| Model.from_category_and_all_its_descendants(c).active.blank?} + @children = + @category.children.reject do |c| + Model.from_category_and_all_its_descendants(@category).active.blank? + end + @grand_children = + @children.map(&:children).flatten.reject do |c| + Model.from_category_and_all_its_descendants(c).active.blank? + end within '#explorative-search' do - @children.map(&:name).each {|c_name| find('a', match: :first, text: c_name)} unless @children.blank? - @grand_children.map(&:name).each {|c_name| find('a', match: :first, text: c_name)} unless @grand_children.blank? + unless @children.blank? + @children.map(&:name).each { |c_name| find('a', match: :first, text: c_name) } + end + unless @grand_children.blank? + @grand_children.map(&:name).each { |c_name| find('a', match: :first, text: c_name) } + end end end Then(/^those categories and their children that do not contain any borrowable items are hidden$/) do - expect((@children + @grand_children).length).to eq find('#explorative-search', match: :first).all('a').length + expect((@children + @grand_children).length).to eq find('#explorative-search', match: :first).all( + 'a' + ) + .length end When(/^I choose a category$/) do - @category = @category.children.reject {|c| Model.from_category_and_all_its_descendants(@category).active.blank?}.first + @category = + @category.children.reject do |c| + Model.from_category_and_all_its_descendants(@category).active.blank? + end + .first find('#explorative-search', match: :first).find('a', match: :first, text: @category.name).click end Then(/^the models of the currently chosen category are shown$/) do - expect((Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id']).to eq @category.id + expect( + (Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id'] + ).to eq @category.id find('#model-list', match: :first) models = Model.from_category_and_all_its_descendants(@category).active within '#model-list' do - models.each do |model| - find('.line', match: :first, text: model.name) - end + models.each { |model| find('.line', match: :first, text: model.name) } end end Given(/^I am in the model list viewing a category without children$/) do - @category = Category.find {|c| c.descendants.blank?} + @category = Category.find { |c| c.descendants.blank? } visit borrow_models_path category_id: @category.id end diff --git a/features/step_definitions/borrow/language_selection_steps.rb b/features/step_definitions/borrow/language_selection_steps.rb index 34c1e51b48..8954a49b4d 100644 --- a/features/step_definitions/borrow/language_selection_steps.rb +++ b/features/step_definitions/borrow/language_selection_steps.rb @@ -1,13 +1,9 @@ # -*- encoding : utf-8 -*- -Given(/^I see the language list$/) do - find("footer a[href*='locale']", match: :first) -end +Given(/^I see the language list$/) { find("footer a[href*='locale']", match: :first) } When(/^I change the language to "(.*?)"$/) do |language| - do_and_wait_for_page_change do - find('footer a', text: language).click - end + do_and_wait_for_page_change { find('footer a', text: language).click } end Then(/^the language is "(.*?)"$/) do |language| diff --git a/features/step_definitions/borrow/model_overview_steps.rb b/features/step_definitions/borrow/model_overview_steps.rb index 25ceab5257..ae791153e4 100644 --- a/features/step_definitions/borrow/model_overview_steps.rb +++ b/features/step_definitions/borrow/model_overview_steps.rb @@ -1,13 +1,12 @@ # -*- encoding : utf-8 -*- Given(/^I am listing a category of models of which at least one is borrowable by me$/) do - @model = @current_user.models.borrowable.detect do |m| - m.images.size > 1 and - not m.description.blank? and - not m.attachments.blank? and - m.properties.length > 5 and - not m.compatibles.blank? - end + @model = + @current_user.models.borrowable.detect do |m| + m.images.size > 1 and nm.description.blank? and nm.attachments.blank? and + m.properties.length > 5 and + nm.compatibles.blank? + end category = @model.categories.first visit borrow_models_path(category_id: category.id) end @@ -16,42 +15,42 @@ find(".line[data-id='#{@model.id}']", match: :first).click end -Then(/^I see that model's detail page$/) do - expect(current_path).to eq borrow_model_path(@model) -end +Then(/^I see that model's detail page$/) { expect(current_path).to eq borrow_model_path(@model) } Then(/^I see the following model information:$/) do |table| table.raw.flatten.each do |section| case section - when 'Model name' - expect(has_content?(@model.name)).to be true - when 'Manufacturer' - expect(has_content?(@model.manufacturer)).to be true - when 'Images' - @model.images.each_with_index {|image,i| find("img[src='#{model_image_thumb_path(@model, offset: i)}']", match: :first)} - when 'Description' - expect(has_content?(@model.description)).to be true - when 'Attachments' - @model.attachments.each {|a| find("a[href='#{get_attachment_path(a.id)}']", match: :first)} - when 'Properties' - @model.properties.each do |p| - expect(has_content?(p.key)).to be true - expect(has_content?(p.value)).to be true - end - when 'Compatible models' - @model.compatibles.each do |c| - find("a[href='#{borrow_model_path(c)}']", match: :first) - find("img[src='#{model_image_thumb_path(c)}']", match: :first) - expect(has_content?(c.name)).to be true - end - else - rais 'unknown section' + when 'Model name' + expect(has_content?(@model.name)).to be true + when 'Manufacturer' + expect(has_content?(@model.manufacturer)).to be true + when 'Images' + @model.images.each_with_index do |image, i| + find("img[src='#{model_image_thumb_path(@model, offset: i)}']", match: :first) + end + when 'Description' + expect(has_content?(@model.description)).to be true + when 'Attachments' + @model.attachments.each { |a| find("a[href='#{get_attachment_path(a.id)}']", match: :first) } + when 'Properties' + @model.properties.each do |p| + expect(has_content?(p.key)).to be true + expect(has_content?(p.value)).to be true + end + when 'Compatible models' + @model.compatibles.each do |c| + find("a[href='#{borrow_model_path(c)}']", match: :first) + find("img[src='#{model_image_thumb_path(c)}']", match: :first) + expect(has_content?(c.name)).to be true + end + else + rais 'unknown section' end end end Given(/^I see a model's detail page that includes images of the model$/) do - @model = @current_user.models.borrowable.detect {|m| m.images.size > 1} + @model = @current_user.models.borrowable.detect { |m| m.images.size > 1 } visit borrow_model_path @model end @@ -60,7 +59,9 @@ end Then(/^that image becomes the main image$/) do - expect(find('#main-image', visible: false)['src'][model_image_path(@model, offset: 0)].blank?).to be false + expect( + find('#main-image', visible: false)['src'][model_image_path(@model, offset: 0)].blank? + ).to be false end When(/^I hover over another image$/) do @@ -68,20 +69,27 @@ end Then(/^that other image becomes the main image$/) do - expect(find('#main-image', visible: false)['src'][model_image_path(@model, offset: 1)].blank?).to be false + expect( + find('#main-image', visible: false)['src'][model_image_path(@model, offset: 1)].blank? + ).to be false end When(/^I click on an image$/) do - find("img[src='#{model_image_thumb_path(@model, offset: 1)}']", visible: false).find(:xpath, './..').click + find("img[src='#{model_image_thumb_path(@model, offset: 1)}']", visible: false).find( + :xpath, './..' + ) + .click end Then(/^that image remains the main image even when I'm not hovering over it$/) do step 'I release the focus from this field' - expect(find('#main-image', visible: false)['src'][model_image_path(@model, offset: 1)]).not_to be_nil + expect( + find('#main-image', visible: false)['src'][model_image_path(@model, offset: 1)] + ).not_to be_nil end Given(/^I see a model's detail page that includes properties$/) do - @model = @current_user.models.borrowable.detect {|m| m.properties.length > 5} + @model = @current_user.models.borrowable.detect { |m| m.properties.length > 5 } visit borrow_model_path @model end @@ -91,9 +99,7 @@ end end -Then(/^I toggle all properties$/) do - find('#properties-toggle', match: :first).click -end +Then(/^I toggle all properties$/) { find('#properties-toggle', match: :first).click } Then(/^all properties are displayed$/) do expect(find('#collapsed-properties', match: :first)['class']['collapsed'].nil?).to be true diff --git a/features/step_definitions/borrow/my_orders_overview_steps.rb b/features/step_definitions/borrow/my_orders_overview_steps.rb index 0a31ca597b..c5c44e3699 100644 --- a/features/step_definitions/borrow/my_orders_overview_steps.rb +++ b/features/step_definitions/borrow/my_orders_overview_steps.rb @@ -1,8 +1,6 @@ # -*- encoding : utf-8 -*- -Given(/^I have added items to an order$/) do - step 'I have an unsubmitted order with models' -end +Given(/^I have added items to an order$/) { step 'I have an unsubmitted order with models' } When(/^I open my list of orders$/) do visit borrow_current_order_path @@ -13,14 +11,13 @@ ############################################################################# Then(/^I see entries grouped by start date and inventory pool$/) do - @current_user.reservations.unsubmitted.group_by{|l| [l.start_date, l.inventory_pool]}.each do |k,v| - find('#current-order-lines .row', text: /#{I18n.l(k[0])}.*#{k[1].name}/) - end + @current_user.reservations.unsubmitted.group_by { |l| [l.start_date, l.inventory_pool] } + .each { |k, v| find('#current-order-lines .row', text: /#{I18n.l(k[0])}.*#{k[1].name}/) } end Then(/^the models are ordered alphabetically$/) do all('.emboss.deep').each do |x| - names = x.all('.line .name').map{|name| name.text} + names = x.all('.line .name').map(&:text) expect(names.sort == names).to be true end end @@ -28,24 +25,28 @@ Then(/^each entry has the following information$/) do |table| all('.line').each do |line| reservations = Reservation.find JSON.parse line['data-ids'] - table.raw.map{|e| e.first}.each do |row| + table.raw.map(&:first).each do |row| case row - when 'Image' - expect(line.find('img', match: :first)[:src][reservations.first.model.id.to_s]).to be - when 'Quantity' - expect(line.has_content?(reservations.sum(&:quantity))).to be true - when 'Model name' - expect(line.has_content?(reservations.first.model.name)).to be true - when 'Manufacturer' - expect(line.has_content?(reservations.first.model.manufacturer)).to be true - when 'Number of days' - expect(line.has_content?(((reservations.first.end_date - reservations.first.start_date).to_i+1).to_s)).to be true - when 'End date' - expect(line.has_content?(I18n.l reservations.first.end_date)).to be true - when 'the various actions' - line.find('.line-actions', match: :first) - else - raise 'Unknown' + when 'Image' + expect(line.find('img', match: :first)[:src][reservations.first.model.id.to_s]).to be + when 'Quantity' + expect(line.has_content?(reservations.sum(&:quantity))).to be true + when 'Model name' + expect(line.has_content?(reservations.first.model.name)).to be true + when 'Manufacturer' + expect(line.has_content?(reservations.first.model.manufacturer)).to be true + when 'Number of days' + expect( + line.has_content?( + ((reservations.first.end_date - reservations.first.start_date).to_i + 1).to_s + ) + ).to be true + when 'End date' + expect(line.has_content?(I18n.l reservations.first.end_date)).to be true + when 'the various actions' + line.find('.line-actions', match: :first) + else + raise 'Unknown' end end end @@ -57,7 +58,9 @@ def before_max_available(user) h = {} reservations = user.reservations.unsubmitted reservations.each do |order_line| - h[order_line.id] = order_line.model.availability_in(order_line.inventory_pool).maximum_available_in_period_summed_for_groups(order_line.start_date, order_line.end_date) + h[order_line.id] = + order_line.model.availability_in(order_line.inventory_pool) + .maximum_available_in_period_summed_for_groups(order_line.start_date, order_line.end_date) end h end @@ -97,7 +100,9 @@ def before_max_available(user) Then(/^the items are available for borrowing again$/) do @current_user.reservations.unsubmitted.each do |reservation| - after_max_available = reservation.model.availability_in(reservation.inventory_pool).maximum_available_in_period_summed_for_groups(reservation.start_date, reservation.end_date) + after_max_available = + reservation.model.availability_in(reservation.inventory_pool) + .maximum_available_in_period_summed_for_groups(reservation.start_date, reservation.end_date) expect(after_max_available).to eq @before_max_available[reservation.id] end end @@ -109,7 +114,7 @@ def before_max_available(user) ############################################################################# When(/^I enter a purpose$/) do - find("form textarea[name='purpose']", match: :first).set Faker::Lorem.sentences(2).join() + find("form textarea[name='purpose']", match: :first).set Faker::Lorem.sentences(2).join end When(/^I submit the order$/) do @@ -118,18 +123,17 @@ def before_max_available(user) end Then(/^the reservations' status changes to submitted$/) do - @reservations.reload.each do |r| - expect(r.status).to be == :submitted - end + @reservations.reload.each { |r| expect(r.status).to be == :submitted } expect(@current_user.reservations.unsubmitted).to be_empty end -Then(/^I see an order confirmation$/) do - find('.notice', match: :first) -end +Then(/^I see an order confirmation$/) { find('.notice', match: :first) } Then(/^the order confirmation lets me know that my order will be handled soon$/) do - find('.notice', match: :first, text: _('Your order has been successfully submitted, but is NOT YET APPROVED.')) + find( + '.notice', + match: :first, text: _('Your order has been successfully submitted, but is NOT YET APPROVED.') + ) end ############################################################################# @@ -153,21 +157,21 @@ def before_max_available(user) if @just_changed_line @just_changed_line.click else - # try to get reservations where quantity is still increasable - line_to_edit = all('[data-change-order-lines]').detect do |line| - reservations = Reservation.find JSON.parse line['data-ids'] - if reservations.first.maximum_available_quantity > 0 - @changed_lines = reservations + line_to_edit = + all('[data-change-order-lines]').detect do |line| + reservations = Reservation.find JSON.parse line['data-ids'] + @changed_lines = reservations if reservations.first.maximum_available_quantity > 0 end - end if line_to_edit line_to_edit.click else - @changed_lines = Reservation.find JSON.parse find('[data-change-order-lines]', match: :first)['data-ids'] + @changed_lines = + Reservation.find JSON.parse find('[data-change-order-lines]', match: :first)['data-ids'] find('[data-change-order-lines]', match: :first).click end end + # try to get reservations where quantity is still increasable end #Then(/^the calendar opens$/) do @@ -182,7 +186,7 @@ def before_max_available(user) current_scope.set(I18n.l(start_date)) current_scope.native.send_keys(:return) end - while current_scope.has_selector?('#booking-calendar-errors') do + while current_scope.has_selector?('#booking-calendar-errors') start_date += 1.day within('#booking-calendar-start-date') do current_scope.set(I18n.l(start_date)) @@ -195,7 +199,7 @@ def before_max_available(user) current_scope.set(I18n.l(end_date)) current_scope.native.send_keys(:return) end - while current_scope.has_selector?('#booking-calendar-errors') do + while current_scope.has_selector?('#booking-calendar-errors') end_date += 1.day within('#booking-calendar-end-date') do current_scope.set(I18n.l(end_date)) @@ -206,26 +210,30 @@ def before_max_available(user) end Then(/^the entry's date is changed accordingly$/) do - within('.line', match: :first) do - find('[data-change-order-lines]').click - end + within('.line', match: :first) { find('[data-change-order-lines]').click } within '.modal' do find('#booking-calendar .fc-widget-content', match: :first) find('.modal-close').click end - if @new_date - expect(@changed_lines.first.reload.start_date).to eq @new_date - end + expect(@changed_lines.first.reload.start_date).to eq @new_date if @new_date if @new_quantity line = @changed_lines.first - t = line.user.reservations.where(inventory_pool_id: line.inventory_pool_id, - status: line.status, - model_id: line.model_id, - start_date: line.start_date, - end_date: line.end_date).sum(:quantity) + t = + line.user.reservations.where( + inventory_pool_id: line.inventory_pool_id, + status: line.status, + model_id: line.model_id, + start_date: line.start_date, + end_date: line.end_date + ) + .sum(:quantity) expect(t).to eq @new_quantity - @just_changed_line = find("[data-model-id='#{line.model_id}'][data-start-date='#{line.start_date}'][data-end-date='#{line.end_date}']") + @just_changed_line = + find( + "[data-model-id='#{line.model_id}'][data-start-date='#{line + .start_date}'][data-end-date='#{line.end_date}']" + ) end end @@ -233,7 +241,9 @@ def before_max_available(user) step 'I see entries grouped by start date and inventory pool' end - Then(/^I see the timer formatted as "(.*?)"$/) do |format| - find('#timeout-countdown-time', match: :first, text: Regexp.new(format.gsub('mm', '\\d+').gsub('ss', '\\d+'))) + find( + '#timeout-countdown-time', + match: :first, text: Regexp.new(format.gsub('mm', 'undefinedd+').gsub('ss', 'undefinedd+')) + ) end diff --git a/features/step_definitions/borrow/navigation_steps.rb b/features/step_definitions/borrow/navigation_steps.rb index 2122f1f5fb..c1756a3f5f 100644 --- a/features/step_definitions/borrow/navigation_steps.rb +++ b/features/step_definitions/borrow/navigation_steps.rb @@ -1,36 +1,38 @@ # -*- encoding : utf-8 -*- -Then(/^I can see the navigation bars$/) do - find('nav', match: :first) -end +Then(/^I can see the navigation bars$/) { find('nav', match: :first) } Then(/^the navigation contains "(.*?)"$/) do |section| within 'nav.topbar' do case section - when 'To pick up' - find("a[href='#{borrow_to_pick_up_path}']") if @current_user.reservations.approved.to_a.sum(&:quantity) > 0 - when 'To return' - find("a[href='#{borrow_returns_path}']") if @current_user.reservations.signed.to_a.sum(&:quantity) > 0 - when 'Orders' - find("a[href='#{borrow_orders_path}']") if @current_user.reservations.submitted.exists? - when 'Inventory pools' - find("a[href='#{borrow_inventory_pools_path}']", text: _('Inventory Pools')) - when 'User' - find(".topbar-item", text: @current_user.short_name) - when 'Log out' - find('.topbar-navigation.float-right .topbar-item', text: @current_user.short_name).hover - find(".topbar form[action='/sign-out'] button") - when 'Manage' - find('.topbar-navigation.float-right .topbar-item', match: :first).hover - @current_user.inventory_pools.managed.each do |ip| - find(".topbar-navigation.float-right a[href='#{manage_daily_view_path(ip)}']", text: ip) - end - when 'Lending' - find("a[href='#{manage_daily_view_path(@current_inventory_pool)}']", text: _('Lending')) - when 'Borrow' - find("a[href='#{borrow_root_path}']", text: _('Borrow')) - else - raise + when 'To pick up' + if @current_user.reservations.approved.to_a.sum(&:quantity) > 0 + find("a[href='#{borrow_to_pick_up_path}']") + end + when 'To return' + if @current_user.reservations.signed.to_a.sum(&:quantity) > 0 + find("a[href='#{borrow_returns_path}']") + end + when 'Orders' + find("a[href='#{borrow_orders_path}']") if @current_user.reservations.submitted.exists? + when 'Inventory pools' + find("a[href='#{borrow_inventory_pools_path}']", text: _('Inventory Pools')) + when 'User' + find('.topbar-item', text: @current_user.short_name) + when 'Log out' + find('.topbar-navigation.float-right .topbar-item', text: @current_user.short_name).hover + find(".topbar form[action='/sign-out'] button") + when 'Manage' + find('.topbar-navigation.float-right .topbar-item', match: :first).hover + @current_user.inventory_pools.managed.each do |ip| + find(".topbar-navigation.float-right a[href='#{manage_daily_view_path(ip)}']", text: ip) + end + when 'Lending' + find("a[href='#{manage_daily_view_path(@current_inventory_pool)}']", text: _('Lending')) + when 'Borrow' + find("a[href='#{borrow_root_path}']", text: _('Borrow')) + else + raise end end end @@ -39,45 +41,41 @@ find("nav a[href='#{borrow_root_path}']", match: :first) end -When(/^I use the home button$/) do - find("nav a[href='#{borrow_root_path}']", match: :first).click -end +When(/^I use the home button$/) { find("nav a[href='#{borrow_root_path}']", match: :first).click } -When(/^I visit the lending section$/) do - visit manage_daily_view_path(@current_inventory_pool) -end +When(/^I visit the lending section$/) { visit manage_daily_view_path(@current_inventory_pool) } When(/^I visit the lending section on the list of (all|open|closed) contracts$/) do |arg1| visit manage_contracts_path(@current_inventory_pool, status: [:signed, :closed]) - step %Q(I can view "#{arg1}" contracts) + step "I can view \"#{arg1}\" contracts" find('#contracts.list-of-lines .line', match: :first) end Then(/^I see at least (an order|a contract)$/) do |arg1| case arg1 - when 'an order' - find('#orders.list-of-lines .line', match: :first) - when 'a contract' - find('#contracts.list-of-lines .line', match: :first) - else - raise + when 'an order' + find('#orders.list-of-lines .line', match: :first) + when 'a contract' + find('#contracts.list-of-lines .line', match: :first) + else + raise end end - When(/^I open the tab "(Orders|Contracts)"$/) do |arg1| within('#contracts-index-view > .row:nth-child(1) > nav:nth-child(1) ul') do find('li a', text: _(arg1)).click end - s1 = case arg1 - when 'Orders' - _('List of Orders') - when 'Contracts' - _('List of Contracts') - else - raise - end + s1 = + case arg1 + when 'Orders' + _('List of Orders') + when 'Contracts' + _('List of Contracts') + else + raise + end within('#contracts-index-view') do find('.headline-xl', text: s1) @@ -86,25 +84,19 @@ end Then(/^I see the tabs:$/) do |table| - table.raw.flatten do |tab| - find('#list-tabs a.inline-tab-item', text: tab) - end + table.raw.flatten { |tab| find('#list-tabs a.inline-tab-item', text: tab) } end Then(/^the checkbox "(.*?)" is already checked and I can uncheck$/) do |arg1| case arg1 - when 'To be verified' - find("input[type='checkbox'][name='to_be_verified']:checked").click - within('#contracts-index-view') do - find('#contracts') - end - when 'No verification required' - find("input[type='checkbox'][name='no_verification_required']:checked").click - within('#contracts-index-view') do - find('#contracts') - end - else - raise + when 'To be verified' + find("input[type='checkbox'][name='to_be_verified']:checked").click + within('#contracts-index-view') { find('#contracts') } + when 'No verification required' + find("input[type='checkbox'][name='no_verification_required']:checked").click + within('#contracts-index-view') { find('#contracts') } + else + raise end end diff --git a/features/step_definitions/borrow/order_window_steps.rb b/features/step_definitions/borrow/order_window_steps.rb index a6e77ccc6f..4c642acbee 100644 --- a/features/step_definitions/borrow/order_window_steps.rb +++ b/features/step_definitions/borrow/order_window_steps.rb @@ -1,19 +1,15 @@ # -*- encoding : utf-8 -*- -When(/^I am viewing my current order$/) do - visit borrow_current_order_path -end +When(/^I am viewing my current order$/) { visit borrow_current_order_path } Then(/^I am redirected to my current order$/) do expect(current_path).to eq borrow_current_order_path end - Then(/^I do not see the order window$/) do expect(has_no_selector?('.col1of5 .navigation-tab-item', text: _('Order'))).to be true end - Then(/^I see the order window$/) do expect(has_selector?('.col1of5 .navigation-tab-item', text: _('Order'))).to be true end @@ -25,21 +21,21 @@ Then(/^the models in the order window are sorted alphabetically$/) do within '#current-order-basket #current-order-lines' do - @names = all('.line').map{|l| l[:title] } + @names = all('.line').map { |l| l[:title] } expect(@names.sort == @names).to be true end end -Then(/^identical models are collapsed$/) do - expect(@names.uniq == @names).to be true -end +Then(/^identical models are collapsed$/) { expect(@names.uniq == @names).to be true } When(/^I add the same model one more time$/) do - FactoryGirl.create(:reservation, - user: @current_user, - status: :unsubmitted, - inventory_pool: @inventory_pool, - model: @new_reservation.model) + FactoryGirl.create( + :reservation, + user: @current_user, + status: :unsubmitted, + inventory_pool: @inventory_pool, + model: @new_reservation.model + ) #step "erscheint es im Bestellfensterchen" step 'it appears in the order window' end @@ -73,7 +69,10 @@ step 'the model has been added to the order with the respective start and end date, quantity and inventory pool' #step "erscheint es im Bestellfensterchen" step 'it appears in the order window' - find("#current-order-basket #current-order-lines .line[title='#{@model.name}']", match: :first, text: "#{@quantity}x #{@model.name}") + find( + "#current-order-basket #current-order-lines .line[title='#{@model.name}']", + match: :first, text: "#{@quantity}x #{@model.name}" + ) end Given(/^my order is empty$/) do @@ -90,16 +89,20 @@ Then(/^I see a timer$/) do step 'I visit the homepage' expect(has_selector?('#current-order-basket #timeout-countdown', visible: true)).to be true - @timeoutStart = if @current_user.reservations.unsubmitted.empty? - Time.now - else - @current_user.reservations.unsubmitted.first.updated_at - end + @timeoutStart = + if @current_user.reservations.unsubmitted.empty? + Time.now + else + @current_user.reservations.unsubmitted.first.updated_at + end @countdown = find('#timeout-countdown-time', match: :first).text end Then(/^the timer is near the basket$/) do - find('#current-order-basket .navigation-tab-item #timeout-countdown #timeout-countdown-time', match: :first) + find( + '#current-order-basket .navigation-tab-item #timeout-countdown #timeout-countdown-time', + match: :first + ) end Then(/^the timer counts down from (\d+) minutes$/) do |timeout_minutes| @@ -108,7 +111,8 @@ seconds = @countdown.split(':')[1].to_i sleep(1) # NOTE this sleep is required in order to test the countdown expect(Setting.first.timeout_minutes - 1).to be <= minutes - expect(find('#timeout-countdown-time', match: :first).reload.text.split(':')[1].to_i).to be < seconds + expect(find('#timeout-countdown-time', match: :first).reload.text.split(':')[1].to_i).to be < + seconds end Given(/^my order is not empty$/) do @@ -132,6 +136,4 @@ expect(Setting.first.timeout_minutes).to eq arg1.to_i end -When(/^the timer has run down$/) do - sleep(Setting.first.timeout_minutes * 60 + 1) # NOTE this sleep is required to test the timeout -end +When(/^the timer has run down$/) { sleep(Setting.first.timeout_minutes * 60 + 1) } # NOTE this sleep is required to test the timeout diff --git a/features/step_definitions/borrow/orders_steps.rb b/features/step_definitions/borrow/orders_steps.rb index 482f10e78c..e0d1a971f7 100644 --- a/features/step_definitions/borrow/orders_steps.rb +++ b/features/step_definitions/borrow/orders_steps.rb @@ -1,12 +1,17 @@ # -*- encoding : utf-8 -*- Then(/^I see the number of submitted, unapproved orders on every page$/) do - [borrow_root_path, - borrow_inventory_pools_path, - borrow_current_order_path, - borrow_current_user_path].each do |path| + [ + borrow_root_path, + borrow_inventory_pools_path, + borrow_current_order_path, + borrow_current_user_path + ] + .each do |path| visit path - expect(find("nav a[href='#{borrow_orders_path}'] .badge", match: :first).text.to_i).to eq @current_user.orders.submitted.to_a.size # NOTE count returns a Hash because the group() in default scope + expect( + find("nav a[href='#{borrow_orders_path}'] .badge", match: :first).text.to_i + ).to eq @current_user.orders.submitted.to_a.size # NOTE count returns a Hash because the group() in default scope end end @@ -22,11 +27,16 @@ end Then(/^I see the information that the order has not yet been approved$/) do - expect(has_content?(_('These orders have been successfully submitted, but are NOT YET APPROVED.'))).to be true + expect( + has_content?(_('These orders have been successfully submitted, but are NOT YET APPROVED.')) + ).to be true end Then(/^the orders are sorted by date and inventory pool$/) do - titles = all('.row.padding-inset-l').map {|x| [Date.parse(x.find('h3', match: :first).text), x.find('h2', match: :first).text]} + titles = + all('.row.padding-inset-l').map do |x| + [Date.parse(x.find('h3', match: :first).text), x.find('h2', match: :first).text] + end expect(titles.empty?).to be false expect(titles.sort == titles).to be true end @@ -39,8 +49,7 @@ Then(/^the items in the order are sorted alphabetically and by model name$/) do all('.separated-top').each do |block| - names = block.all('.line').map {|x| x.text.split("\n")[1]} + names = block.all('.line').map { |x| x.text.split('undefined')[1] } expect(names.sort == names).to be true end end - diff --git a/features/step_definitions/borrow/pickups_returns_steps.rb b/features/step_definitions/borrow/pickups_returns_steps.rb index 61dfc5b64e..55632fa8be 100644 --- a/features/step_definitions/borrow/pickups_returns_steps.rb +++ b/features/step_definitions/borrow/pickups_returns_steps.rb @@ -1,45 +1,52 @@ # -*- encoding : utf-8 -*- Then(/^I see the number of "(.*?)" on each page$/) do |visit_type| - link = case visit_type - when "Returns" - "returns" - when "Pick ups" - "to_pick_up" - end + link = + case visit_type + when 'Returns' + 'returns' + when 'Pick ups' + 'to_pick_up' + end - text = case visit_type - when 'Returns' - @current_user.visits.take_back - when 'Pick ups' - @current_user.visits.hand_over - end.to_a.size.to_s + text = + case visit_type + when 'Returns' + @current_user.visits.take_back + when 'Pick ups' + @current_user.visits.hand_over + end + .to_a + .size + .to_s find("a[href*='borrow/#{link}'] > span", match: :first, text: text) end -Given(/^I am in the borrow section$/) do - visit borrow_root_path -end - +Given(/^I am in the borrow section$/) { visit borrow_root_path } Then(/^I don't see the "(.*?)" button$/) do |visit_type| - s = case visit_type - when 'Returns' - 'returns' - when 'Pick ups' - 'to_pick_up' - end + s = + case visit_type + when 'Returns' + 'returns' + when 'Pick ups' + 'to_pick_up' + end expect(has_no_selector?("a[href*='borrow/#{s}']")).to be true end When(/^I press the "(.*?)" link$/) do |visit_type| - find("a[href*='borrow/#{case visit_type - when "Returns" - "returns" - when "Pick ups" - "to_pick_up" - end}']", match: :first).click + find( + "a[href*='borrow/#{case visit_type + when 'Returns' + 'returns' + when 'Pick ups' + 'to_pick_up' + end}']", + match: :first + ) + .click end Then(/^I see my "(.*?)"$/) do |visit_type| @@ -48,7 +55,8 @@ @current_user.visits.take_back when 'Pick ups' @current_user.visits.hand_over - end.each do |visit| + end + .each do |visit| expect(has_selector?('.row h3', text: I18n.l(visit.date).to_s)).to be true expect(has_selector?('.row h2', text: visit.inventory_pool.name)).to be true end @@ -56,11 +64,14 @@ Then(/^the "(.*?)" are sorted by date and inventory pool$/) do |visit_type| expect(all('.row h3').map(&:text)).to eq case visit_type - when 'Returns' - @current_user.visits.take_back - when 'Pick ups' - @current_user.visits.hand_over - end.order(:date).map(&:date).map {|d| I18n.l d} + when 'Returns' + @current_user.visits.take_back + when 'Pick ups' + @current_user.visits.hand_over + end + .order(:date) + .map(&:date) + .map { |d| I18n.l d } end Then(/^each of the "(.*?)" shows items to (?:.+)$/) do |visit_type| @@ -69,7 +80,8 @@ @current_user.visits.take_back when 'Pick ups' @current_user.visits.hand_over - end.each do |visit| + end + .each do |visit| visit.reservations.each do |line| expect(has_selector?('.row.line', text: line.model.name)).to be true end @@ -77,56 +89,55 @@ end Then(/^the items are sorted alphabetically and grouped by model name and number of items$/) do + temp = + if current_path == borrow_returns_path + @current_user.visits.joins(:inventory_pool).take_back + elsif current_path == borrow_to_pick_up_path + @current_user.visits.hand_over.joins(:inventory_pool) + end + .order('date', 'inventory_pools.name') + .map(&:reservations) - temp = if current_path == borrow_returns_path - @current_user.visits.joins(:inventory_pool).take_back - elsif current_path == borrow_to_pick_up_path - @current_user.visits.hand_over.joins(:inventory_pool) - end.order('date', 'inventory_pools.name').map(&:reservations) - - t = temp.map{|reservations| reservations.map(&:model).uniq.map(&:name).sort }.flatten + t = temp.map { |reservations| reservations.map(&:model).uniq.map(&:name).sort }.flatten expect(t).to eq all('.row.line .col6of10').map(&:text) - temp. - map{|reservations| reservations.group_by {|l| l.model.name}}. - map {|h| h.sort}. - flatten(1). - map{|vl| [vl.first, (if vl.second.first.is_a? OptionLine then vl.second.first.quantity else vl.second.length end)]}. - each do |element| - expect(has_selector?('.row.line', text: /#{element.second}[\sx]*#{element.first}/)).to be true - end + temp.map { |reservations| reservations.group_by { |l| l.model.name } }.map(&:sort).flatten(1) + .map do |vl| + [vl.first, (vl.second.first.is_a? OptionLine ? vl.second.first.quantity : vl.second.length)] + end + .each do |element| + expect(has_selector?('.row.line', text: /#{element.second}[\sx]*#{element.first}/)).to be true + end end - Then(/^the items are sorted alphabetically by model name$/) do - t = @current_user.visits.joins(:inventory_pool).take_back.order('date', 'inventory_pools.name'). - map(&:reservations).map{|reservations| reservations.map(&:model)}. - map{|visit_models| visit_models.map(&:name)}. - map{|visit_model_names| visit_model_names.sort}.flatten + t = + @current_user.visits.joins(:inventory_pool).take_back.order('date', 'inventory_pools.name').map( + &:reservations + ) + .map { |reservations| reservations.map(&:model) } + .map { |visit_models| visit_models.map(&:name) } + .map(&:sort) + .flatten expect(t).to eq all('.row.line .col5of10').map(&:text) end Then(/^each line shows the proper quantity$/) do - qs = \ - @current_user - .visits - .joins(:inventory_pool) - .take_back - .order('date', 'inventory_pools.name') - .map(&:reservations) - .map { |rs| rs.sort_by { |r| r.model.name } } - .flatten - .map(&:quantity) - .map { |q| "#{q} x" } + qs = + @current_user.visits.joins(:inventory_pool).take_back.order('date', 'inventory_pools.name').map( + &:reservations + ) + .map { |rs| rs.sort_by { |r| r.model.name } } + .flatten + .map(&:quantity) + .map { |q| "#{q} x" } expect(qs).to eq all('.row.line .col1of10').map(&:text) end Then(/^I have to return some options$/) do c = @current_user.contracts.open.first - FactoryGirl.create(:option_line, - status: :signed, - inventory_pool: c.inventory_pool, - quantity: 5, - user: @current_user, - contract: c) + FactoryGirl.create( + :option_line, + status: :signed, inventory_pool: c.inventory_pool, quantity: 5, user: @current_user, contract: c + ) end diff --git a/features/step_definitions/borrow/search_steps.rb b/features/step_definitions/borrow/search_steps.rb index 1da2f41876..a38a6922be 100644 --- a/features/step_definitions/borrow/search_steps.rb +++ b/features/step_definitions/borrow/search_steps.rb @@ -10,10 +10,10 @@ within '.ui-autocomplete' do matches = all('.ui-autocomplete a', minimum: 1) expect(matches.length).to be >= 6 - matches[0,6].each do |match| + matches[0, 6].each do |match| within match do text = find('strong', text: @search_term).text - model = @current_user.models.borrowable.find {|m| [m.name, m.product].include? text } + model = @current_user.models.borrowable.find { |m| [m.name, m.product].include? text } find('div > div:nth-child(2)', text: model.manufacturer) find("div > img[src='/models/#{model.id}/image_thumb']") end @@ -29,16 +29,20 @@ Given(/^I pick a model from the ones suggested$/) do #step 'man einen Suchbegriff eingibt' step 'I enter a search term' - @model = @current_user.models.find {|m| [m.name, m.product].include? find('.ui-autocomplete a strong', match: :first).text } + @model = + @current_user.models.find do |m| + [m.name, m.product].include? find('.ui-autocomplete a strong', match: :first).text + end find('.ui-autocomplete a', match: :first, text: @model.name).click end -Then(/^I see the model's detail page$/) do - expect(current_path).to eq borrow_model_path(@model) -end +Then(/^I see the model's detail page$/) { expect(current_path).to eq borrow_model_path(@model) } Given(/^I enter a search term$/) do - @model ||= @current_user.models.borrowable.detect {|m| @current_user.models.borrowable.where("models.product LIKE '%#{m.name[0..3]}%'").length >= 6} + @model ||= + @current_user.models.borrowable.detect do |m| + @current_user.models.borrowable.where("models.product LIKE '%#{m.name[0..3]}%'").length >= 6 + end @search_term = @model.name[0..3] fill_in 'search_term', with: @search_term end @@ -55,12 +59,15 @@ end Then(/^the search result page is shown$/) do - find("nav .navigation-tab-item.active span[title=\"%s\"]" % _("Search for '%s'") % @search_term) + find('nav .navigation-tab-item.active span[title="%s"]' % _("Search for '%s'") % @search_term) expect(current_path).to eq borrow_search_results_path end Then(/^I see image, name and manufacturer of all matching models$/) do - @models = @current_user.models.borrowable.search(@search_term, [:manufacturer, :product, :version]).default_order.paginate(page: 1, per_page: 20) + @models = + @current_user.models.borrowable.search(@search_term, [:manufacturer, :product, :version]) + .default_order + .paginate(page: 1, per_page: 20) @models.each do |model| within "#model-list .line[data-id='#{model.id}']" do find('div .col1of6', text: model.manufacturer, match: :prefer_exact) diff --git a/features/step_definitions/borrow/start_page_steps.rb b/features/step_definitions/borrow/start_page_steps.rb index c56814a7be..49e334b3c2 100644 --- a/features/step_definitions/borrow/start_page_steps.rb +++ b/features/step_definitions/borrow/start_page_steps.rb @@ -1,15 +1,11 @@ # -*- encoding : utf-8 -*- -Given(/^I am listing the main categories$/) do - visit borrow_root_path -end +Given(/^I am listing the main categories$/) { visit borrow_root_path } -Then(/^I stay on listing the main categories$/) do - expect(page.current_path).to eq borrow_root_path -end +Then(/^I stay on listing the main categories$/) { expect(page.current_path).to eq borrow_root_path } Then(/^I see exactly those main categories that are useful for my user$/) do - @main_categories = @current_user.all_categories.select {|c| c.parents.empty?} + @main_categories = @current_user.all_categories.select { |c| c.parents.empty? } categories_counter = 0 @main_categories.each do |mc| find('a', match: :first, text: mc.name) @@ -24,23 +20,25 @@ end When(/^I hover over a main category with children$/) do - @main_category = (@current_user.all_categories & Category.roots).find do |c| - borrowable_children = (@current_user.categories.with_borrowable_items & c.children) - c.children.size != borrowable_children.size and borrowable_children.size > 0 - end - within('[data-category_id]', text: @main_category.name) do - find('.dropdown-holder').hover - end + @main_category = + (@current_user.all_categories & Category.roots).find do |c| + borrowable_children = (@current_user.categories.with_borrowable_items & c.children) + c.children.size != borrowable_children.size and borrowable_children.size > 0 + end + within('[data-category_id]', text: @main_category.name) { find('.dropdown-holder').hover } end Then(/^I see only this main category's children that are useful and available to me$/) do second_level_categories = @main_category.children - visible_2nd_level_categories = (@current_user.categories.with_borrowable_items & @main_category.children) + visible_2nd_level_categories = + (@current_user.categories.with_borrowable_items & @main_category.children) @second_level_category = visible_2nd_level_categories.first find('a', match: :first, text: @second_level_category.name) visible_2nd_level_categories_count = 0 - within find('[data-category_id] .padding-inset-s', match: :first, text: @main_category.name).first(:xpath, '../..').find('.dropdown-holder', match: :first) do + within find('[data-category_id] .padding-inset-s', match: :first, text: @main_category.name) + .first(:xpath, '../..') + .find('.dropdown-holder', match: :first) do visible_2nd_level_categories.each do |c| find('.dropdown a', match: :first, text: c.name) visible_2nd_level_categories_count += 1 @@ -49,16 +47,18 @@ expect(visible_2nd_level_categories_count).to eq visible_2nd_level_categories.size end -When(/^I choose one of these child categories$/) do - click_link @second_level_category.name -end +When(/^I choose one of these child categories$/) { click_link @second_level_category.name } Then(/^I see the model list for this main category$/) do - expect((Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id']).to eq @main_category.id + expect( + (Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id'] + ).to eq @main_category.id end Then(/^I see the model list for this category$/) do - expect((Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id']).to eq @second_level_category.id + expect( + (Rack::Utils.parse_nested_query URI.parse(current_url).query)['category_id'] + ).to eq @second_level_category.id end When(/^I click on the first category dropdown$/) do @@ -77,22 +77,29 @@ end Given(/^there is a main category whose child categories cannot offer me any items$/) do - @main_category = (@current_user.all_categories & Category.roots).find do |c| - (@current_user.categories.with_borrowable_items & c.children).size == 0 - end + @main_category = + (@current_user.all_categories & Category.roots).find do |c| + (@current_user.categories.with_borrowable_items & c.children).size == 0 + end end Then(/^that main category has no child category dropdown$/) do - expect(find('.row.emboss.focus-hover', match: :first, text: @main_category.name).has_no_selector? '.dropdown-holder').to be true -end - -Then(/^I see for each category its image, or if not set, the first image of a model from this category$/) do + expect( + find( + '.row.emboss.focus-hover', match: :first, text: @main_category.name + ).has_no_selector? '.dropdown-holder' + ).to be true +end + +Then( + / + ^I see for each category its image, or if not set, the first image of a model from this category$ + / +) do @main_categories.each do |mc| img_el = find('a', match: :first, text: mc.name).find('img') response = get img_el[:src] - if image = mc.image - expect(response.location).to match /#{image.id}/ - end + expect(response.location).to match /#{image.id}/ if image = mc.image end end @@ -103,7 +110,9 @@ end Given(/^there exists a main category without own image but with a model with image$/) do - expect((@current_user.all_categories & Category.roots).find do |c| - not c.images.exists? and c.all_models.detect{|m| not m.image.blank? } - end).not_to be_nil + expect( + (@current_user.all_categories & Category.roots).find do |c| + nc.images.exists? and c.all_models.detect { |m| nm.image.blank? } + end + ).not_to be_nil end diff --git a/features/step_definitions/borrow/templates_steps.rb b/features/step_definitions/borrow/templates_steps.rb index c668cff01e..efb303b5a3 100644 --- a/features/step_definitions/borrow/templates_steps.rb +++ b/features/step_definitions/borrow/templates_steps.rb @@ -1,13 +1,10 @@ # -*- encoding : utf-8 -*- - Then(/^I see a link to the templates underneath the categories$/) do - find("a[href='#{borrow_templates_path}'][title='#{_("Borrow template")}']", match: :first) + find("a[href='#{borrow_templates_path}'][title='#{_('Borrow template')}']", match: :first) end -When(/^I am listing templates in the borrow section$/) do - visit borrow_templates_path -end +When(/^I am listing templates in the borrow section$/) { visit borrow_templates_path } Then(/^I see the templates$/) do @current_user.templates.each do |template| @@ -16,7 +13,7 @@ end Then(/^the templates are sorted alphabetically by name$/) do - all_names = all(".separated-top > a[href*='#{borrow_templates_path}']").map {|x| x.text.strip } + all_names = all(".separated-top > a[href*='#{borrow_templates_path}']").map { |x| x.text.strip } expect(all_names.sort).to eq all_names expect(all_names.count).to eq @current_user.templates.count end @@ -28,14 +25,17 @@ end When(/^I am looking at a template$/) do - @template = @current_user.templates.find do |t| - # choose a template, whose all models provide some borrowable quantity (> 0) considering all customer's groups from all his inventory pools - t.models.all? do |m| - t.inventory_pools.map do |ip| - m.total_borrowable_items_for_user_and_pool(@current_user, ip) - end.max > 0 + @template = + @current_user.templates.find do |t| + # choose a template, whose all models provide some borrowable quantity (> 0) considering all customer's groups from all his inventory pools + t + .models + .all? do |m| + t.inventory_pools.map { |ip| m.total_borrowable_items_for_user_and_pool(@current_user, ip) } + .max > + 0 + end end - end visit borrow_template_path(@template) find("nav a[href='#{borrow_template_path(@template)}']", match: :first) @@ -43,37 +43,60 @@ Then(/^I see all models that template contains$/) do @template.model_links.each do |model_link| - find('.line', match: :prefer_exact, text: model_link.model.name).find("input[name='reservations[][quantity]'][value='#{model_link.quantity}']") + find('.line', match: :prefer_exact, text: model_link.model.name).find( + "input[name='reservations[][quantity]'][value='#{model_link.quantity}']" + ) end end Then(/^the models in that template are ordered alphabetically$/) do - all_names = all('.separated-top > .row.line').map {|x| x.text.strip } + all_names = all('.separated-top > .row.line').map { |x| x.text.strip } expect(all_names.sort).to eq all_names expect(all_names.count).to eq @template.models.count end Then(/^for each model I see the quantity as specified by the template$/) do @template.model_links.each do |model_link| - find('.row', match: :first, text: model_link.model.name).find("input[name='reservations[][quantity]'][value='#{model_link.quantity}']", match: :first) + find('.row', match: :first, text: model_link.model.name).find( + "input[name='reservations[][quantity]'][value='#{model_link.quantity}']", match: :first + ) end end When(/^I can modify the quantity of each model before ordering$/) do @model_link = @template.model_links.first - find('.row', match: :first, text: @model_link.model.name).find("input[name='reservations[][quantity]'][value='#{@model_link.quantity}']", match: :first).set rand(10) + find('.row', match: :first, text: @model_link.model.name).find( + "input[name='reservations[][quantity]'][value='#{@model_link.quantity}']", match: :first + ).set rand(10) end Then(/^I can specify at most the maximum available quantity per model$/) do - max = find('.row', match: :first, text: @model_link.model.name).find("input[name='reservations[][quantity]']", match: :first)[:max].to_i - find('.row', match: :first, text: @model_link.model.name).find("input[name='reservations[][quantity]']", match: :first).set max+1 + max = + find('.row', match: :first, text: @model_link.model.name).find( + "input[name='reservations[][quantity]']", match: :first + )[ + :max + ] + .to_i + find('.row', match: :first, text: @model_link.model.name).find( + "input[name='reservations[][quantity]']", match: :first + ).set max + 1 wait_until do - find('.row', match: :first, text: @model_link.model.name).find("input[name='reservations[][quantity]']", match: :first).value.to_i == max + find('.row', match: :first, text: @model_link.model.name).find( + "input[name='reservations[][quantity]']", match: :first + ) + .value + .to_i == + max end end Then(/^I see a warning on the page itself and on every affected model$/) do - find('.emboss.red', match: :first, text: _('The highlighted entries are not accomplishable for the intended quantity.')) + find( + '.emboss.red', + match: :first, + text: _('The highlighted entries are not accomplishable for the intended quantity.') + ) find('.separated-top .row.line .line-info.red', match: :first) end @@ -89,8 +112,12 @@ end end -When(/^this template contains models that don't have enough items to satisfy the quantity required by the template$/) do - @template = @current_user.templates.detect {|t| not t.accomplishable?(@current_user) } +When( + / + ^this template contains models that don't have enough items to satisfy the quantity required by the template$ + / +) do + @template = @current_user.templates.detect { |t| nt.accomplishable?(@current_user) } visit borrow_template_path(@template) find("nav a[href='#{borrow_template_path(@template)}']", match: :first) end @@ -105,20 +132,20 @@ Then(/^those models are highlighted that are no longer available at this time$/) do within '#template-lines' do - all('.row.line').each do |line| - line.find('.line-info.red', match: :first) - end + all('.row.line').each { |line| line.find('.line-info.red', match: :first) } end end Then(/^I can remove the models from the view$/) do within('.row.line', match: :first) do - if has_selector? '.multibutton .dropdown-toggle' - find('.multibutton .dropdown-toggle').click - end + find('.multibutton .dropdown-toggle').click if has_selector? '.multibutton .dropdown-toggle' find('.red', text: _('Delete')).click end - page.driver.browser.switch_to.alert.accept rescue nil + begin + page.driver.browser.switch_to.alert.accept + rescue StandardError + nil + end end Then(/^I can change the quantity of the models$/) do @@ -130,12 +157,14 @@ def select_available_not_closed_date(as = :start, from = Date.today) current_date = from - step "I set the %s in the calendar to '#{I18n::l(current_date)}'" % (as == :start ? 'start date' : 'end date') - while page.has_selector?("#booking-calendar-errors") do + step "I set the %s in the calendar to '#{I18n.l(current_date)}'" % + (as == :start ? 'start date' : 'end date') + while page.has_selector?('#booking-calendar-errors') before_date = current_date current_date += 1.day find('.fc-button-next').click if before_date.month < current_date.month - step "I set the %s in the calendar to '#{I18n::l(current_date)}'" % (as == :start ? 'start date' : 'end date') + step "I set the %s in the calendar to '#{I18n.l(current_date)}'" % + (as == :start ? 'start date' : 'end date') end current_date end @@ -160,11 +189,9 @@ def select_available_not_closed_date(as = :start, from = Date.today) step 'I am looking at a template' find("[type='submit']", match: :first).click date = Date.today - while @template.inventory_pools.first.open_on?(date) do - date += 1.day - end - find('#start_date').set I18n::localize(date) - find('#end_date').set I18n::localize(date) + date += 1.day while @template.inventory_pools.first.open_on?(date) + find('#start_date').set I18n.localize(date) + find('#end_date').set I18n.localize(date) step 'I can follow the process to the availability display of the template' end diff --git a/features/step_definitions/borrow/timeoutpage_steps.rb b/features/step_definitions/borrow/timeoutpage_steps.rb index cedcfca603..4bb762d141 100644 --- a/features/step_definitions/borrow/timeoutpage_steps.rb +++ b/features/step_definitions/borrow/timeoutpage_steps.rb @@ -19,23 +19,30 @@ end Then(/^I am informed that my items are no longer reserved for me$/) do - expect(has_content?(_('%d minutes passed. The items are not reserved for you any more!') % Setting.first.timeout_minutes)).to be true + expect( + has_content?( + _('%d minutes passed. The items are not reserved for you any more!') % + Setting.first.timeout_minutes + ) + ).to be true end Then(/^I am informed that the remaining models are all available$/) do - expect(has_content?(_('Your order has been modified. All reservations are now available.'))).to be true + expect( + has_content?(_('Your order has been modified. All reservations are now available.')) + ).to be true end ######################################################################### -Then(/^I see my order$/) do - find('#current-order-lines') -end +Then(/^I see my order$/) { find('#current-order-lines') } Then(/^the no longer available items are highlighted$/) do @current_user.reservations.unsubmitted.each do |line| unless line.available? - find("[data-ids*='#{line.id}']", match: :first).find(:xpath, './../../..').find(".line-info.red[title='#{_("Not available")}']") + find("[data-ids*='#{line.id}']", match: :first).find(:xpath, './../../..').find( + ".line-info.red[title='#{_('Not available')}']" + ) end end end @@ -51,14 +58,10 @@ end Then(/^I can edit entries$/) do - all('.row.line').each do |x| - x.find('button', text: _('Change entry')) - end + all('.row.line').each { |x| x.find('button', text: _('Change entry')) } end -Then(/^I can return to the main order overview$/) do - find('a', text: _('Continue this order')) -end +Then(/^I can return to the main order overview$/) { find('a', text: _('Continue this order')) } ######################################################################### @@ -71,7 +74,9 @@ Given(/^I delete one entry$/) do line = all('.row.line').to_a.sample @line_ids = JSON.parse(line.find('button[data-ids]')['data-ids']) - expect(@line_ids.all? { |id| @current_user.reservations.unsubmitted.map(&:id).include?(id) }).to be true + expect( + @line_ids.all? { |id| @current_user.reservations.unsubmitted.map(&:id).include?(id) } + ).to be true line.find('.dropdown-toggle').click line.find('a', text: _('Delete')).click step 'I am asked whether I really want to delete' @@ -79,7 +84,9 @@ Then(/^the entry is deleted from the order$/) do expect(@line_ids.all? { |id| page.has_no_selector? "button[data-ids='[#{id}]']" }).to be true - expect(@line_ids.all? { |id| not @current_user.reservations.unsubmitted.map(&:id).include?(id) }).to be true + expect( + @line_ids.all? { |id| n@current_user.reservations.unsubmitted.map(&:id).include?(id) } + ).to be true end ######################################################################### @@ -87,17 +94,18 @@ When(/^I (increase|decrease) the quantity of one entry$/) do |arg1| step 'I change the entry' step 'the calendar opens' - @new_quantity = case arg1 - when 'increase' - line = @changed_lines.first - line.model.total_borrowable_items_for_user_and_pool(line.user, - line.inventory_pool, - ensure_non_negative_general: true) - when 'decrease' - 1 - else - raise - end + @new_quantity = + case arg1 + when 'increase' + line = @changed_lines.first + line.model.total_borrowable_items_for_user_and_pool( + line.user, line.inventory_pool, ensure_non_negative_general: true + ) + when 'decrease' + 1 + else + raise + end find('#booking-calendar-quantity').set(@new_quantity) step 'I save the booking calendar' step 'the booking calendar is closed' @@ -108,26 +116,28 @@ end When(/^the unavailable models are deleted from the order$/) do - expect(@current_user.reservations.unsubmitted.all? { |l| l.available? }).to be true + expect(@current_user.reservations.unsubmitted.all?(&:available?)).to be true end When(/^I correct one of the errors$/) do - @line_ids = @current_user.reservations.unsubmitted.select { |l| not l.available? }.map(&:id) + @line_ids = @current_user.reservations.unsubmitted.select { |l| nl.available? }.map(&:id) resolve_conflict_for_reservation @line_ids.delete_at(0) end When(/^I correct all errors$/) do - @line_ids.each do |line_id| - resolve_conflict_for_reservation line_id - end + @line_ids.each { |line_id| resolve_conflict_for_reservation line_id } end Then(/^the error message appears$/) do - expect(has_no_content? _('Please solve the conflicts for all highlighted reservations in order to continue.')).to be true + expect( + has_no_content? _( + 'Please solve the conflicts for all highlighted reservations in order to continue.' + ) + ).to be true end def resolve_conflict_for_reservation(line_id) - within ".line[data-ids='[\"#{line_id}\"]']" do + within ".line[data-ids='[undefined#{line_id}undefined]']" do find('.button', text: _('Change entry')).click end expect(has_selector?('#booking-calendar .fc-day-content')).to be true @@ -138,7 +148,7 @@ def resolve_conflict_for_reservation(line_id) find('.modal .button.green').click step 'the booking calendar is closed' - within ".line[data-ids='[\"#{line_id}\"]']" do + within ".line[data-ids='[undefined#{line_id}undefined]']" do expect(has_no_selector?('.line-info.red')).to be true end end diff --git a/features/step_definitions/borrow/view_my_user_data_steps.rb b/features/step_definitions/borrow/view_my_user_data_steps.rb index a10a2f19f6..30ff095b28 100644 --- a/features/step_definitions/borrow/view_my_user_data_steps.rb +++ b/features/step_definitions/borrow/view_my_user_data_steps.rb @@ -1,28 +1,26 @@ # -*- encoding : utf-8 -*- #Dann(/^werden mir meine Benutzerdaten angezeigt$/) do -Then(/^I can see my user data$/) do - find('nav ul li a', match: :first, text: _('User data')) -end +Then(/^I can see my user data$/) { find('nav ul li a', match: :first, text: _('User data')) } #Dann(/^die Benutzerdaten beinhalten$/) do |table| Then(/^the user data consist of$/) do |table| table.raw.flatten.each do |section| case section - when 'First name' - expect(has_content?(_('First name'))).to be true - expect(has_content?(@current_user.firstname)).to be true - when 'Last name' - expect(has_content?(_('Last name'))).to be true - expect(has_content?(@current_user.lastname)).to be true - when 'Email' - expect(has_content?(_('Email'))).to be true - expect(has_content?(@current_user.email)).to be true - when 'Phone number' - expect(has_content?(_('Phone'))).to be true - expect(has_content?(@current_user.phone)).to be true - else - raise 'unkown section' + when 'First name' + expect(has_content?(_('First name'))).to be true + expect(has_content?(@current_user.firstname)).to be true + when 'Last name' + expect(has_content?(_('Last name'))).to be true + expect(has_content?(@current_user.lastname)).to be true + when 'Email' + expect(has_content?(_('Email'))).to be true + expect(has_content?(@current_user.email)).to be true + when 'Phone number' + expect(has_content?(_('Phone'))).to be true + expect(has_content?(@current_user.phone)).to be true + else + raise 'unkown section' end end end diff --git a/features/step_definitions/category_steps.rb b/features/step_definitions/category_steps.rb index f65ec8af52..8197710405 100644 --- a/features/step_definitions/category_steps.rb +++ b/features/step_definitions/category_steps.rb @@ -2,10 +2,11 @@ find('tr', match: :first, text: /#{model_name}/).find_link('Show').click end -When /^I check the category "([^"]*)"$/ do |category| +When /^I check the category "([^"]*)"$/ do |category| within 'ul.simple_tree' do all('li').each do |item| - if item.text == category and item.find('input', match: :first).native.attribute('checked').nil? + if item.text == category and + item.find('input', match: :first).native.attribute('checked').nil? item.find('input', match: :first).click end end @@ -15,42 +16,40 @@ When /^I uncheck the category "([^"]*)"$/ do |category| within 'ul.simple_tree' do all('li').each do |item| - if item.text == category and !item.find('input', match: :first).native.attribute('checked').nil? + if item.text == category and + !item.find('input', match: :first).native.attribute('checked').nil? item.find('input', match: :first).click end end end end -Then /^the model "([^"]*)" should( not)? be in category "([^"]*)"$/ do |model_name, boolean, category_name| - step "I follow the sloppy link \"All Models\"" +Then / + ^the model "([^"]*)" should( not)? be in category "([^"]*)"$ + / do |model_name, boolean, category_name| + step 'I follow the sloppy link "All Models"' category_list = find('tr', match: :first, text: model_name).all('ul')[3] case boolean - when ' not' - expect(category_list.text).not_to match /#{category_name}/ - else - expect(category_list.text).to match /#{category_name}/ + when ' not' + expect(category_list.text).not_to match /#{category_name}/ + else + expect(category_list.text).to match /#{category_name}/ end end -Given(/^there is a main category$/) do - @main_category = Category.roots.first -end +Given(/^there is a main category$/) { @main_category = Category.roots.first } Then(/^this category can have children$/) do - child_category = Category.where.not(id: @main_category).detect {|c| not @main_category.children.include? c } + child_category = + Category.where.not(id: @main_category).detect { |c| n@main_category.children.include? c } @main_category.children << child_category expect(@main_category.reload.children.include? child_category).to be true end -Then(/^this category has no parents$/) do - expect(@main_category.parents).to be_empty -end +Then(/^this category has no parents$/) { expect(@main_category.parents).to be_empty } # We wrap some steps in this so that it's guaranteed that we get a logout. This is # necessary so any "I log in as...." steps in the Background section actually work, as # they don't work when a user is already logged in. This prevents failing steps from # breaking following tests. -After('@logoutafter') do - step "I follow the sloppy link \"Logout\"" -end +After('@logoutafter') { step 'I follow the sloppy link "Logout"' } diff --git a/features/step_definitions/database_login_steps.rb b/features/step_definitions/database_login_steps.rb index bc5f1e3e93..65b93afa8f 100644 --- a/features/step_definitions/database_login_steps.rb +++ b/features/step_definitions/database_login_steps.rb @@ -3,8 +3,7 @@ toggle ||= first('.topbar .dropdown', text: @current_user.try(:lastname)) if toggle toggle.click - sign_out_button = first(".topbar form[action='/sign-out'] button", - visible: :all) + sign_out_button = first(".topbar form[action='/sign-out'] button", visible: :all) sign_out_button.click find('#flash') else @@ -12,17 +11,12 @@ end end -When(/^I visit the homepage$/) do - visit root_path -end +When(/^I visit the homepage$/) { visit root_path } When(/^I login as "(.*?)" via web interface$/) do |persona| @current_user = User.where(login: persona.downcase).first - I18n.locale = if @current_user.language then - @current_user.language.locale_name.to_sym - else - Language.default_language - end + I18n.locale = + @current_user.language ? @current_user.language.locale_name.to_sym : Language.default_language step 'I visit the homepage' fill_in 'email', with: @current_user.email click_on _('Login') @@ -30,48 +24,47 @@ When(/^I login as "(.*?)" via web interface using keyboard$/) do |persona| @current_user = User.where(login: persona.downcase).first - I18n.locale = if @current_user.language then - @current_user.language.locale_name.to_sym - else - Language.default_language - end + I18n.locale = + @current_user.language ? @current_user.language.locale_name.to_sym : Language.default_language step 'I visit the homepage' find("a[href='#{login_path}']", match: :first).click fill_in 'username', with: persona.downcase sleep 0.2 pw_field = find('[name="login[password]"]') - pw_field.native.send_keys('passw') - sleep 0.2 # must be larger than BarcodeScanner delay (100ms)! + pw_field.native.send_keys('passw') # must be larger than BarcodeScanner delay (100ms)! + sleep 0.2 pw_field.native.send_keys('ord', :enter) end -Then(/^I am logged in$/) do - expect(has_content?(@current_user.short_name)).to be true -end +Then(/^I am logged in$/) { expect(has_content?(@current_user.short_name)).to be true } Given(/^my authentication system is "(.*?)"$/) do |arg1| expect(@current_user.authentication_system.class_name).to eq arg1 end When(/^I hover over my name$/) do - find("nav.topbar ul.topbar-navigation .topbar-item", text: @current_user.short_name).hover + find('nav.topbar ul.topbar-navigation .topbar-item', text: @current_user.short_name).hover end Then(/^I get to the "(.*?)" page$/) do |arg1| case arg1 - when 'User Data' - expect(current_path).to eq borrow_current_user_path - else - raise + when 'User Data' + expect(current_path).to eq borrow_current_user_path + else + raise end end When(/^I change my password$/) do @new_password = Faker::Internet.password(6) - find('.row', match: :prefer_exact, text: _('Password')).find("input[name='db_auth[password]']").set @new_password - find('.row', match: :prefer_exact, text: _('Password Confirmation')).find("input[name='db_auth[password_confirmation]']").set @new_password + find('.row', match: :prefer_exact, text: _('Password')).find( + "input[name='db_auth[password]']" + ).set @new_password + find('.row', match: :prefer_exact, text: _('Password Confirmation')).find( + "input[name='db_auth[password_confirmation]']" + ).set @new_password find(".row button[type='submit']", text: _('Save')).click - step %Q(I get to the "User Data" page) + step 'I get to the "User Data" page' end Then(/^my password is changed$/) do diff --git a/features/step_definitions/db_steps.rb b/features/step_definitions/db_steps.rb index d8f15be7c0..4159dbf021 100644 --- a/features/step_definitions/db_steps.rb +++ b/features/step_definitions/db_steps.rb @@ -1,9 +1,3 @@ -Given(/^(?:the )database is empty$/) do - PgTasks.truncate_tables -end +Given(/^(?:the )database is empty$/) { PgTasks.truncate_tables } -Given(/^settings exist$/) do - unless Setting.first - FactoryGirl.create(:setting) - end -end +Given(/^settings exist$/) { FactoryGirl.create(:setting) unless Setting.first } diff --git a/features/step_definitions/debug_steps.rb b/features/step_definitions/debug_steps.rb index 46ec1f8e40..e7cc643dd9 100644 --- a/features/step_definitions/debug_steps.rb +++ b/features/step_definitions/debug_steps.rb @@ -3,12 +3,9 @@ end Then /^dump the response to '([^']*)'$/ do |filename| - File.open(filename, File::CREAT|File::TRUNC|File::RDWR) do |f| - f.puts body - end + File.open(filename, File::CREAT | File::TRUNC | File::RDWR) { |f| f.puts body } end - # rubocop:disable Lint/Debugger Then 'start the debugger' do debugger @@ -42,13 +39,9 @@ # tag your scenarion with '@slowly' and then every step # will be executed with a default delay of 2 seconds -Before('@slowly') do - step 'wait' unless @skip_wait -end +Before('@slowly') { step 'wait' unless @skip_wait } -AfterStep('@slowly') do - step 'wait' unless @skip_wait -end +AfterStep('@slowly') { step 'wait' unless @skip_wait } # since only Scenarios and not single steps can be tagged with # '@slowly', you can switch on and off delaying between steps @@ -63,4 +56,3 @@ Then 'set the default delay to $delay' do |delay| @delay = delay.to_i end - diff --git a/features/step_definitions/documents_steps.rb b/features/step_definitions/documents_steps.rb index f38d8d2649..acb84c58d1 100644 --- a/features/step_definitions/documents_steps.rb +++ b/features/step_definitions/documents_steps.rb @@ -1,45 +1,57 @@ # -*- encoding : utf-8 -*- When(/^I click on "([^"]*)" underneath my username$/) do |arg| - #step "ich über meinen Namen fahre" - step 'I hover over my name' + step #step "ich über meinen Namen fahre" + 'I hover over my name' find("a[href='#{borrow_user_documents_path}']").click end Then(/^my contracts are ordered by the earliest time window$/) do - dates = all('div.line-col', text: /\d{2}.\d{2}.\d{4}\s\-\s\d{2}.\d{2}.\d{4}/).map {|x| Date.parse(x.text.split.first) } + dates = + all('div.line-col', text: /\d{2}.\d{2}.\d{4}\s\-\s\d{2}.\d{2}.\d{4}/).map do |x| + Date.parse(x.text.split.first) + end expect(dates.sort).to eq dates end Then(/^I see the following information for each contract:$/) do |table| - contracts = @current_user.contracts.sort {|a,b| b.time_window_min <=> a.time_window_min} + contracts = @current_user.contracts.sort { |a, b| b.time_window_min <=> a.time_window_min } contracts.each do |contract| within(".line[data-id='#{contract.id}']") do table.raw.flatten.each do |s| case s - when 'Contract number' - expect(has_content?(contract.compact_id)).to be true - when 'Time window with its start and end' - expect(has_content?(contract.time_window_min.strftime('%d/%m/%Y'))).to be true - expect(has_content?(contract.time_window_max.strftime('%d/%m/%Y'))).to be true - expect(has_content?((contract.time_window_max - contract.time_window_min).to_i.abs + 1)).to be true - when 'Inventory pool' - expect(has_content?(contract.inventory_pool.shortname)).to be true - when 'Purpose' - expect(has_content?(contract.purpose)).to be true - when 'Status' - expect(has_content?(_('Open'))).to be true if contract.state == :open - when 'Link to the contract' - expect(has_selector?("a[href='#{borrow_user_contract_path(contract.id)}']", text: _('Contract'))).to be true - when 'Link to the value list' - unless first('.dropdown') - find('.dropdown-holder').click - end - find("a[href='#{borrow_user_contract_path(contract.id)}'] + .dropdown-holder > .dropdown-toggle").click - expect(has_selector?("a[href='#{borrow_user_value_list_path(contract.id)}']")).to be true - find("a[href='#{borrow_user_contract_path(contract.id)}']").click # release the previous click - else - raise 'unkown section' + when 'Contract number' + expect(has_content?(contract.compact_id)).to be true + when 'Time window with its start and end' + expect(has_content?(contract.time_window_min.strftime('%d/%m/%Y'))).to be true + expect(has_content?(contract.time_window_max.strftime('%d/%m/%Y'))).to be true + expect( + has_content?((contract.time_window_max - contract.time_window_min).to_i.abs + 1) + ).to be true + when 'Inventory pool' + expect(has_content?(contract.inventory_pool.shortname)).to be true + when 'Purpose' + expect(has_content?(contract.purpose)).to be true + when 'Status' + expect(has_content?(_('Open'))).to be true if contract.state == :open + when 'Link to the contract' + expect( + has_selector?( + "a[href='#{borrow_user_contract_path(contract.id)}']", text: _('Contract') + ) + ).to be true + when 'Link to the value list' + find('.dropdown-holder').click unless first('.dropdown') + find( + "a[href='#{borrow_user_contract_path( + contract.id + )}'] + .dropdown-holder > .dropdown-toggle" + ) + .click + expect(has_selector?("a[href='#{borrow_user_value_list_path(contract.id)}']")).to be true + find("a[href='#{borrow_user_contract_path(contract.id)}']").click # release the previous click + else + raise 'unkown section' end end end @@ -50,9 +62,7 @@ @contract = @current_user.contracts.first within(".row.line[data-id='#{@contract.id}']") do find('.dropdown-toggle').click - document_window = window_opened_by do - click_link _('Value List') - end + document_window = window_opened_by { click_link _('Value List') } page.driver.browser.switch_to.window(document_window.handle) end end @@ -63,15 +73,14 @@ Given(/^I click the contract link$/) do @contract = @current_user.contracts.first - document_window = window_opened_by do - find("a[href='#{borrow_user_contract_path(@contract.id)}']", text: _('Contract')).click - end + document_window = + window_opened_by do + find("a[href='#{borrow_user_contract_path(@contract.id)}']", text: _('Contract')).click + end page.driver.browser.switch_to.window(document_window.handle) end -Then(/^the contract opens$/) do - expect(current_path).to eq borrow_user_contract_path(@contract.id) -end +Then(/^the contract opens$/) { expect(current_path).to eq borrow_user_contract_path(@contract.id) } When(/^I open a value list from my documents$/) do @contract = @current_user.contracts.first @@ -90,7 +99,7 @@ end When(/^I open a contract with returned items from my documents$/) do - @contract = @current_user.contracts.find {|c| c.reservations.any? &:returned_to_user} + @contract = @current_user.contracts.find { |c| c.reservations.any? &:returned_to_user } visit borrow_user_contract_path(@contract.id) step 'the contract opens' end @@ -100,15 +109,27 @@ # The rest is deleted: Dito, see above. end -Then(/^the relevant reservations show the person taking back the item in the format "F. Lastname"$/) do +Then( + /^the relevant reservations show the person taking back the item in the format "F. Lastname"$/ +) do if @reservations_to_take_back @reservations_to_take_back.map(&:contract).uniq.each do |contract| - new_window = window_opened_by do - find(".button[target='_blank'][href='#{manage_contract_path(@current_inventory_pool, contract)}']").click - end + new_window = + window_opened_by do + find( + ".button[target='_blank'][href='#{manage_contract_path( + @current_inventory_pool, contract + )}']" + ) + .click + end within_window new_window do contract.reservations.each do |cl| - find('.contract .list.returned_items tr', text: /#{cl.quantity}.*#{cl.item.inventory_code}.*#{I18n.l cl.end_date}/).find('.returning_date', text: cl.returned_to_user.short_name) + find( + '.contract .list.returned_items tr', + text: /#{cl.quantity}.*#{cl.item.inventory_code}.*#{I18n.l cl.end_date}/ + ) + .find('.returning_date', text: cl.returned_to_user.short_name) end end end @@ -116,7 +137,9 @@ reservations = @contract.reservations.where.not(returned_date: nil) expect(reservations.size).to be > 0 reservations.each do |cl| - find('.contract .list.returned_items tr', text: cl.item.inventory_code).find('.returning_date', text: cl.returned_to_user.short_name) + find('.contract .list.returned_items tr', text: cl.item.inventory_code).find( + '.returning_date', text: cl.returned_to_user.short_name + ) end end end @@ -126,11 +149,10 @@ customer = FactoryGirl.create(:user) customer.access_rights << FactoryGirl.create(:access_right, inventory_pool: inventory_pool) (Date.today..Date.today + 1.week).each do |date| - FactoryGirl.create(:open_contract, - inventory_pool: inventory_pool, - user: customer, - start_date: date, - end_date: date + 1.day) + FactoryGirl.create( + :open_contract, + inventory_pool: inventory_pool, user: customer, start_date: date, end_date: date + 1.day + ) end step 'I am logged in as "%s"' % customer.login end diff --git a/features/step_definitions/group_steps.rb b/features/step_definitions/group_steps.rb index 5f9f7b1d72..1ab93a2f55 100644 --- a/features/step_definitions/group_steps.rb +++ b/features/step_definitions/group_steps.rb @@ -1,26 +1,35 @@ # # Models in EntitlementGroups # -Then 'that model should not be available in any other group' do +Then 'that model should not be available in any other group' do # FIXME how can be executed the next line ?? where is implemented the maximum method ?? # quantities = @model.in(@inventory_pool).maximum_available_in_period_for_groups(@inventory_pool.entitlement_groups.where(['id != ?',@group]).pluck(:id)) # quantities.values.reduce(:+).to_i.should == 0 end -Then /^(\w+) item(s?) of that model should be available in group '([^"]*)'( only)?$/ do |n, plural, group_name, exclusivity| +Then / + ^(\w+) item(s?) of that model should be available in group '([^"]*)'( only)?$ + / do |n, plural, group_name, exclusivity| n = to_number(n) @group = @inventory_pool.entitlement_groups.find_by_name(group_name) all_groups = [EntitlementGroup::GENERAL_GROUP_ID] + @inventory_pool.entitlement_group_ids quantities = Entitlement.hash_with_generals(@inventory_pool, @model) expect(quantities[@group.id].to_i).to eq to_number(n) - all_groups.each do |group| - expect(quantities[group].to_i).to eq 0 if (group ? group.name : 'General') != group_name - end if exclusivity + if exclusivity + all_groups.each do |group| + expect(quantities[group].to_i).to eq 0 if (group ? group.name : 'General') != group_name + end + end end -Then 'that model should not be available in any group' do - expect(Entitlement.hash_with_generals(@inventory_pool, @model).reject { |group_id, num| group_id == EntitlementGroup::GENERAL_GROUP_ID }.size).to eq 0 +Then 'that model should not be available in any group' do + expect( + Entitlement.hash_with_generals(@inventory_pool, @model).reject do |group_id, num| + group_id == EntitlementGroup::GENERAL_GROUP_ID + end + .size + ).to eq 0 end # TODO: currently unused @@ -37,7 +46,7 @@ end When /^an item is assigned to group "([^"]*)"$/ do |to_group_name| - step "I assign one item to group \"#{to_group_name}\"" + step "I assign one item to group undefined#{to_group_name}undefined" end When /^I assign (\w+) item(s?) to group "([^"]*)"$/ do |n, plural, to_group_name| @@ -55,20 +64,24 @@ Then '$n items of that model should be available to everybody' do |n| User.where.not(login: nil).each do |user| - step "#{n} items of that model should be available to \"#{user.login}\"" + step "#{n} items of that model should be available to undefined#{user.login}undefined" end end Then /^(\w+) item(s?) of that model should be available to "([^"]*)"$/ do |n, plural, user| @user = User.find_by_login user - expect(@model.availability_in(@inventory_pool.reload).maximum_available_in_period_for_groups(Date.today, Date.tomorrow, @user.entitlement_group_ids)).to eq n.to_i + expect( + @model.availability_in(@inventory_pool.reload).maximum_available_in_period_for_groups( + Date.today, Date.tomorrow, @user.entitlement_group_ids + ) + ).to eq n.to_i end # # EntitlementGroups # -Given /^a group '([^']*)'( exists)?$/ do |name,foo| - step "I add a group called \"#{name}\"" +Given /^a group '([^']*)'( exists)?$/ do |name, foo| + step "I add a group called undefined#{name}undefined" end When /^I add a group called "([^"]*)"$/ do |name| @@ -76,20 +89,19 @@ end # TODO: currently unused -Then /^he must be in group '(\w+)'( in inventory pool )?('[^']*')?$/ \ -do |group, filler, inventory_pool| +Then / + ^he must be in group '(\w+)'( in inventory pool )?('[^']*')?$ + / do |group, filler, inventory_pool| inventory_pools = [] if inventory_pool - inventory_pool.gsub!(/'/,'') # remove quotes - inventory_pools << InventoryPool.find_by_name( inventory_pool ) + inventory_pool.gsub!(/'/, '') # remove quotes + inventory_pools << InventoryPool.find_by_name(inventory_pool) else inventory_pools = @user.inventory_pools end groups = inventory_pools.collect { |ip| ip.entitlement_groups.where(name: group).first } - groups.each do |group| - expect(group.users.find_by_id( @user.id )).not_to be_nil - end + groups.each { |group| expect(group.users.find_by_id(@user.id)).not_to be_nil } end # @@ -104,34 +116,37 @@ Given /^a customer "([^"]*)" that belongs to group "([^"]*)"$/ do |user, group| step "a customer '#{user}' for inventory pool '#{@inventory_pool.name}'" - step "the customer \"#{user}\" is added to group \"#{group}\"" + step "the customer undefined#{user}undefined is added to group undefined#{group}undefined" end When /^I lend (\w+) item(s?) of that model to "([^"]*)"$/ do |n, plural, user_login| user = User.find_by_login user_login purpose = 'this is the required purpose' - order = FactoryGirl.create(:order, - state: :approved, - user: user, - inventory_pool: @inventory_pool, - purpose: purpose) - reservations = to_number(n).times.map do - FactoryGirl.create(:reservation, - status: :approved, - order: order, - inventory_pool: @inventory_pool, - user: user, - model: @model, - start_date: Date.today, - end_date: Date.tomorrow) - end + order = + FactoryGirl.create( + :order, state: :approved, user: user, inventory_pool: @inventory_pool, purpose: purpose + ) + reservations = + to_number(n).times.map do + FactoryGirl.create( + :reservation, + status: :approved, + order: order, + inventory_pool: @inventory_pool, + user: user, + model: @model, + start_date: Date.today, + end_date: Date.tomorrow + ) + end reservations.each do |cl| - cl.update_attributes(item: cl.model.items.borrowable.in_stock.where(inventory_pool: cl.inventory_pool).sample ) + cl.update_attributes( + item: cl.model.items.borrowable.in_stock.where(inventory_pool: cl.inventory_pool).sample + ) end - contract = Contract.sign!(@user, @inventory_pool, user, reservations, - Faker::Lorem.sentence) + contract = Contract.sign!(@user, @inventory_pool, user, reservations, Faker::Lorem.sentence) expect(contract).to be_valid end @@ -140,9 +155,7 @@ cl = @user.reservations.last ApplicationRecord.transaction do cl.update_attributes(returned_date: Date.today) - if cl.last_closed_reservation_of_contract? - cl.contract.update_attributes(state: :closed) - end + cl.contract.update_attributes(state: :closed) if cl.last_closed_reservation_of_contract? end expect(cl.status).to be :closed end diff --git a/features/step_definitions/hand_over_steps.rb b/features/step_definitions/hand_over_steps.rb index 4e99c09eae..dd044d863a 100644 --- a/features/step_definitions/hand_over_steps.rb +++ b/features/step_definitions/hand_over_steps.rb @@ -1,4 +1,4 @@ -When '$who approves the order' do | who | +When '$who approves the order' do |who| post login_path(login: @last_manager_login_name) post manage_approve_order_path(@inventory_pool, @order, comment: 'test comment') @order = assigns(:order) @@ -26,24 +26,22 @@ # expect(@contract.reservations.size).to eq 1 # end - -Then /he sees ([0-9]+) line(s?) with a total quantity of ([0-9]+)$/ do |total, s, quantity | - expect(@visits.size).to eq total.to_i - s = @visits.sum(:quantity) - expect(s).to eq quantity.to_i +Then /he sees ([0-9]+) line(s?) with a total quantity of ([0-9]+)$/ do |total, s, quantity| + expect(@visits.size).to eq total.to_i + s = @visits.sum(:quantity) + expect(s).to eq quantity.to_i end ############################################### -Then "line $line has a quantity of $quantity for customer '$who'" do | line, quantity, who | +Then "line $line has a quantity of $quantity for customer '$who'" do |line, quantity, who| expect(@visits[line.to_i - 1].quantity).to eq quantity.to_i expect(@visits[line.to_i - 1].user.login).to eq who end ############################################### - -When '$who chooses one line' do | who | +When '$who chooses one line' do |who| visit = @visits.first get manage_hand_over_path(@inventory_pool, visit.user) response.should render_template('backend/hand_over/show') @@ -51,7 +49,7 @@ end # copied from 'When "$who chooses $name's order"' -When "$who chooses $name's visit" do | who, name | +When "$who chooses $name's visit" do |who, name| @visit = @visits.detect { |c| c.user.login == name } get manage_hand_over_path(@inventory_pool, @visit.user) response.should render_template('backend/hand_over/show') @@ -59,15 +57,15 @@ @response = response end -When "$who assigns '$item' to the first line" do | who, item | +When "$who assigns '$item' to the first line" do |who, item| step "#{who} assigns '#{item}' to line 0" end -When "$who tries to assign '$item' to the first line" do | who,item | +When "$who tries to assign '$item' to the first line" do |who, item| step "#{who} tries to assign '#{item}' to line 0" end -When "$who assigns '$item' to line $number" do | who, item, number | +When "$who assigns '$item' to line $number" do |who, item, number| step "#{who} tries to assign '#{item}' to line #{number}" step "#{who} should not see a flash error" end @@ -88,12 +86,12 @@ expect(@contract.nil?).to be false end -Then /^he sees ([0-9]+) contract line(s?) for all approved order lines$/ do | size, s | +Then /^he sees ([0-9]+) contract line(s?) for all approved order lines$/ do |size, s| expect(@contract.reservations.size).to eq size.to_i end Then 'the total number of contracts is $n_contracts' do |n_contracts| - expect(Contract.count).to eq n_contracts.to_i + expect(Contract.count).to eq n_contracts.to_i end Then /^he should (.*)see a flash error$/ do |shouldNot| @@ -129,7 +127,7 @@ within '#list_table' do all('tr').each do |row| if row.text =~ /#{person.to_s}/ - row.find('td.buttons', match: :first).find('a', text: /.*#{button}.*/i).click + row.find('td.buttons', match: :first).find('a', text: /.*#{button}.*/).click end end end diff --git a/features/step_definitions/inventory_steps.rb b/features/step_definitions/inventory_steps.rb index 3106204bb6..89807bb768 100644 --- a/features/step_definitions/inventory_steps.rb +++ b/features/step_definitions/inventory_steps.rb @@ -17,9 +17,7 @@ Given(/^(\d+) inventory pool(s?)$/) do |size, plural| InventoryPool.delete_all - size.to_i.times do |i| - LeihsFactory.create_inventory_pool(name: (i + 1)) - end + size.to_i.times { |i| LeihsFactory.create_inventory_pool(name: (i + 1)) } @inventory_pools = InventoryPool.all expect(@inventory_pools.size).to eq size.to_i # default inventory pool @@ -58,9 +56,7 @@ Then "the label of the direct children are '$labels'" do |labels| @category_labels = @category.children.map { |c| c.label(@category.id) } - labels.split(',').each do |l| - expect(@category_labels.include?(l)).to be true - end + labels.split(',').each { |l| expect(@category_labels.include?(l)).to be true } end ############################################### @@ -70,9 +66,7 @@ @model = LeihsFactory.create_model(product: model) end -When(/^I register a new model '([^']*)'$/) do |model| - step "a model '#{model}' exists" -end +When(/^I register a new model '([^']*)'$/) { |model| step "a model '#{model}' exists" } Given "the model '$model' belongs to the category '$category'" do |model, category| @model = Model.find_by_name(model) @@ -93,14 +87,13 @@ # Given "$number items of model '$model' exist" do |number, model| Given(/(\d+) item(s?) of model '(.+)' exist(s?)/) do |number, plural1, model, plural2| @model = LeihsFactory.create_model(product: model) - number.to_i.times do |i| - FactoryGirl.create(:item, owner: @inventory_pool, model: @model) - end + number.to_i.times { |i| FactoryGirl.create(:item, owner: @inventory_pool, model: @model) } end # rubocop:disable Metrics/ParameterLists -Given(/^(a?n? ?)item(s?) '([^']*)' of model '([^']*)' exist(s?)( only)?$/)\ - do |particle, plural, inventory_codes, model, plural2, only| +Given( + /^(a?n? ?)item(s?) '([^']*)' of model '([^']*)' exist(s?)( only)?$/ +) do |particle, plural, inventory_codes, model, plural2, only| Item.delete_all if only @model = LeihsFactory.create_model(product: model) @@ -120,21 +113,20 @@ end Given '$number items of this model exist' do |number| - number.to_i.times do |i| - FactoryGirl.create(:item, owner: @inventory_pool, model: @model) - end + number.to_i.times { |i| FactoryGirl.create(:item, owner: @inventory_pool, model: @model) } @model = Model.find(@model.id) end -Given(/^(\w+) item(s?) of that model exist(s?)/) \ -do |number, plural, plural2| +Given(/^(\w+) item(s?) of that model exist(s?)/) do |number, plural, plural2| number = to_number(number) step "#{number} items of this model exist" end Given 'we have items with the following inventory_codes:' do |inventory_codes_table| inventory_codes_table.hashes.each do |hash| - FactoryGirl.create(:item, owner: @inventory_pool, model: @model, inventory_code: hash[:inventory_code]) + FactoryGirl.create( + :item, owner: @inventory_pool, model: @model, inventory_code: hash[:inventory_code] + ) end end diff --git a/features/step_definitions/login_steps.rb b/features/step_definitions/login_steps.rb index 23624f7930..4d549b1122 100644 --- a/features/step_definitions/login_steps.rb +++ b/features/step_definitions/login_steps.rb @@ -1,4 +1,4 @@ -Given "a $role for inventory pool '$ip_name' logs in as '$who'" do | role, ip_name, who | +Given "a $role for inventory pool '$ip_name' logs in as '$who'" do |role, ip_name, who| step "a #{role} '#{who}' for inventory pool '#{ip_name}'" step "I log in as '#{who}' with password 'pass'" # use default pw @last_manager_login_name = who @@ -6,7 +6,7 @@ # This does NOT go through the UI. It simply logs in the user. # for 99% of our Cucumber scenarios, we don't need the UI at all! -Given "a $role for inventory pool '$ip_name' is logged in as '$who'" do | role, ip_name, who | +Given "a $role for inventory pool '$ip_name' is logged in as '$who'" do |role, ip_name, who| step "a #{role} '#{who}' for inventory pool '#{ip_name}'" step "I am logged in as '#{who}' with password 'foobar'" @last_manager_login_name = who @@ -14,21 +14,22 @@ Given "I am logged in as '$username' with password '$password'" do |username, password| @current_user = User.where(login: username.downcase).first - I18n.locale = if @current_user.language then @current_user.language.locale_name.to_sym else Language.default_language end + I18n.locale = + @current_user.language ? @current_user.language.locale_name.to_sym : Language.default_language @current_inventory_pool = @current_user.inventory_pools.managed.first case Capybara.current_driver - when /selenium/ - visit '/' - fill_in 'email', with: @current_user.email - click_on _('Login') - when :rack_test - step "I log in as '%s' with password '%s'" % [username, password] + when /selenium/ + visit '/' + fill_in 'email', with: @current_user.email + click_on _('Login') + when :rack_test + step "I log in as '%s' with password '%s'" % [username, password] end end -Given "I log in as a $role for inventory pool '$ip_name'$with_access_level" do |role, ip_name,with_access_level| - # use default user name - step "a #{role} 'inv_man_0' for inventory pool '#{ip_name}'#{with_access_level}" +Given "I log in as a $role for inventory pool '$ip_name'$with_access_level" do |role, ip_name, with_access_level| + step "a #{# use default user name + role} 'inv_man_0' for inventory pool '#{ip_name}'#{with_access_level}" step "I log in as 'inv_man_0' with password 'pass'" # use default pw @last_manager_login_name = 'inv_man_0' @@ -41,8 +42,8 @@ post sign_in_path, { email: @current_user.email } end -Given /(his|her) password is '([^']*)'$/ do |foo,password| - LeihsFactory.create_db_auth( login: @user.login, password: password) +Given /(his|her) password is '([^']*)'$/ do |foo, password| + LeihsFactory.create_db_auth(login: @user.login, password: password) end When 'I log in as the admin' do @@ -61,12 +62,12 @@ When /^I am redirected to the "([^"]*)" section$/ do |section_name| case section_name - when 'Admin' - within '.topbar' do - find('.navbar-right .dropdown-toggle', text: _(section_name)) - end - else - find('nav#topbar .topbar-navigation .active', match: :prefer_exact, text: _(section_name)) + when 'Admin' + within '.topbar' do + find('.navbar-right .dropdown-toggle', text: _(section_name)) + end + else + find('nav#topbar .topbar-navigation .active', match: :prefer_exact, text: _(section_name)) end end @@ -74,8 +75,9 @@ step 'I make sure I am logged out' @current_user = User.where(login: persona.downcase).first fill_in :email, with: @current_user.email - click_on "Login" - I18n.locale = if @current_user.language then @current_user.language.locale_name.to_sym else Language.default_language end + click_on 'Login' + I18n.locale = + @current_user.language ? @current_user.language.locale_name.to_sym : Language.default_language step 'I visit the homepage' - expect(page).to have_content @current_user.lastname + expect(page).to have_content @current_user.lastname end diff --git a/features/step_definitions/mail_management_steps.rb b/features/step_definitions/mail_management_steps.rb index 632d81848f..e81d2b72a3 100644 --- a/features/step_definitions/mail_management_steps.rb +++ b/features/step_definitions/mail_management_steps.rb @@ -7,7 +7,7 @@ Then '$email receives an email' do |email| expect(ActionMailer::Base.deliveries.size).to eq 1 - @mail = ActionMailer::Base.deliveries[0] + @mail = ActionMailer::Base.deliveries[0] # ActiveMailer upcases the first letter?! expect(@mail.to[0].downcase).to eq email.downcase ActionMailer::Base.deliveries.clear diff --git a/features/step_definitions/mail_templates_steps.rb b/features/step_definitions/mail_templates_steps.rb index 5326e175f5..4a277c2e45 100644 --- a/features/step_definitions/mail_templates_steps.rb +++ b/features/step_definitions/mail_templates_steps.rb @@ -1,62 +1,86 @@ -Then(/^the default (.*) exists in the database for a given (.*) and all languages$/) do |template_name, type| +Then( + /^the default (.*) exists in the database for a given (.*) and all languages$/ +) do |template_name, type| Language.all.each do |language| - mt = MailTemplate.find_by(is_template_template: true, - type: type, - name: template_name, - language_id: language.id) + mt = + MailTemplate.find_by( + is_template_template: true, type: type, name: template_name, language_id: language.id + ) expect(mt).to be end name_count = MailTemplate.select('DISTINCT(name)').count language_count = Language.count - expect(MailTemplate.where(is_template_template: true).count).to be == (name_count * language_count) + expect(MailTemplate.where(is_template_template: true).count).to be == + (name_count * language_count) end -When(/^I specify a mail template for the (.*) action (for the whole system|in the current inventory pool) for each active language$/) do |template_name, scope| +When( + / + ^I specify a mail template for the (.*) action (for the whole system|in the current inventory pool) for each active language$ + / +) do |template_name, scope| case scope - when 'for the whole system' - visit '/admin/mail_templates' - find('table tr', text: /^#{template_name}/).find('.btn', text: _('Edit')).click - when 'in the current inventory pool' - visit "/manage/#{@current_inventory_pool.id}/mail_templates" - selector1 = '.list-of-lines .line-col.col2of5' - selector2 = '.button' - find(selector1, text: /^#{template_name}$/).find(:xpath, './..').find(selector2, text: _('Edit')).click + when 'for the whole system' + visit '/admin/mail_templates' + find('table tr', text: /^#{template_name}/).find('.btn', text: _('Edit')).click + when 'in the current inventory pool' + visit "/manage/#{@current_inventory_pool.id}/mail_templates" + selector1 = '.list-of-lines .line-col.col2of5' + selector2 = '.button' + find(selector1, text: /^#{template_name}$/).find(:xpath, './..').find( + selector2, text: _('Edit') + ) + .click end step 'I land on the mail templates edit page' end -Then(/^the template (.*) is saved for the (whole system|current inventory pool) for each active language$/) do |template_name, scope| - inventory_pool_id = case scope - when 'whole system' - nil - when 'current inventory pool' - @current_inventory_pool.id - end +Then( + / + ^the template (.*) is saved for the (whole system|current inventory pool) for each active language$ + / +) do |template_name, scope| + inventory_pool_id = + case scope + when 'whole system' + nil + when 'current inventory pool' + @current_inventory_pool.id + end Language.active_languages.each do |language| - mt = MailTemplate.find_by(inventory_pool_id: inventory_pool_id, - name: template_name.gsub(' ', '_'), - language: language, - format: 'text') + mt = + MailTemplate.find_by( + inventory_pool_id: inventory_pool_id, + name: template_name.gsub(' ', '_'), + language: language, + format: 'text' + ) expect(mt).not_to be_nil end end -Given(/^I have a contract with deadline (yesterday|tomorrow)( for the inventory pool "(.*?)")?$/) do |day, arg1, inventory_pool_name| - @visit = if arg1 - inventory_pool = InventoryPool.find_by(name: inventory_pool_name) - @current_user.visits.where(inventory_pool_id: inventory_pool) - else - @current_user.visits - end.take_back.first +Given( + /^I have a contract with deadline (yesterday|tomorrow)( for the inventory pool "(.*?)")?$/ +) do |day, arg1, inventory_pool_name| + @visit = + if arg1 + inventory_pool = InventoryPool.find_by(name: inventory_pool_name) + @current_user.visits.where(inventory_pool_id: inventory_pool) + else + @current_user.visits + end + .take_back + .first expect(@visit).not_to be_nil - sign = case day - when 'yesterday' - :+ - when 'tomorrow' - :- - end + sign = + case day + when 'yesterday' + :+ + when 'tomorrow' + :- + end Dataset.back_to_date(@visit.date.send(sign, 1.day)) end @@ -68,35 +92,51 @@ expect(ActionMailer::Base.deliveries.count).to be > 0 end -Then(/^I receive an email formatted according to the (reminder|deadline_soon_reminder) mail template$/) do |template_name| +Then( + /^I receive an email formatted according to the (reminder|deadline_soon_reminder) mail template$/ +) do |template_name| language = Language.find_by(locale_name: @current_user.language.locale_name) - sent_mails = ActionMailer::Base.deliveries.select { |m| m.to.include?(@current_user.email) and m.from.include?(@visit.inventory_pool.email) } - sent_mails = sent_mails.select do |m| - m.subject == case template_name - when 'reminder' - _('[leihs] Reminder') - when 'deadline_soon_reminder' - _('[leihs] Some items should be returned tomorrow') - end - end + sent_mails = + ActionMailer::Base.deliveries.select do |m| + m.to.include?(@current_user.email) and m.from.include?(@visit.inventory_pool.email) + end + sent_mails = + sent_mails.select do |m| + m.subject == + case template_name + when 'reminder' + _('[leihs] Reminder') + when 'deadline_soon_reminder' + _('[leihs] Some items should be returned tomorrow') + end + end expect(sent_mails.size).to eq 1 sent_mail = sent_mails.first - template = MailTemplate.find_by!(inventory_pool_id: @visit.inventory_pool_id, - name: template_name, - language: language, - format: 'text') - variables = MailTemplate.liquid_variables_for_user(@current_user, @visit.inventory_pool, @visit.reservations) + template = + MailTemplate.find_by!( + inventory_pool_id: @visit.inventory_pool_id, + name: template_name, + language: language, + format: 'text' + ) + variables = + MailTemplate.liquid_variables_for_user( + @current_user, @visit.inventory_pool, @visit.reservations + ) expect(sent_mail.body.to_s).to eq Liquid::Template.parse(template.body).render(variables) end Given(/^the (reminder) mail template looks like$/) do |template_name, string| language = Language.find_by(locale_name: @current_user.language.locale_name) - mt = MailTemplate.find_or_initialize_by(inventory_pool_id: @visit.inventory_pool_id, - name: template_name.gsub(' ', '_'), - language: language, - format: 'text') + mt = + MailTemplate.find_or_initialize_by( + inventory_pool_id: @visit.inventory_pool_id, + name: template_name.gsub(' ', '_'), + language: language, + format: 'text' + ) mt.update_attributes(body: string) end @@ -107,7 +147,10 @@ def reset_language_for_current_user def get_reminder_for_visit(visit) reset_language_for_current_user - sent_mails = ActionMailer::Base.deliveries.select { |m| m.to.include?(@current_user.email) and m.from.include?(visit.inventory_pool.email) } + sent_mails = + ActionMailer::Base.deliveries.select do |m| + m.to.include?(@current_user.email) and m.from.include?(visit.inventory_pool.email) + end sent_mails = sent_mails.select { |m| m.subject == _('[leihs] Reminder') } expect(sent_mails.size).to eq 1 sent_mails.first @@ -124,43 +167,61 @@ def get_reminder_for_visit(visit) expect(@current_user.reload.language.locale_name).to eq locale_name end -When(/^one of my submitted orders to an inventory pool without custom approved mail templates get approved$/) do +When( + / + ^one of my submitted orders to an inventory pool without custom approved mail templates get approved$ + / +) do expect(ActionMailer::Base.deliveries.count).to eq 0 - @contract = @current_user.orders.submitted.detect { |c| c.approvable? } + @contract = @current_user.orders.submitted.detect(&:approvable?) @contract.approve(Faker::Lorem.sentence) expect(ActionMailer::Base.deliveries.count).to be > 0 end -Then(/^I receive an approved mail based on the system\-wide template for the language "(.*?)"$/) do |locale_name| +Then( + /^I receive an approved mail based on the system\-wide template for the language "(.*?)"$/ +) do |locale_name| language = Language.find_by(locale_name: locale_name) - sent_mails = ActionMailer::Base.deliveries.select { |m| m.to.include?(@current_user.email) and m.from.include?(@contract.inventory_pool.email) } + sent_mails = + ActionMailer::Base.deliveries.select do |m| + m.to.include?(@current_user.email) and m.from.include?(@contract.inventory_pool.email) + end sent_mails = sent_mails.select { |m| m.subject == _('[leihs] Reservation Confirmation') } expect(sent_mails.size).to eq 1 sent_mail = sent_mails.first - template = MailTemplate.find_by(inventory_pool_id: nil, - name: 'approved', - language: language, - format: 'text').body + template = + MailTemplate.find_by( + inventory_pool_id: nil, name: 'approved', language: language, format: 'text' + ) + .body variables = MailTemplate.liquid_variables_for_order(@contract) expect(sent_mail.body.to_s).to eq Liquid::Template.parse(template).render(variables) end Then(/^I receive a reminder in "(.*?)"$/) do |locale_name| - variables = MailTemplate.liquid_variables_for_user(@current_user, @visit.inventory_pool, @visit.reservations) + variables = + MailTemplate.liquid_variables_for_user( + @current_user, @visit.inventory_pool, @visit.reservations + ) language = Language.find_by!(locale_name: locale_name) - template = MailTemplate.find_by!(inventory_pool_id: @visit.inventory_pool_id, - name: :reminder, - language: language, - format: 'text') + template = + MailTemplate.find_by!( + inventory_pool_id: @visit.inventory_pool_id, + name: :reminder, + language: language, + format: 'text' + ) string = Liquid::Template.parse(template.body).render(variables) sent_mail = get_reminder_for_visit(@visit) expect(sent_mail.body.to_s).to eq string end -When(/^I edit the (reminder) with the "(.*?)" template in "(.*?)"$/) do |template_name, body, locale_name| +When( + /^I edit the (reminder) with the "(.*?)" template in "(.*?)"$/ +) do |template_name, body, locale_name| selector = @current_inventory_pool ? '.row.margin-vertical-s' : '.form-group' find(selector, text: locale_name).find("textarea[name='mail_templates[][body]']").set body end @@ -168,21 +229,33 @@ def get_reminder_for_visit(visit) Then(/^I land on the mail templates edit page$/) do find("form button[type='submit']", text: _('Save %s') % _('Mail Templates')) Language.active_languages.each do |language| - find("input[name='mail_templates[][language]'][type='hidden'][value='#{language.locale_name}']", visible: false) + find( + "input[name='mail_templates[][language]'][type='hidden'][value='#{language.locale_name}']", + visible: false + ) end end -Then(/^the failing (reminder) mail template in "(.*?)" is highlighted in red$/) do |template_name, locale_name| +Then( + /^the failing (reminder) mail template in "(.*?)" is highlighted in red$/ +) do |template_name, locale_name| selector = @current_inventory_pool ? '.row.margin-vertical-s' : '.form-group' - expect(find(selector, text: locale_name).native.css_value('background-color')).to eq 'rgba(255, 176, 176, 1)' + expect( + find(selector, text: locale_name).native.css_value('background-color') + ).to eq 'rgba(255, 176, 176, 1)' end -Then(/^the failing (reminder) mail template in "(.*?)" is not persisted with the "(.*?)" template$/) do |template_name, locale_name, body| +Then( + /^the failing (reminder) mail template in "(.*?)" is not persisted with the "(.*?)" template$/ +) do |template_name, locale_name, body| language = Language.find_by(locale_name: locale_name) - template = MailTemplate.find_or_initialize_by(inventory_pool_id: @current_inventory_pool.try(:id), - name: template_name.gsub(' ', '_'), - language: language, - format: 'text') + template = + MailTemplate.find_or_initialize_by( + inventory_pool_id: @current_inventory_pool.try(:id), + name: template_name.gsub(' ', '_'), + language: language, + format: 'text' + ) expect(template.body).not_to eq body end @@ -190,9 +263,7 @@ def get_reminder_for_visit(visit) visit "/manage/#{@current_inventory_pool.id}/mail_templates" end -Then(/^I am redirected to the login page$/) do - find('#login-form') -end +Then(/^I am redirected to the login page$/) { find('#login-form') } Then(/^I see a list of mail templates$/) do find('nav .active', text: _('Mail Templates')) diff --git a/features/step_definitions/manage/acknowledge/add_item_steps.rb b/features/step_definitions/manage/acknowledge/add_item_steps.rb index 36a0e5fc22..0691a72113 100644 --- a/features/step_definitions/manage/acknowledge/add_item_steps.rb +++ b/features/step_definitions/manage/acknowledge/add_item_steps.rb @@ -1,7 +1,7 @@ When /^I add a model by typing in the inventory code of an item of that model to the quick add$/ do - @item ||= @current_inventory_pool.items.detect {|x| not x.inventory_code.blank? } + @item ||= @current_inventory_pool.items.detect { |x| nx.inventory_code.blank? } find('#add-input input').set @item.inventory_code - find("button[type='submit'][title='#{_("Add")}']").click + find("button[type='submit'][title='#{_('Add')}']").click find('.line', match: :prefer_exact, text: @item.model.name) end @@ -31,15 +31,13 @@ When /^I start to type the name of a model( which is not yet in the contract)?$/ do |arg1| items = @current_inventory_pool.items.borrowable - @item = if arg1 - items.detect {|i| not @contract.models.include? i.model} - else - items.first - end + @item = arg1 ? items.detect { |i| n@contract.models.include? i.model } : items.first find('#add-input input').set @item.model.name[0..-2] end -When /^I add a model to the acknowledge which is already existing in the selected date range by providing an inventory code$/ do +When / + ^I add a model to the acknowledge which is already existing in the selected date range by providing an inventory code$ + / do @line = @contract.reservations.first @old_lines_count = @contract.reservations.count @model = @line.model @@ -54,7 +52,7 @@ end Then /^the existing line quantity is not increased$/ do - old_quantity = @line.quantity + old_quantity = @line.quantity expect(@line.reload.quantity).to eq old_quantity end @@ -68,7 +66,11 @@ find('.line', match: :prefer_exact, text: @model.name) reservations = @contract.reload.reservations.where(model_id: @model) expect(all('.line').count).to eq @line_el_count - expect(all('.line', text: @model.name).sum{|l| l.find('div:nth-child(3) > span:nth-child(1)').text.to_i}).to eq reservations.count + expect( + all('.line', text: @model.name).sum do |l| + l.find('div:nth-child(3) > span:nth-child(1)').text.to_i + end + ).to eq reservations.count expect(reservations.count).to eq reservations.to_a.sum(&:quantity) end end @@ -76,11 +78,12 @@ Given /^I search for a model with default dates and note the current availability$/ do init_start_date = Date.parse find('#add-start-date').value av = nil - @model = @current_inventory_pool.models.detect do |model| - av = model.availability_in(@current_inventory_pool) - av.changes.keys.last > init_start_date - end - @new_start_date = av.changes.select{|k, v| k > init_start_date }.keys.first + @model = + @current_inventory_pool.models.detect do |model| + av = model.availability_in(@current_inventory_pool) + av.changes.keys.last > init_start_date + end + @new_start_date = av.changes.select { |k, v| k > init_start_date }.keys.first find('#add-input input').set @model.name el = find('.ui-autocomplete .row', match: :prefer_exact, text: @model.name) @init_aval = el.find('div.col1of4:nth-child(2) > div:nth-child(1)').text @@ -107,7 +110,11 @@ Then (/^the model's availability has changed$/) do wait_until(3) do - @changed_aval = find('.row a', match: :prefer_exact, text: @model.name).find('div.col1of4:nth-child(2) > div:nth-child(1)').text + @changed_aval = + find('.row a', match: :prefer_exact, text: @model.name).find( + 'div.col1of4:nth-child(2) > div:nth-child(1)' + ) + .text @changed_aval.slice(0) != @init_aval.slice(0) end end @@ -118,13 +125,9 @@ find('#add-input input').click end -When(/^I leave the autocomplete$/) do - find('body').click -end +When(/^I leave the autocomplete$/) { find('body').click } -When(/^I reenter the autocomplete$/) do - find('#add-input input').click -end +When(/^I reenter the autocomplete$/) { find('#add-input input').click } Then(/^I should still see the model in the resultlist$/) do find('.ui-autocomplete a', text: @model.name[0..-2], match: :first) @@ -140,16 +143,12 @@ end end else - # when selector not present, then no matched results + end + # when selector not present, then no matched results end When(/^I enter a model name( which is not related to my current pool)?$/) do |arg1| - model = if arg1 - Model.all - @current_inventory_pool.models - else - Model.all - end.first + model = arg1 ? Model.all - @current_inventory_pool.models : Model.all.first find('#assign-or-add-input input').set model.name[0..-2] end - diff --git a/features/step_definitions/manage/acknowledge/approve_steps.rb b/features/step_definitions/manage/acknowledge/approve_steps.rb index 21e67c8940..afb353358b 100644 --- a/features/step_definitions/manage/acknowledge/approve_steps.rb +++ b/features/step_definitions/manage/acknowledge/approve_steps.rb @@ -1,20 +1,19 @@ # -*- encoding : utf-8 -*- Given(/^I navigate to the (open orders|hand over visits|take back visits)$/) do |arg1| - if current_path != manage_daily_view_path(@current_inventory_pool) - step 'I open the daily view' - end - - s = case arg1 - when 'open orders' - _('Open Orders') - when 'hand over visits' - _('Hand Overs') - when 'take back visits' - _('Take Backs') - else - raise - end + step 'I open the daily view' if current_path != manage_daily_view_path(@current_inventory_pool) + + s = + case arg1 + when 'open orders' + _('Open Orders') + when 'hand over visits' + _('Hand Overs') + when 'take back visits' + _('Take Backs') + else + raise + end find('.button', text: s).click end @@ -26,21 +25,24 @@ end Then(/^I see a link to the hand over process of that order$/) do - find(".line[data-id='#{@contract.id}'] .line-actions a[href='#{manage_hand_over_path(@current_inventory_pool, @contract.user)}']", text: _('Hand Over')) + find( + ".line[data-id='#{@contract.id}'] .line-actions a[href='#{manage_hand_over_path( + @current_inventory_pool, @contract.user + )}']", + text: _('Hand Over') + ) end Given /^I try to approve a contract that has problems$/ do - @contract = @current_inventory_pool.orders.submitted.detect do |o| - not o.approvable? and not o.to_be_verified? - end + @contract = + @current_inventory_pool.orders.submitted.detect { |o| no.approvable? and no.to_be_verified? } step 'I quick approve a submitted order' find('.modal') end Then /^I got an information that this contract has problems$/ do error = find('.modal .row.emboss.red') - expect(error.text) - .to be == @contract.errors.full_messages.join(' ') + expect(error.text).to be == @contract.errors.full_messages.join(' ') end When /^I approve anyway$/ do diff --git a/features/step_definitions/manage/acknowledge/delete_lines_steps.rb b/features/step_definitions/manage/acknowledge/delete_lines_steps.rb index 80091392d7..b73e5a91dd 100644 --- a/features/step_definitions/manage/acknowledge/delete_lines_steps.rb +++ b/features/step_definitions/manage/acknowledge/delete_lines_steps.rb @@ -18,9 +18,7 @@ When /^I delete multiple reservations of this contract$/ do step 'I add a model that is not already part of that contract' - all('input[data-select-line]:checked').each do |checkbox| - checkbox.click - end + all('input[data-select-line]:checked').each(&:click) step 'I select two reservations' find('.multibutton [data-selection-enabled] + .dropdown-holder').click find('a', text: _('Delete Selection')).click @@ -47,7 +45,11 @@ end Then /^I got an error message that not all reservations can be deleted$/ do - find('#flash .error', text: _('You cannot delete all reservations of an order. Perhaps you want to reject it instead?')) + find( + '#flash .error', + text: + _('You cannot delete all reservations of an order. Perhaps you want to reject it instead?') + ) end Then /^none of the reservations are deleted$/ do @@ -66,9 +68,7 @@ end Then(/^all reservations of that hand over are deleted$/) do - within(".line[data-id='#{@visit.id}']") do - find('.line-actions', text: _('Deleted')) - end + within(".line[data-id='#{@visit.id}']") { find('.line-actions', text: _('Deleted')) } reloaded_visit = Visit.where(id: @visit.id).first expect(reloaded_visit).to be_nil @visit_line_ids.each do |line_id| diff --git a/features/step_definitions/manage/acknowledge/edit_order_line_steps.rb b/features/step_definitions/manage/acknowledge/edit_order_line_steps.rb index 8839f8c9fd..dccfbd11db 100644 --- a/features/step_definitions/manage/acknowledge/edit_order_line_steps.rb +++ b/features/step_definitions/manage/acknowledge/edit_order_line_steps.rb @@ -1,8 +1,20 @@ # -*- encoding : utf-8 -*- -When(/^I open a contract for acknowledgement( with more then one line)?(, whose start date is not in the past)?$/) do |arg1, arg2| - contracts = @current_inventory_pool.orders.submitted.select { |o| not o.user.suspended?(@current_inventory_pool) } - contracts = contracts.select { |c| c.reservations.size > 1 and c.reservations.map(&:model_id).uniq.size > 1 } if arg1 +When( + / + ^I open a contract for acknowledgement( with more then one line)?(, whose start date is not in the past)?$ + / +) do |arg1, arg2| + contracts = + @current_inventory_pool.orders.submitted.select do |o| + no.user.suspended?(@current_inventory_pool) + end + if arg1 + contracts = + contracts.select do |c| + c.reservations.size > 1 and c.reservations.map(&:model_id).uniq.size > 1 + end + end contracts = contracts.select { |c| c.min_date >= Time.zone.today } if arg2 @contract = contracts.first @@ -21,17 +33,20 @@ end When(/^I edit the timerange of the selection$/) do - if page.has_selector?('.button.green[data-hand-over-selection]') or page.has_selector?('.button.green[data-take-back-selection]') + if page.has_selector?('.button.green[data-hand-over-selection]') or + page.has_selector?('.button.green[data-take-back-selection]') step 'I edit all reservations' else - find(".multibutton [data-selection-enabled][data-edit-lines='selected-lines']", text: _('Edit Selection')).click + find( + ".multibutton [data-selection-enabled][data-edit-lines='selected-lines']", + text: _('Edit Selection') + ) + .click end step 'I see the booking calendar' end -When(/^I save the booking calendar$/) do - find('#submit-booking-calendar:not(:disabled)').click -end +When(/^I save the booking calendar$/) { find('#submit-booking-calendar:not(:disabled)').click } Then(/^the booking calendar is( not)? closed$/) do |arg1| b = !arg1 @@ -44,20 +59,19 @@ if @contract @contract.reservations.first else - @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).first.reservations.first + @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).first + .reservations + .first + end + @line_element = + begin + find(".line[data-ids*='#{@line.id}']", match: :first) + rescue StandardError + find(".line[data-id='#{@line.id}']", match: :first) end - @line_element = begin - find(".line[data-ids*='#{@line.id}']", match: :first) - rescue - find(".line[data-id='#{@line.id}']", match: :first) - end step 'I open the booking calendar for this line' @new_start_date = - if @line.start_date + 1.day < Time.zone.today - Time.zone.today - else - @line.start_date + 1.day - end + @line.start_date + 1.day < Time.zone.today ? Time.zone.today : @line.start_date + 1.day expect(has_selector?('.fc-widget-content .fc-day-number')).to be true get_fullcalendar_day_element(@new_start_date).click sleep 1 @@ -84,7 +98,10 @@ end When(/^I decrease a submitted contract reservations quantity$/) do - @line_element = all('.line[data-ids]').detect { |l| l.find('div:nth-child(3) > span:nth-child(1)').text.to_i > 1 } + @line_element = + all('.line[data-ids]').detect do |l| + l.find('div:nth-child(3) > span:nth-child(1)').text.to_i > 1 + end within @line_element do @line_model_name = find('.col6of10 strong').text @new_quantity = find('div:nth-child(3) > span:nth-child(1)').text.to_i - 1 @@ -100,10 +117,14 @@ elsif @order @order.reservations.first else - @hand_over = @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).first + @hand_over = + @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).first @hand_over.reservations.first end - @total_quantity = (@contract || @order || @hand_over).reservations.where(model_id: @line.model_id).to_a.sum(&:quantity) + @total_quantity = + (@contract || @order || @hand_over).reservations.where(model_id: @line.model_id).to_a.sum( + &:quantity + ) @new_quantity = @line.quantity + 1 @line_element = find(".line[data-id='#{@line.id}']") end @@ -119,8 +140,11 @@ Then(/^the contract line was duplicated$/) do expect( - (@line.contract || @contract || @order || @hand_over.reload) - .reservations.where(model_id: @line.model_id).to_a.sum(&:quantity) + (@line.contract || @contract || @order || @hand_over.reload).reservations.where( + model_id: @line.model_id + ) + .to_a + .sum(&:quantity) ).to eq @total_quantity + 1 end @@ -136,9 +160,13 @@ When(/^I select two reservations$/) do @line1 = @contract.reservations.first - find('.line', match: :prefer_exact, text: @line1.model.name).find('input[type=checkbox]').set(true) + find('.line', match: :prefer_exact, text: @line1.model.name).find('input[type=checkbox]').set( + true + ) @line2 = @contract.reservations.detect { |l| l.model != @line1.model } - find('.line', match: :prefer_exact, text: @line2.model.name).find('input[type=checkbox]').set(true) + find('.line', match: :prefer_exact, text: @line2.model.name).find('input[type=checkbox]').set( + true + ) end When(/^I change the time range for multiple reservations$/) do @@ -164,11 +192,7 @@ end When(/^I edit one of the selected reservations$/) do - all('.line').each do |line| - if line.find('input', match: :first).checked? - @line_element = line - end - end + all('.line').each { |line| @line_element = line if line.find('input', match: :first).checked? } step 'I open the booking calendar for this line' end @@ -176,17 +200,20 @@ expect(has_selector?('#booking-calendar .fc-day-content')).to be true end -When(/^I change the time range for multiple reservations that have quantity bigger then (\d+)$/) do |arg1| +When( + /^I change the time range for multiple reservations that have quantity bigger then (\d+)$/ +) do |arg1| expect(has_selector?('.line[data-ids]')).to be true sleep 2 all_ids = all('.line[data-ids]').to_a.map { |x| x['data-ids'] } - @models_quantities = all_ids.map do |ids| - @line_element = find(".line[data-ids='#{ids}']") - step 'I increase a submitted contract reservations quantity' - step 'the quantity of that submitted contract line is changed' - expect(@new_quantity).to be > arg1.to_i - { name: @line_model_name, quantity: @new_quantity } - end + @models_quantities = + all_ids.map do |ids| + @line_element = find(".line[data-ids='#{ids}']") + step 'I increase a submitted contract reservations quantity' + step 'the quantity of that submitted contract line is changed' + expect(@new_quantity).to be > arg1.to_i + { name: @line_model_name, quantity: @new_quantity } + end expect(@models_quantities.size).to be > 0 step 'I change the time range for multiple reservations' end diff --git a/features/step_definitions/manage/acknowledge/edit_purpose_steps.rb b/features/step_definitions/manage/acknowledge/edit_purpose_steps.rb index 76702dad04..05c6df7f7d 100644 --- a/features/step_definitions/manage/acknowledge/edit_purpose_steps.rb +++ b/features/step_definitions/manage/acknowledge/edit_purpose_steps.rb @@ -14,6 +14,5 @@ Then /^the contract's purpose is changed$/ do find('#purpose', text: @new_purpose) visit current_path - expect(@contract.reload.purpose.split(';').any? {|str| str == @new_purpose }) - .to be true + expect(@contract.reload.purpose.split(';').any? { |str| str == @new_purpose }).to be true end diff --git a/features/step_definitions/manage/acknowledge/reject_steps.rb b/features/step_definitions/manage/acknowledge/reject_steps.rb index d48ae799e3..f18c38112f 100644 --- a/features/step_definitions/manage/acknowledge/reject_steps.rb +++ b/features/step_definitions/manage/acknowledge/reject_steps.rb @@ -1,9 +1,7 @@ When /^I reject a contract$/ do - @contract = @current_inventory_pool.orders.submitted.detect do |o| - o.to_be_verified? - end + @contract = @current_inventory_pool.orders.submitted.detect(&:to_be_verified?) - step %Q(I uncheck the "No verification required" button) + step 'I uncheck the "No verification required" button' @daily_view_line = find(".line[data-id='#{@contract.id}']") within @daily_view_line do @@ -17,11 +15,7 @@ end Then /^I see a summary of that contract$/ do - within('.modal') do - unless @contract.purpose.blank? - find('p', text: @contract.purpose[0..25]) - end - end + within('.modal') { find('p', text: @contract.purpose[0..25]) unless @contract.purpose.blank? } end Then /^I can write a reason why I reject that contract$/ do @@ -29,24 +23,18 @@ end When /^I confirm the contract rejection$/ do - within('.modal') do - find('.button.red[type=submit]').click - end + within('.modal') { find('.button.red[type=submit]').click } step 'the modal is closed' end Then /^the contract is rejected$/ do sleep 1 - if @daily_view_line - within @daily_view_line do - find('.line-actions-column', text: _('Rejected')) - end - end + within @daily_view_line dofind('.line-actions-column', text: _('Rejected'))end if @daily_view_line expect(@contract.reload.state).to be == 'rejected' @contract.reservations.each do |line| if current_path == manage_contracts_path(@current_inventory_pool.id) - find(".line.row", text: @contract.user.name).find('.line-actions-column', text: _('Rejected')) + find('.line.row', text: @contract.user.name).find('.line-actions-column', text: _('Rejected')) end expect(line.reload.status).to eq :rejected end diff --git a/features/step_definitions/manage/add_line_steps.rb b/features/step_definitions/manage/add_line_steps.rb index ffdb439ea0..91430a0bfc 100644 --- a/features/step_definitions/manage/add_line_steps.rb +++ b/features/step_definitions/manage/add_line_steps.rb @@ -15,17 +15,18 @@ name = item.find('.col3of4 strong').text model = Model.find_by_name(name) av = model.availability_in(@current_inventory_pool) - max_available = av.maximum_available_in_period_for_groups(start_date, end_date, @customer.entitlement_group_ids) - max_available_in_total = av.maximum_available_in_period_summed_for_groups(start_date, end_date) - total_rentable = \ - model - .items - .where(inventory_pool_id: @current_inventory_pool) - .borrowable - .unretired - .count + max_available = + av.maximum_available_in_period_for_groups( + start_date, end_date, @customer.entitlement_group_ids + ) + max_available_in_total = + av.maximum_available_in_period_summed_for_groups(start_date, end_date) + total_rentable = + model.items.where(inventory_pool_id: @current_inventory_pool).borrowable.unretired.count availability_text = item.find('.col1of4 .row:nth-child(1)').text - expect(availability_text).to eq "#{max_available}(#{max_available_in_total})/#{total_rentable}" + expect( + availability_text + ).to eq "#{max_available}(#{max_available_in_total})/#{total_rentable}" end find('.row', match: :first) end diff --git a/features/step_definitions/manage/availability/allocating_steps.rb b/features/step_definitions/manage/availability/allocating_steps.rb index bc475c45cb..76eb5f67f7 100644 --- a/features/step_definitions/manage/availability/allocating_steps.rb +++ b/features/step_definitions/manage/availability/allocating_steps.rb @@ -1,10 +1,18 @@ -Given /^a list of changes\/availabilities$/ do - @model = @current_inventory_pool.models.max {|a,b| a.availability_in(@current_inventory_pool).changes.length <=> b.availability_in(@current_inventory_pool).changes.length} +Given %r{^a list of changes\/availabilities$} do + @model = + @current_inventory_pool.models.max do |a, b| + a.availability_in(@current_inventory_pool).changes.length <=> + b.availability_in(@current_inventory_pool).changes.length + end @reference = @model.availability_in(@current_inventory_pool).available_total_quantities end -When /^I request that list multiple times the allocation of the reservations should always be the same$/ do +When / + ^I request that list multiple times the allocation of the reservations should always be the same$ + / do 50.times do - expect(@reference.to_json).to eq @model.availability_in(@current_inventory_pool).available_total_quantities.to_json + expect(@reference.to_json).to eq @model.availability_in(@current_inventory_pool) + .available_total_quantities + .to_json end end diff --git a/features/step_definitions/manage/booking_calendar/availability_changes_steps.rb b/features/step_definitions/manage/booking_calendar/availability_changes_steps.rb index 1adfd296ab..26d5b99362 100644 --- a/features/step_definitions/manage/booking_calendar/availability_changes_steps.rb +++ b/features/step_definitions/manage/booking_calendar/availability_changes_steps.rb @@ -1,32 +1,42 @@ When /^I open a booking calendar to edit a singe line$/ do # high frequently booked model - @model = @current_inventory_pool.models.max {|a,b| a.availability_in(@current_inventory_pool).changes.length <=> b.availability_in(@current_inventory_pool).changes.length} - @order = @contract = @current_inventory_pool.orders.submitted.detect {|c| c.reservations.any? {|cl| cl.model_id == @model.id} } + @model = + @current_inventory_pool.models.max do |a, b| + a.availability_in(@current_inventory_pool).changes.length <=> + b.availability_in(@current_inventory_pool).changes.length + end + @order = + @contract = + @current_inventory_pool.orders.submitted.detect do |c| + c.reservations.any? { |cl| cl.model_id == @model.id } + end step 'I edit the order' @edited_line = find('.line', text: @model.name, match: :first) @edited_line.find('[data-edit-lines]').click find('.modal') end -Then /^I see all availabilities in that calendar, where the small number is the total quantity of that specific date$/ do +Then / + ^I see all availabilities in that calendar, where the small number is the total quantity of that specific date$ + / do within('.modal') do find('#booking-calendar .fc-widget-content', match: :first) # go to today - while(all('.fc-button-prev:not(.fc-state-disabled)').length != 0) - find('.fc-button-prev').click - end + find('.fc-button-prev').click while (all('.fc-button-prev:not(.fc-state-disabled)').length != 0) av = @model.availability_in(@current_inventory_pool) changes = av.available_total_quantities changes.each_with_index do |change, i| - current_calendar_date = Date.parse find('.fc-widget-content:not(.fc-other-month)', match: :first)['data-date'] + current_calendar_date = + Date.parse find('.fc-widget-content:not(.fc-other-month)', match: :first)['data-date'] current_change_date = change[0] - while current_calendar_date.month != current_change_date.month do + while current_calendar_date.month != current_change_date.month find('.fc-button-next').click - current_calendar_date = Date.parse find('.fc-widget-content:not(.fc-other-month)', match: :first)['data-date'] + current_calendar_date = + Date.parse find('.fc-widget-content:not(.fc-other-month)', match: :first)['data-date'] end # iterate days between this change and the next one - next_change = changes[i+1] + next_change = changes[i + 1] if next_change days_between_changes = (next_change[0] - change[0]).to_i @@ -34,12 +44,10 @@ last_month = next_date.month days_between_changes.times do + find('.fc-button-next').click if next_date.month != last_month - if next_date.month != last_month - find('.fc-button-next').click - end - - change_date_el = find(".fc-widget-content:not(.fc-other-month)[data-date='#{next_date.to_s(:db)}']") + change_date_el = + find(".fc-widget-content:not(.fc-other-month)[data-date='#{next_date.to_s(:db)}']") ####################################################################################################################### # check total, where the small number is the total quantity of that specific date @@ -54,12 +62,18 @@ ####################################################################################################################### # check selected partition/borrower quantity (big number) - quantity_for_borrower = av.maximum_available_in_period_summed_for_groups next_date, next_date, @contract.user.entitlement_group_ids + quantity_for_borrower = + av.maximum_available_in_period_summed_for_groups next_date, + next_date, + @contract.user.entitlement_group_ids # the quantity is considering only the partitions with groups we are member of (exclude soft overbookings) if change_date_el[:class].match('selected') != nil - x = change[2].select {|h| ([nil] + @contract.user.entitlement_group_ids).include? h[:group_id]} - y = x.flat_map {|h| h[:running_reservations] } + x = + change[2].select do |h| + ([nil] + @contract.user.entitlement_group_ids).include? h[:group_id] + end + y = x.flat_map { |h| h[:running_reservations] } quantity_to_restore = (y & @contract.reservations.pluck(:id)).size quantity_for_borrower += quantity_to_restore end diff --git a/features/step_definitions/manage/booking_calendar/closed_day_alert_steps.rb b/features/step_definitions/manage/booking_calendar/closed_day_alert_steps.rb index 58e289df8b..41ec10655b 100644 --- a/features/step_definitions/manage/booking_calendar/closed_day_alert_steps.rb +++ b/features/step_definitions/manage/booking_calendar/closed_day_alert_steps.rb @@ -2,40 +2,41 @@ next_closed_day = nil date = Date.today expect(has_selector?('td[data-date]')).to be true - if all("td[data-date='#{date}']").empty? - date = (date + 1.month).beginning_of_month - end + date = (date + 1.month).beginning_of_month if all("td[data-date='#{date}']").empty? while next_closed_day.nil? - next_date = @current_inventory_pool.next_open_date date+1.day - next_closed_day = (next_date - 1.day) if (next_date-date).to_i > 1 - date = date+1.day + next_date = @current_inventory_pool.next_open_date date + 1.day + next_closed_day = (next_date - 1.day) if (next_date - date).to_i > 1 + date = date + 1.day end get_fullcalendar_day_element(next_closed_day).click sleep 1 case date_target - when 'start' - find('#set-start-date', text: _('Start date')).click - when 'end' - find('#set-end-date', text: _('End date')).click + when 'start' + find('#set-start-date', text: _('Start date')).click + when 'end' + find('#set-end-date', text: _('End date')).click end end -Then /^the (start|end) date becomes red and I see a (closed|not possible|too early) day warning?$/ do |arg1, arg2| +Then / + ^the (start|end) date becomes red and I see a (closed|not possible|too early) day warning?$ + / do |arg1, arg2| within '.modal' do el = find(".fc-widget-content.closed.#{arg1}-date").native.style('background-color') # NOTE our red definition is #FF4C4D == rgba(255, 76, 77, 1) expect(el).to eq 'rgba(255, 76, 77, 1)' - s = case arg2 - when 'closed' - _("Inventory pool is closed on #{arg1} date") - when 'not possible' - _("Booking is no longer possible on this #{arg1} date") - when 'too early' - _('No orders are possible on this start date') - end + s = + case arg2 + when 'closed' + _("Inventory pool is closed on #{arg1} date") + when 'not possible' + _("Booking is no longer possible on this #{arg1} date") + when 'too early' + _('No orders are possible on this start date') + end find('.red', text: s) end end diff --git a/features/step_definitions/manage/booking_calendar/summary_of_lines_in_calendar_steps.rb b/features/step_definitions/manage/booking_calendar/summary_of_lines_in_calendar_steps.rb index 182c60c048..98f8e51008 100644 --- a/features/step_definitions/manage/booking_calendar/summary_of_lines_in_calendar_steps.rb +++ b/features/step_definitions/manage/booking_calendar/summary_of_lines_in_calendar_steps.rb @@ -1,13 +1,13 @@ -When /^I change the quantity( of the model in the calendar which leads to an overbooking)?$/ do |arg1| - n = if arg1 - @line.model.items.where(inventory_pool_id: @line.inventory_pool).count - else - 1 - end +When / + ^I change the quantity( of the model in the calendar which leads to an overbooking)?$ + / do |arg1| + n = arg1 ? @line.model.items.where(inventory_pool_id: @line.inventory_pool).count : 1 @new_quantity = find('#booking-calendar-quantity').value.to_i + n fill_in 'booking-calendar-quantity', with: @new_quantity end Then /^the specific line in the summary inside the calendar also updates its quantity$/ do - find('.modal .line', text: @edited_line.find('strong', match: :first).text).find('div.col1of10:nth-child(2) > span:nth-child(1)', text: @new_quantity) + find('.modal .line', text: @edited_line.find('strong', match: :first).text).find( + 'div.col1of10:nth-child(2) > span:nth-child(1)', text: @new_quantity + ) end diff --git a/features/step_definitions/manage/calendar_steps.rb b/features/step_definitions/manage/calendar_steps.rb index 3b11777eaf..699b36ad28 100644 --- a/features/step_definitions/manage/calendar_steps.rb +++ b/features/step_definitions/manage/calendar_steps.rb @@ -7,12 +7,12 @@ end Then /^I see the availability of models on weekdays as well as holidays and weekends$/ do - while all('.fc-widget-content.holiday').empty? do - find('.fc-button-next', match: :first).click - end + find('.fc-button-next', match: :first).click while all('.fc-widget-content.holiday').empty? expect(find('.fc-widget-content.holiday .fc-day-content div', match: :first).text).not_to eq '' find('.fc-widget-content.holiday .fc-day-content div', match: :first).text.to_i >= 0 - expect(find('.fc-widget-content.holiday .fc-day-content .total_quantity', match: :first).text).not_to eq '' + expect( + find('.fc-widget-content.holiday .fc-day-content .total_quantity', match: :first).text + ).not_to eq '' end When /^I open the booking calendar$/ do @@ -27,7 +27,7 @@ end Then /^there is no limit on augmenting the quantity, thus I can overbook$/ do - @size = @line.model.items.where(inventory_pool_id: @current_inventory_pool).size*2 + @size = @line.model.items.where(inventory_pool_id: @current_inventory_pool).size * 2 find('.modal').fill_in 'booking-calendar-quantity', with: @size #expect(find(".modal #booking-calendar-quantity").value.to_i).to eq @size end @@ -37,7 +37,12 @@ step 'the booking calendar is closed' case arg1 when 'order' - expect(@line.order.reservations.where(start_date: @line.start_date, end_date: @line.end_date, model_id: @line.model).size).to eq @size + expect( + @line.order.reservations.where( + start_date: @line.start_date, end_date: @line.end_date, model_id: @line.model + ) + .size + ).to eq @size when 'hand over' expect(@line.user.reservations.approved.where(model_id: @line.model).size).to be >= @size else @@ -49,7 +54,8 @@ step 'I close the flash message' find('.multibutton .green.dropdown-toggle').click - find(".multibutton .dropdown-item[data-edit-lines='selected-lines']", text: _('Edit Selection')).click + find(".multibutton .dropdown-item[data-edit-lines='selected-lines']", text: _('Edit Selection')) + .click end Then /^the list underneath the calendar shows the respective line as not available \(red\)$/ do diff --git a/features/step_definitions/manage/category_steps.rb b/features/step_definitions/manage/category_steps.rb index 4536a23161..3f61e91acb 100644 --- a/features/step_definitions/manage/category_steps.rb +++ b/features/step_definitions/manage/category_steps.rb @@ -9,24 +9,23 @@ find('#categories-index-view h1', text: _('List of Categories')) end - And /^I create a new category$/ do find('a', text: _('New Category')).click end - And /^I give the category a name$/ do @new_category_name = 'Neue Kategorie' find("input[name='category[name]']").set @new_category_name end - And /^I define parent categories and their names$/ do @parent_category = ModelGroup.where(name: 'Portabel').first @label_1 = 'Label 1' find("#categories input[data-type='autocomplete']").set @parent_category.name find('.ui-menu-item a', match: :first, text: @parent_category.name).click - find('#categories .list-of-lines .line', text: @parent_category.name).find("input[type='text']").set @label_1 + find('#categories .list-of-lines .line', text: @parent_category.name).find( + "input[type='text']" + ).set @label_1 end Then /^the category has been created with the specified name$/ do @@ -35,15 +34,17 @@ expect(ModelGroup.where(name: "#{@new_category_name}").count).to eq 1 end -Then /^the category is created with the assigned name and parent categories( and the image)?$/ do |image| +Then / + ^the category is created with the assigned name and parent categories( and the image)?$ + / do |image| find('#categories-index-view h1', text: _('List of Categories')) expect(current_path).to eq manage_categories_path(@current_inventory_pool) @category = Category.find_by_name "#{@new_category_name}" expect(@category).not_to be_nil - expect(ModelGroupLink.where('parent_id = ? AND label = ?', @parent_category.id, @label_1).count).to eq 1 - if image - expect(@category.images.count).to eq 1 - end + expect( + ModelGroupLink.where('parent_id = ? AND label = ?', @parent_category.id, @label_1).count + ).to eq 1 + expect(@category.images.count).to eq 1 if image end Then /^I see the list of categories$/ do @@ -51,10 +52,10 @@ find('h1', text: _('List of Categories')) expect(current_path).to eq manage_categories_path(@current_inventory_pool) @parent_categories = - ModelGroup.where(type: 'Category').select { |mg| ModelGroupLink.where(child_id: mg.id).empty? } - @parent_categories.each do |pc| - find '.line', visible: true, text: pc.name - end + ModelGroup.where(type: 'Category').select do |mg| + ModelGroupLink.where(child_id: mg.id).empty? + end + @parent_categories.each { |pc| find '.line', visible: true, text: pc.name } end end @@ -63,8 +64,12 @@ @category = ModelGroup.where(name: 'Portabel').first within('#categories-index-view #list') do find('.line', match: :first) - all(".button[data-type='expander'] i.arrow.right").each {|toggle| toggle.click } - find("a[href='/manage/%s/categories/%s/edit']" % [@current_inventory_pool.id, @category.id], match: :first).click + all(".button[data-type='expander'] i.arrow.right").each(&:click) + find( + "a[href='/manage/%s/categories/%s/edit']" % [@current_inventory_pool.id, @category.id], + match: :first + ) + .click end end @@ -75,11 +80,12 @@ expect(@category.parents.count).to eq 2 within('#categories .list-of-lines') do - @parent_category_labels = @category.parents.map do |parent| - new_label = "Label #{parent.name}" - find('.line', match: :prefer_exact, text: parent.name).find('.col3of10 input').set new_label - new_label - end + @parent_category_labels = + @category.parents.map do |parent| + new_label = "Label #{parent.name}" + find('.line', match: :prefer_exact, text: parent.name).find('.col3of10 input').set new_label + new_label + end end end @@ -92,7 +98,6 @@ expect(@category.links_as_child.map(&:label).to_set).to eq @parent_category_labels.to_set end - And /^the categories are ordered alphabetically$/ do sorted_parent_categories = @parent_categories.sort @first_category = sorted_parent_categories.first @@ -104,12 +109,10 @@ end end - And /^the first level is displayed on top$/ do expect(@visible_categories.count).to eq @parent_categories.count end - And /^I can expand and collapse subcategories$/ do child_name = @first_category.children.first.name within @visible_categories.first do @@ -121,13 +124,20 @@ find(".button[data-type='expander'] i.arrow.down").click find(".button[data-type='expander'] i.arrow.right") end - expect(has_no_selector?('.group-of-lines .line .col3of9:nth-child(2) strong', visible: true, text: child_name)).to be true + expect( + has_no_selector?( + '.group-of-lines .line .col3of9:nth-child(2) strong', visible: true, text: child_name + ) + ).to be true end When /^I edit the model$/ do - @model = Model.find {|m| [m.name, m.product].include? 'Sharp Beamer' } + @model = Model.find { |m| [m.name, m.product].include? 'Sharp Beamer' } step 'I search for "%s"' % @model.name - find('.line', text: @model.name, match: :prefer_exact).find('.button', text: _('Edit %s' % 'Model')).click + find('.line', text: @model.name, match: :prefer_exact).find( + '.button', text: _('Edit %s' % 'Model') + ) + .click end When /^I assign categories$/ do @@ -161,14 +171,14 @@ end When /^a category has no models$/ do - @unused_category = Category.all.detect{|c| c.children.empty? and c.models.empty?} + @unused_category = Category.all.detect { |c| c.children.empty? and c.models.empty? } end When /^I delete the category$/ do visit manage_categories_path @current_inventory_pool within('#categories-index-view #list') do find('.line', match: :first) - all(".button[data-type='expander'] i.arrow.right").each {|toggle| toggle.click } + all(".button[data-type='expander'] i.arrow.right").each(&:click) within(".line[data-id='#{@unused_category.id}']", match: :first) do within('.multibutton') do find('.dropdown-holder .dropdown-toggle').click @@ -190,7 +200,7 @@ end When /^a category has models$/ do - @used_category = Category.all.detect{|c| not c.children.empty? or not c.models.empty?} + @used_category = Category.all.detect { |c| nc.children.empty? or nc.models.empty? } end Then /^it's not possible to delete the category$/ do @@ -198,7 +208,9 @@ within('#categories-index-view #list') do within(".line[data-id='#{@used_category.id}']") do expect(has_no_selector?('.multibutton .dropdown-holder .dropdown-toggle')).to be true - expect(has_no_selector?(".multibutton .dropdown-item.red[data-method='delete']", text: _('Delete'))).to be true + expect( + has_no_selector?(".multibutton .dropdown-item.red[data-method='delete']", text: _('Delete')) + ).to be true end end end @@ -207,7 +219,7 @@ visit manage_categories_path @current_inventory_pool @searchTerm ||= Category.first.name[0] countBefore = all('.line').size - step %Q(I search for "%s") % @searchTerm + step 'I search for "%s"' % @searchTerm find('#list-search') expect(countBefore).not_to eq all('.line', minimum: 1).size end @@ -221,20 +233,18 @@ end Then /^the search results are ordered alphabetically$/ do - names = all('.category_name', visible: true).map{|name| name.text} + names = all('.category_name', visible: true).map(&:text) expect(names.sort == names).to be true end Then /^I can edit these categories$/ do within '#categories-index-view' do - all('.line', visible: true).each do |line| - line.find("a[href*='categories'][href*='edit']") - end + all('.line', visible: true).each { |line| line.find("a[href*='categories'][href*='edit']") } end end When /^I search for a category without models by name$/ do - @unused_category = Category.all.detect{|c| c.children.empty? and c.models.empty?} + @unused_category = Category.all.detect { |c| c.children.empty? and c.models.empty? } @searchTerm = @unused_category.name step 'I search for a category by name' end @@ -257,7 +267,7 @@ end Given(/^there exists a category with an image$/) do - @category = Category.find {|c| c.images.exists?} + @category = Category.find { |c| c.images.exists? } expect(@category).not_to be_nil end @@ -273,9 +283,7 @@ def upload_images(images) find("input[type='file']", match: :first, visible: false) page.execute_script("$('input:file').attr('class', 'visible');") image_field_id = find('.visible', match: :first) - images.each do |image| - image_field_id.set Rails.root.join('features', 'data', 'images', image) - end + images.each { |image| image_field_id.set Rails.root.join('features', 'data', 'images', image) } end When(/^I add an image$/) do diff --git a/features/step_definitions/manage/change_orderer2_steps.rb b/features/step_definitions/manage/change_orderer2_steps.rb index f8e43a7bb9..dc8c0f3277 100644 --- a/features/step_definitions/manage/change_orderer2_steps.rb +++ b/features/step_definitions/manage/change_orderer2_steps.rb @@ -5,13 +5,14 @@ find('.multibutton [data-selection-enabled] + .dropdown-holder').click find('a', text: _('Change Borrower')).click find('.modal') - @line_ids = @linegroup.all('.line').map {|l| l[:'data-id'] } - @new_user = @current_inventory_pool.users.detect {|u| u.id != @customer.id and u.visits.where(is_approved: true).exists? } + @line_ids = @linegroup.all('.line').map { |l| l[:"data-id"] } + @new_user = + @current_inventory_pool.users.detect do |u| + u.id != @customer.id and u.visits.where(is_approved: true).exists? + end find('input#user-id').set @new_user.name find('.ui-menu-item a', visible: true, text: @new_user.name).click find(".modal .button[type='submit']").click find('h1', text: @new_user.name) - @line_ids.each do |l| - expect(Reservation.find(l).user).to eq @new_user - end + @line_ids.each { |l| expect(Reservation.find(l).user).to eq @new_user } end diff --git a/features/step_definitions/manage/change_orderer_steps.rb b/features/step_definitions/manage/change_orderer_steps.rb index b845f029a9..48af612887 100644 --- a/features/step_definitions/manage/change_orderer_steps.rb +++ b/features/step_definitions/manage/change_orderer_steps.rb @@ -2,7 +2,10 @@ Then(/^I can change who placed this order$/) do old_user = @contract.user - new_user = @current_inventory_pool.users.detect {|u| u.id != old_user.id and u.visits.where(is_approved: true).exists? } + new_user = + @current_inventory_pool.users.detect do |u| + u.id != old_user.id and u.visits.where(is_approved: true).exists? + end find('#swap-user').click within '.modal' do find('input#user-id', match: :first).set new_user.name @@ -11,9 +14,8 @@ end find('.content-wrapper', text: new_user.name, match: :first) - new_contract = new_user.orders.find_by(state: :submitted, inventory_pool_id: @contract.inventory_pool) - @contract.reservations.each do |line| - expect(new_contract.reservations.include? line).to be true - end + new_contract = + new_user.orders.find_by(state: :submitted, inventory_pool_id: @contract.inventory_pool) + @contract.reservations.each { |line| expect(new_contract.reservations.include? line).to be true } expect(@contract.reload.user).to be == new_user end diff --git a/features/step_definitions/manage/contract_steps.rb b/features/step_definitions/manage/contract_steps.rb index a21110777f..2eadf41d40 100644 --- a/features/step_definitions/manage/contract_steps.rb +++ b/features/step_definitions/manage/contract_steps.rb @@ -1,14 +1,13 @@ # -*- encoding : utf-8 -*- Given /^I open a contract during hand over( that contains software)?$/ do |arg1| - step 'I open a hand over which has multiple unassigned reservations and models in stock%s' % (arg1 ? ' with software' : nil) - + step 'I open a hand over which has multiple unassigned reservations and models in stock%s' % + (arg1 ? ' with software' : nil) step 'I select a license line and assign an inventory code' if arg1 - max = [@hand_over.reservations.where(item_id: nil, option_id: nil).select {|l| l.available? }.count, 1].max - rand(1..max).times do - step 'I select an item line and assign an inventory code' - end + max = [@hand_over.reservations.where(item_id: nil, option_id: nil).select(&:available?).count, 1] + .max + rand(1..max).times { step 'I select an item line and assign an inventory code' } step 'I click hand over' step 'I see a summary of the things I selected for hand over' @@ -25,35 +24,37 @@ within @contract_element do table.hashes.each do |area| case area['Area'] - when 'Date' - within find('.date') do - expect(has_content?(Date.today.year)).to be true - expect(has_content?(Date.today.month)).to be true - expect(has_content?(Date.today.day)).to be true - end - when 'Title', 'Contract number' - expect(find('h1').has_content?(@contract.compact_id)).to be true - when 'Borrower' - find('.customer') - when 'Lender' - find('.inventory_pool') - when 'List 1' - # this list is not always there - when 'List 2' - # this list is not always there - when 'List of purposes' - expect(find('section.purposes').has_content?(@contract.purpose)).to be true - when 'Additional notes' - find('section.note') - when 'Terms' - find('.terms') - when "Borrower's signature" - find('.terms_and_signature') - when 'Page number' - # depends on browser settings - when 'Barcode' - find('.barcode') + when 'Date' + within find('.date') do + expect(has_content?(Date.today.year)).to be true + expect(has_content?(Date.today.month)).to be true + expect(has_content?(Date.today.day)).to be true + end + when 'Title', 'Contract number' + expect(find('h1').has_content?(@contract.compact_id)).to be true + when 'Borrower' + find('.customer') + when 'Lender' + find('.inventory_pool') + when 'List 1' + when 'List 2' + when 'List of purposes' + expect(find('section.purposes').has_content?(@contract.purpose)).to be true + when 'Additional notes' + find('section.note') + when 'Terms' + find('.terms') + when "Borrower's signature" + find('.terms_and_signature') + when 'Page number' + when 'Barcode' + find('.barcode') end + # this list is not always there + + # this list is not always there + + # depends on browser settings end end end @@ -66,60 +67,64 @@ within @contract_element do table.hashes.each do |area| case area['Column name'] - when 'Quantity' - @contract.reservations.each {|line| - within('section.list tr', text: line.item.inventory_code) do - find('.quantity', text: line.quantity.to_s) - end - } - when 'Inventory code' - @contract.reservations.each {|line| find('section.list tr', text: line.item.inventory_code) } - when 'Model name' - @contract.reservations.each {|line| - within('section.list tr', text: line.item.inventory_code) do - find('.model_name', text: line.item.model.name) - end - } - when 'Start date' - @contract.reservations.each {|line| - line_element = find('section.list tr', text: line.item.inventory_code) - within line_element.find('.start_date') do - expect(has_content? line.start_date.year).to be true - expect(has_content? line.start_date.month).to be true - expect(has_content? line.start_date.day).to be true - end - } - when 'End date' - @contract.reservations.each {|line| + when 'Quantity' + @contract.reservations.each do |line| + within('section.list tr', text: line.item.inventory_code) do + find('.quantity', text: line.quantity.to_s) + end + end + when 'Inventory code' + @contract.reservations.each do |line| + find('section.list tr', text: line.item.inventory_code) + end + when 'Model name' + @contract.reservations.each do |line| + within('section.list tr', text: line.item.inventory_code) do + find('.model_name', text: line.item.model.name) + end + end + when 'Start date' + @contract.reservations.each do |line| + line_element = find('section.list tr', text: line.item.inventory_code) + within line_element.find('.start_date') do + expect(has_content? line.start_date.year).to be true + expect(has_content? line.start_date.month).to be true + expect(has_content? line.start_date.day).to be true + end + end + when 'End date' + @contract.reservations.each do |line| + line_element = find('section.list tr', text: line.item.inventory_code) + within line_element.find('.end_date') do + expect(has_content? line.end_date.year).to be true + expect(has_content? line.end_date.month).to be true + expect(has_content? line.end_date.day).to be true + end + end + when 'Return date' + @contract.reservations.each do |line| + unless line.returned_date.blank? line_element = find('section.list tr', text: line.item.inventory_code) - within line_element.find('.end_date') do - expect(has_content? line.end_date.year).to be true - expect(has_content? line.end_date.month).to be true - expect(has_content? line.end_date.day).to be true - end - } - when 'Return date' - @contract.reservations.each {|line| - unless line.returned_date.blank? - line_element = find('section.list tr', text: line.item.inventory_code) - within line_element.find('.returning_date') do - expect(has_content? line.returned_date.year).to be true - expect(has_content? line.returned_date.month).to be true - expect(has_content? line.returned_date.day).to be true - end + within line_element.find('.returning_date') do + expect(has_content? line.returned_date.year).to be true + expect(has_content? line.returned_date.month).to be true + expect(has_content? line.returned_date.day).to be true end - } + end + end end end end end Then /^I see a comma-separated list of purposes$/ do - @contract.reservations.each {|line| expect(@contract_element.find('.purposes').has_content? line.order.purpose).to be true } + @contract.reservations.each do |line| + expect(@contract_element.find('.purposes').has_content? line.order.purpose).to be true + end end Then /^each unique purpose is listed only once$/ do - purposes = @contract.reservations.sort.map{|l| l.order.purpose }.uniq.join('; ') + purposes = @contract.reservations.sort.map { |l| l.order.purpose }.uniq.join('; ') @contract_element.find('.purposes > p', text: purposes) end @@ -132,7 +137,7 @@ end Then /^I see a title in the format "(.*?)"$/ do |format| - @contract_element.find('h1').text.match Regexp.new(format.gsub('#', '\\d')) + @contract_element.find('h1').text.match Regexp.new(format.gsub('#', 'undefinedd')) end Then /^I see the barcode in the top left$/ do @@ -152,17 +157,17 @@ @customer = @contract.user table.hashes.each do |area| case area['Area'] - when 'First name' - expect(@customer_element.has_content?(@customer.firstname)).to be true - when 'Last name' - expect(@customer_element.has_content?(@customer.lastname)).to be true - when 'Street', 'Street Number' - expect(@customer_element.has_content?(@customer.address)).to be true - when 'Country code', 'postal code' - expect(@customer_element.has_content?(@customer.zip)).to be true - when 'City' - expect(@customer_element.has_content?(@customer.city)).to be true - end + when 'First name' + expect(@customer_element.has_content?(@customer.firstname)).to be true + when 'Last name' + expect(@customer_element.has_content?(@customer.lastname)).to be true + when 'Street', 'Street Number' + expect(@customer_element.has_content?(@customer.address)).to be true + when 'Country code', 'postal code' + expect(@customer_element.has_content?(@customer.zip)).to be true + when 'City' + expect(@customer_element.has_content?(@customer.city)).to be true + end end end @@ -173,9 +178,8 @@ step 'I see a summary of the things I selected for take back' step 'I click take back inside the dialog' visit manage_contracts_path(@current_inventory_pool, status: [:signed, :closed]) - document_window = window_opened_by do - find('.line .multibutton a', match: :first, text: _('Contract')).click - end + document_window = + window_opened_by { find('.line .multibutton a', match: :first, text: _('Contract')).click } page.driver.browser.switch_to.window(document_window.handle) end @@ -192,13 +196,11 @@ end Then /^this list contains borrowed and returned items$/ do - all('.modal .contract .returning_date').each do |date| - expect(date).not_to eq '' - end + all('.modal .contract .returning_date').each { |date| expect(date).not_to eq '' } end When /^there are unreturned items$/ do - @not_returned = @contract.reservations.select{|reservations| reservations.returned_date.nil?} + @not_returned = @contract.reservations.select { |reservations| reservations.returned_date.nil? } end Then /^this list contains items that were borrowed but not yet returned$/ do @@ -211,16 +213,17 @@ end Then(/^the models are sorted alphabetically within their group$/) do - not_returned_lines, returned_lines = @contract.reservations.partition {|line| line.returned_date.blank? } + not_returned_lines, returned_lines = + @contract.reservations.partition { |line| line.returned_date.blank? } unless returned_lines.empty? - names = all('.contract .returned_items tbody .model_name').map{|name| name.text} + names = all('.contract .returned_items tbody .model_name').map(&:text) expect(names.empty?).to be false expect(names.sort == names).to be true end unless not_returned_lines.empty? - names = all('.contract .not_returned_items tbody .model_name').map{|name| name.text} + names = all('.contract .not_returned_items tbody .model_name').map(&:text) expect(names.empty?).to be false expect(names.sort == names).to be true end @@ -231,7 +234,10 @@ end Given(/^there is a contract for a user whose address ends with "(.*?)"$/) do |arg1| - @user = @current_inventory_pool.users.customers.find {|u| u.contracts.exists? and u.read_attribute(:address) =~ /, $/} + @user = + @current_inventory_pool.users.customers.find do |u| + u.contracts.exists? and u.read_attribute(:address) =~ /, $/ + end expect(@user).not_to be_nil end @@ -239,9 +245,7 @@ visit manage_contract_path(@current_inventory_pool, @user.contracts.first) end -Then(/^their address is shown without the "(.*?)"$/) do |arg1| - find('.street', text: @user.address) -end +Then(/^their address is shown without the "(.*?)"$/) { |arg1| find('.street', text: @user.address) } When(/^the instance's address is configured in the global settings$/) do @address = Setting.first.contract_lending_party_string @@ -253,20 +257,19 @@ end When(/^the contract contains a software license$/) do - @selected_items_with_license = @selected_items.select {|i| i.model.is_a? Software } + @selected_items_with_license = @selected_items.select { |i| i.model.is_a? Software } expect(@selected_items_with_license).not_to be_empty end Then(/^I additionally see the following information$/) do |table| table.raw.flatten.each do |s| case s - when 'Serial number' - @selected_items_with_license.each do |item| - find('.contract tbody .model_name', text: item.serial_number) - end - else - raise + when 'Serial number' + @selected_items_with_license.each do |item| + find('.contract tbody .model_name', text: item.serial_number) + end + else + raise end end - end diff --git a/features/step_definitions/manage/copy_item_steps.rb b/features/step_definitions/manage/copy_item_steps.rb index 79024e046a..f35c640868 100644 --- a/features/step_definitions/manage/copy_item_steps.rb +++ b/features/step_definitions/manage/copy_item_steps.rb @@ -1,7 +1,11 @@ # encoding: utf-8 When(/^I make a note of the original inventory code$/) do - @inventory_code_original = find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find('input', match: :first).value + @inventory_code_original = + find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find( + 'input', match: :first + ) + .value end When(/^I save and copy$/) do @@ -26,9 +30,7 @@ expect(has_content?(_('Create copied item'))).to be true end -Then(/^I can cancel$/) do - find('.button', match: :first, text: _('Cancel')) -end +Then(/^I can cancel$/) { find('.button', match: :first, text: _('Cancel')) } Then(/^all fields except the following were copied:$/) do |table| not_copied_fields = table.raw.flatten @@ -40,7 +42,11 @@ within('.row.emboss', match: :prefer_exact, text: field_name) do case field_type when 'autocomplete' - expect(find('input,textarea', match: :first).value).to eq (field_value != 'None' ? field_value : '') + expect(find('input,textarea', match: :first).value).to eq (if field_value != 'None' + field_value + else + '' + end) when 'select' expect(all('option').detect(&:selected?).text).to eq field_value when 'radio must' @@ -50,13 +56,13 @@ if field_name == _('Inventory Code') expect(find('input,textarea', match: :first).value).not_to eq @inventory_code_original elsif field_name == _('Last Checked') - # don't expect nothing; this field is tested in a separate step + else expect(find('input,textarea', match: :first).value.blank?).to be true end else field = Field.all.detect { |f| _(f.data['label']) == field_name } - if field.data["type"] == 'date' + if field.data['type'] == 'date' input_value = find('input', match: :first).value expect(input_value).to eq field_value else @@ -64,12 +70,17 @@ end end end + # don't expect nothing; this field is tested in a separate step end end end Then(/^the inventory code is already filled in$/) do - @inventory_code_copied = find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find('input', match: :first).value + @inventory_code_copied = + find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find( + 'input', match: :first + ) + .value expect(@inventory_code_copied.blank?).to be false end @@ -85,16 +96,46 @@ end Then(/^all fields except inventory code, serial number and name are copied$/) do - expect(find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find('input,textarea', match: :first).value == @item.inventory_code).to be false - expect(find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find('input,textarea', match: :first).value.empty?).to be false - expect(find('.row.emboss', match: :prefer_exact, text: _('Model')).find('input,textarea', match: :first).value).to eql @item.model.name - expect(find('.row.emboss', match: :prefer_exact, text: _('Serial Number')).find('input,textarea', match: :first).value.empty?).to be true - expect(find('.row.emboss', match: :prefer_exact, text: _('Name')).find('input,textarea', match: :first).value.empty?).to be true + expect( + find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find( + 'input,textarea', match: :first + ) + .value == + @item.inventory_code + ).to be false + expect( + find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find( + 'input,textarea', match: :first + ) + .value + .empty? + ).to be false + expect( + find('.row.emboss', match: :prefer_exact, text: _('Model')).find( + 'input,textarea', match: :first + ) + .value + ).to eql @item.model.name + expect( + find('.row.emboss', match: :prefer_exact, text: _('Serial Number')).find( + 'input,textarea', match: :first + ) + .value + .empty? + ).to be true + expect( + find('.row.emboss', match: :prefer_exact, text: _('Name')).find('input,textarea', match: :first) + .value + .empty? + ).to be true end When(/^I copy an item$/) do - @item = Item.where(inventory_pool_id: @current_inventory_pool).detect {|i| not i.retired? and not i.serial_number.nil? and not i.name.nil?} - step %Q(I search for "%s") % @item.model.name + @item = + Item.where(inventory_pool_id: @current_inventory_pool).detect do |i| + ni.retired? and ni.serial_number.nil? and ni.name.nil? + end + step 'I search for "%s"' % @item.model.name step 'expand the corresponding model' within(".line[data-type='item'][data-id='#{@item.id}']", text: @item.inventory_code) do find('.dropdown-holder').click @@ -102,27 +143,30 @@ end end - When(/^I am editing a(?:n) (item|software license)$/) do |arg1| - s0, s1, s2, s3 = case arg1 - when 'item' - ['items', 'model', 'item', _('Edit Item')] - when 'software license' - ['licenses', 'software', 'license', _('Edit License')] - end + s0, s1, s2, s3 = + case arg1 + when 'item' + ['items', 'model', 'item', _('Edit Item')] + when 'software license' + ['licenses', 'software', 'license', _('Edit License')] + end @item = @current_inventory_pool.items.send(s0).where(retired: nil).first - step %Q(I search for "%s") % @item.model.name + step 'I search for "%s"' % @item.model.name within(".line[data-type='#{s1}']", match: :prefer_exact, text: @item.model.name) do find("[data-type='inventory-expander']").click end - within(".group-of-lines .line[data-type='#{s2}'][data-id='#{@item.id}']", text: @item.inventory_code) do - find('.button', text: s3).click - end + within( + ".group-of-lines .line[data-type='#{s2}'][data-id='#{@item.id}']", text: @item.inventory_code + ) { find('.button', text: s3).click } end When(/^I edit an item belonging to a different inventory pool$/) do - @item = Item.find {|i| i.inventory_pool_id == @current_inventory_pool.id and @current_inventory_pool.id != i.owner_id} + @item = + Item.find do |i| + i.inventory_pool_id == @current_inventory_pool.id and @current_inventory_pool.id != i.owner_id + end step "I go to this item's edit page" expect(has_selector?('.field')).to be true @fields = all('.field:not(.editable)') @@ -136,7 +180,9 @@ end When(/^I make a note of the inventory code for further steps$/) do - @inventory_code = find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find('input,textarea').value + @inventory_code = + find('.row.emboss', match: :prefer_exact, text: _('Inventory Code')).find('input,textarea') + .value end Then(/^the last check date is set to today$/) do diff --git a/features/step_definitions/manage/create_item_steps.rb b/features/step_definitions/manage/create_item_steps.rb index 66621e75f4..073a7537a4 100644 --- a/features/step_definitions/manage/create_item_steps.rb +++ b/features/step_definitions/manage/create_item_steps.rb @@ -12,7 +12,7 @@ def fill_in_autocomplete_field(field_name, field_value) expect(has_no_selector? '.ui-autocomplete').to be true end -def check_fields_and_their_values table +def check_fields_and_their_values(table) table.hashes.each do |hash_row| field_name = hash_row['field'] field_value = hash_row['value'] @@ -20,28 +20,26 @@ def check_fields_and_their_values table within('.row.emboss', match: :prefer_exact, text: field_name) do case field_type - when 'autocomplete' - expect(find('input,textarea').value).to eq (field_value != 'None' ? field_value : '') - when 'select' - expect(all('option').detect(&:selected?).text).to eq field_value - when 'radio must' - expect(find("input[checked][type='radio']").value).to eq field_value - when 'radio' - expect(find('label', text: field_value).find('input').checked?).to be true - else - expect(find('input,textarea').value).to eq field_value + when 'autocomplete' + expect(find('input,textarea').value).to eq (field_value != 'None' ? field_value : '') + when 'select' + expect(all('option').detect(&:selected?).text).to eq field_value + when 'radio must' + expect(find("input[checked][type='radio']").value).to eq field_value + when 'radio' + expect(find('label', text: field_value).find('input').checked?).to be true + else + expect(find('input,textarea').value).to eq field_value end end end end - Then(/^I can create an item$/) do step 'I add a new Item' expect(current_path).to eq manage_new_item_path(@current_inventory_pool) end - Given(/^I create an? (item|license)$/) do |object_type| opts = {} opts.merge! type: :license if object_type == 'license' @@ -68,53 +66,60 @@ def check_fields_and_their_values table matched_field.select field_value when 'autocomplete' fill_in_autocomplete_field(field_name, field_value) - # within matched_field do - # find('input').click - # find('input').set field_value - # end - # find('.ui-autocomplete a', - # match: :prefer_exact, - # text: field_value, - # visible: true).click - # #################################################################### - # NOTE: For "Building" the filling in is done a second time, because on CI the - # parentValue in values_dependency_field_controller.coffee is not - # yet set when the change event is handled (locally the change event - # is fired twice, dont know why), look at: - # parentValue = App.Field.getValue(@parentElement.find(".field[data-id]")) - # if parentValue - # url = @childField.values_url.replace("$$$parent_value$$$", parentValue) - if field_name == 'Building' - fill_in_autocomplete_field(field_name, field_value) - end - # #################################################################### + fill_in_autocomplete_field(field_name, field_value) if field_name == 'Building' else within matched_field do find('input,textarea').set '' find('input,textarea').set field_value end end + # within matched_field do + # find('input').click + # find('input').set field_value + # end + # find('.ui-autocomplete a', + # match: :prefer_exact, + # text: field_value, + # visible: true).click + + # #################################################################### + # NOTE: For "Building" the filling in is done a second time, because on CI the + # parentValue in values_dependency_field_controller.coffee is not + # yet set when the change event is handled (locally the change event + # is fired twice, dont know why), look at: + # parentValue = App.Field.getValue(@parentElement.find(".field[data-id]")) + # if parentValue + # url = @childField.values_url.replace("$$$parent_value$$$", parentValue) + + # #################################################################### find('body').click end end - Then(/^the item is saved with all the entered information$/) do - select 'retired', from: 'retired' if @table_hashes.detect { |r| r['field'] == 'Retirement' } and (@table_hashes.detect { |r| r['field'] == 'Retirement' }['value']) == 'Yes' + if @table_hashes.detect { |r| r['field'] == 'Retirement' } and + (@table_hashes.detect { |r| r['field'] == 'Retirement' }['value']) == 'Yes' + select 'retired', from: 'retired' + end inventory_code = @table_hashes.detect { |r| r['field'] == 'Inventory Code' }['value'] - step %Q(I search for "%s") % inventory_code - within("#inventory .line[data-type='model']", match: :first, text: /#{@table_hashes.detect { |r| r["field"] == "Model" }["value"]}/) do - find('.col2of5 strong', text: /#{@table_hashes.detect { |r| r["field"] == "Model" }["value"]}/) + step 'I search for "%s"' % inventory_code + within( + "#inventory .line[data-type='model']", + match: :first, text: /#{@table_hashes.detect { |r| r['field'] == 'Model' }['value']}/ + ) do + find('.col2of5 strong', text: /#{@table_hashes.detect { |r| r['field'] == 'Model' }['value']}/) find(".button[data-type='inventory-expander'] i.arrow.right").click find(".button[data-type='inventory-expander'] i.arrow.down") end - find(".group-of-lines .line[data-type='item']", text: inventory_code).find('.button', text: _('Edit Item')).click + find(".group-of-lines .line[data-type='item']", text: inventory_code).find( + '.button', text: _('Edit Item') + ) + .click step 'the item has all previously entered values' end - Then(/^the item has all previously entered values$/) do expect(has_selector?('.row.emboss')).to be true @table_hashes.each do |hash_row| @@ -126,19 +131,23 @@ def check_fields_and_their_values table matched_field = all("[data-type='field'][data-id='#{field.id}']").last expect(matched_field).not_to be_blank case field_type - when 'autocomplete' - expect(matched_field.find('input,textarea').value).to eq (field_value != 'None' ? field_value : '') - when 'select' - expect(matched_field.all('option').detect(&:selected?).text).to eq field_value - when 'radio must' - expect(matched_field.find('label', text: field_value).find('input').checked?).to eq true - when '' - if field.data["type"] == 'date' - input_value = matched_field.find('input').value - expect(input_value).to eq field_value - else - expect(matched_field.find('input,textarea').value).to eq field_value - end + when 'autocomplete' + expect(matched_field.find('input,textarea').value).to eq (if field_value != 'None' + field_value + else + '' + end) + when 'select' + expect(matched_field.all('option').detect(&:selected?).text).to eq field_value + when 'radio must' + expect(matched_field.find('label', text: field_value).find('input').checked?).to eq true + when '' + if field.data['type'] == 'date' + input_value = matched_field.find('input').value + expect(input_value).to eq field_value + else + expect(matched_field.find('input,textarea').value).to eq field_value + end end end end @@ -146,67 +155,70 @@ def check_fields_and_their_values table When(/^these required fields are filled in:$/) do |table| table.raw.flatten.each do |must_field_name| case must_field_name - when 'Inventory Code' - @inventory_code_value = 'test' - @inventory_code_field = find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea') - @inventory_code_field.set @inventory_code_value - when 'Model' - model_name = Model.first.name - fill_in_autocomplete_field must_field_name, model_name - when 'Project Number' - find('.row.emboss', match: :prefer_exact, text: 'Reference').find('label', text: 'Investment').click - @project_number_value = 'test' - @project_number_field = find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea') - @project_number_field.set @project_number_value - when 'Building' - fill_in_autocomplete_field must_field_name, Building.general.name - when 'Room' - find('.row.emboss', text: must_field_name) - room = Building.general.rooms.find_by_general(true) - fill_in_autocomplete_field must_field_name, room.name - else - raise 'unknown field' + when 'Inventory Code' + @inventory_code_value = 'test' + @inventory_code_field = + find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea') + @inventory_code_field.set @inventory_code_value + when 'Model' + model_name = Model.first.name + fill_in_autocomplete_field must_field_name, model_name + when 'Project Number' + find('.row.emboss', match: :prefer_exact, text: 'Reference').find('label', text: 'Investment') + .click + @project_number_value = 'test' + @project_number_field = + find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea') + @project_number_field.set @project_number_value + when 'Building' + fill_in_autocomplete_field must_field_name, Building.general.name + when 'Room' + find('.row.emboss', text: must_field_name) + room = Building.general.rooms.find_by_general(true) + fill_in_autocomplete_field must_field_name, room.name + else + raise 'unknown field' end end end - When(/^these required fields are blank:$/) do |table| table.raw.flatten.each do |must_field_name| case must_field_name - when 'Inventory Code' - find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea').set '' - when 'Model' - find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input').set '' - when 'Project Number' - find('.row.emboss', match: :prefer_exact, text: 'Reference').find('label', text: 'Investment').click - find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea').set '' - else - raise 'unknown field' + when 'Inventory Code' + find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea').set '' + when 'Model' + find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input').set '' + when 'Project Number' + find('.row.emboss', match: :prefer_exact, text: 'Reference').find('label', text: 'Investment') + .click + find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea').set '' + else + raise 'unknown field' end end end - When(/^I leave the field "(.+)" empty$/) do |must_field_name| @must_field_name = must_field_name - if not find('.row.emboss', match: :prefer_exact, text: @must_field_name).all('input,textarea').empty? + if nfind('.row.emboss', match: :prefer_exact, text: @must_field_name).all('input,textarea').empty? find('.row.emboss', match: :prefer_exact, text: @must_field_name).find('input,textarea').set '' - elsif not find('.row.emboss', match: :prefer_exact, text: @must_field_name).all('select').empty? - find('.row.emboss', match: :prefer_exact, text: @must_field_name).find("select option[value='']").select_option + elsif nfind('.row.emboss', match: :prefer_exact, text: @must_field_name).all('select').empty? + find('.row.emboss', match: :prefer_exact, text: @must_field_name).find( + "select option[value='']" + ) + .select_option else raise 'unkown field' end end - Then(/^the model cannot be created$/) do step 'I save' expect(Item.find_by_inventory_code('')).to eq nil expect(Item.find_by_inventory_code('test')).to eq nil end - Then(/^the other fields still contain their data$/) do if @must_field_name == 'Model' expect(@inventory_code_field.value).to eq @inventory_code_value @@ -214,18 +226,18 @@ def check_fields_and_their_values table end end - - Then(/^the barcode is already filled in$/) do - expect(find('.row.emboss', match: :prefer_exact, text: 'Inventory Code').find('input').value.empty?).to be false + expect( + find('.row.emboss', match: :prefer_exact, text: 'Inventory Code').find('input').value.empty? + ).to be false end - Then(/^The date this item was last checked is today's date$/) do - expect(find('.row.emboss', match: :prefer_exact, text: 'Last Checked').find('input').value).to eq Date.today.strftime('%d/%m/%Y') + expect( + find('.row.emboss', match: :prefer_exact, text: 'Last Checked').find('input').value + ).to eq Date.today.strftime('%d/%m/%Y') end - Then(/^the following fields have their default values$/) do |table| check_fields_and_their_values table end @@ -245,35 +257,32 @@ def check_fields_and_their_values table find('.ui-autocomplete li', count: 1).click end - Then(/^(a new|no new) supplier is created$/) do |arg1| find('h1', text: _('List of Inventory')) find('#inventory') expect(Supplier.find_by_name(@new_supplier)).not_to be_nil expect(Supplier.where(name: @new_supplier).count).to eq 1 case arg1 - when 'a new' - expect(Supplier.count).to eq @suppliers_count + 1 - when 'no new' - expect(Supplier.count).to eq @suppliers_count + when 'a new' + expect(Supplier.count).to eq @suppliers_count + 1 + when 'no new' + expect(Supplier.count).to eq @suppliers_count end end - - Then(/^the (created|edited|copied) item has the (new|existing) supplier$/) do |arg1, arg2| sleep 2 expect( case arg1 - when 'created' - Item.find_by_inventory_code('test').supplier.name - when 'edited' - case arg2 - when 'new', 'existing' - @item.reload.supplier.name - end - when 'copied' - Item.find_by_inventory_code(@inventory_code).supplier.name + when 'created' + Item.find_by_inventory_code('test').supplier.name + when 'edited' + case arg2 + when 'new', 'existing' + @item.reload.supplier.name + end + when 'copied' + Item.find_by_inventory_code(@inventory_code).supplier.name end ).to eq @new_supplier end @@ -288,8 +297,9 @@ def check_fields_and_their_values table When(/^I remove one attachment$/) do @attachment_to_remove = @attachment_filenames.first @attachment_filenames.delete(@attachment_to_remove) - find('.row.emboss', match: :prefer_exact, text: _('Attachments')) - .find("[data-type='inline-entry']", text: @attachment_to_remove) + find('.row.emboss', match: :prefer_exact, text: _('Attachments')).find( + "[data-type='inline-entry']", text: @attachment_to_remove + ) .find('button[data-remove]', match: :first) .click end diff --git a/features/step_definitions/manage/create_software_steps.rb b/features/step_definitions/manage/create_software_steps.rb index ef35f3ec3e..e005009916 100644 --- a/features/step_definitions/manage/create_software_steps.rb +++ b/features/step_definitions/manage/create_software_steps.rb @@ -4,9 +4,7 @@ When(/^the possible currencies are$/) do |table| table.raw.flatten.each do |s| - within "select[name='item[properties][maintenance_currency]']" do - find("option[value='#{s}']") - end + within "select[name='item[properties][maintenance_currency]']" dofind("option[value='#{s}']")end end end @@ -18,23 +16,26 @@ When(/^I type the amount "(.*?)" into the field "(.*?)"$/) do |arg1, arg2| case arg2 - when 'maintenance amount' - find("input[name='item[properties][maintenance_price]']").set arg1 - else - raise + when 'maintenance amount' + find("input[name='item[properties][maintenance_price]']").set arg1 + else + raise end end When /^I save$/ do # if some dropdown is covering the save button we need to get rid of it # in a begin/rescue, because rack driver does not implement hover method + begin find('#topbar').hover sleep 1 - rescue NotImplementedError + # do nothing + rescue NotImplementedError + end - find('button', text: /#{_("Save")}/i).click + find('button', text: /#{_('Save')}/).click end Then(/^the "(.*?)" is saved as "(.*?)"$/) do |arg1, arg2| @@ -42,12 +43,11 @@ last_created_software_license = @current_inventory_pool.items.licenses.sort_by(&:created_at).last visit manage_edit_item_path(@current_inventory_pool, last_created_software_license) case arg1 - when 'maintenance currency' - expect(find("select[name='item[properties][maintenance_currency]']").value).to eq arg2 - when 'maintenance amount' - expect(find("input[name='item[properties][maintenance_price]']").value).to eq arg2 - else - raise + when 'maintenance currency' + expect(find("select[name='item[properties][maintenance_currency]']").value).to eq arg2 + when 'maintenance amount' + expect(find("input[name='item[properties][maintenance_price]']").value).to eq arg2 + else + raise end end - diff --git a/features/step_definitions/manage/daily_view_steps.rb b/features/step_definitions/manage/daily_view_steps.rb index f646e86ba1..6756e5bf8e 100644 --- a/features/step_definitions/manage/daily_view_steps.rb +++ b/features/step_definitions/manage/daily_view_steps.rb @@ -2,10 +2,10 @@ Given(/^there is an order with two different time windows$/) do @customer = @current_inventory_pool.users.customers.first - @order = FactoryGirl.create(:order, - user: @customer, - inventory_pool: @current_inventory_pool, - state: :submitted) + @order = + FactoryGirl.create( + :order, user: @customer, inventory_pool: @current_inventory_pool, state: :submitted + ) FactoryGirl.create( :reservation, user: @customer, @@ -22,13 +22,14 @@ order: @order, inventory_pool: @current_inventory_pool, start_date: Date.today, - end_date: Date.today+10.days + end_date: Date.today + 10.days ) end Then(/^I see the longest time span of this order directly on the order's line$/) do - line_with_max_range = @order.reservations.where(type: 'ItemLine').max{|line| line.end_date - line.start_date} - range = (line_with_max_range.end_date-line_with_max_range.start_date).to_i+1 + line_with_max_range = + @order.reservations.where(type: 'ItemLine').max { |line| line.end_date - line.start_date } + range = (line_with_max_range.end_date - line_with_max_range.start_date).to_i + 1 expect(find(".line[data-id='#{@order.id}']").has_content? "#{range} #{_('days')}").to be true end diff --git a/features/step_definitions/manage/delegation_mail_steps.rb b/features/step_definitions/manage/delegation_mail_steps.rb index c187e1d7e8..73e9c25046 100644 --- a/features/step_definitions/manage/delegation_mail_steps.rb +++ b/features/step_definitions/manage/delegation_mail_steps.rb @@ -1,28 +1,39 @@ # -*- encoding : utf-8 -*- -Given(/^there is (an order|a take back|an overdue take back) for a delegation that was not placed by a person responsible for that delegation$/) do |arg1| - status = case arg1 - when "an order" - :submitted - when "a take back", "an overdue take back" - :open - end - @current_inventory_pool = @current_user.inventory_pools.managed.detect do |ip| - User.as_delegations.detect do |delegation| - if status == :submitted - @order = @contract = ip.orders.submitted.where(user_id: delegation).detect do |order| - order.delegated_user != delegation.delegator_user and - if arg1 == "an overdue take back" - order.reservations.any? {|reservation| reservation.end_date < Date.today } - else - true +Given( + / + ^there is (an order|a take back|an overdue take back) for a delegation that was not placed by a person responsible for that delegation$ + / +) do |arg1| + status = + case arg1 + when 'an order' + :submitted + when 'a take back', 'an overdue take back' + :open + end + @current_inventory_pool = + @current_user.inventory_pools.managed.detect do |ip| + User.as_delegations.detect do |delegation| + if status == :submitted + @order = + @contract = + ip.orders.submitted.where(user_id: delegation).detect do |order| + order.delegated_user != delegation.delegator_user and + if arg1 == 'an overdue take back' + order.reservations.any? { |reservation| reservation.end_date < Date.today } + else + true + end + end + elsif status == :open + @contract = + ip.contracts.open.where(user_id: delegation).detect do |c| + c.delegated_user != delegation.delegator_user end end - elsif status == :open - @contract = ip.contracts.open.where(user_id: delegation).detect { |c| c.delegated_user != delegation.delegator_user } end end - end expect(@contract).not_to be_nil expect(@contract.user.delegator_user).not_to eq @contract.delegated_user expect(ActionMailer::Base.deliveries.count).to eq 0 @@ -31,17 +42,18 @@ Then(/^the approval email is sent to the orderer$/) do sleep 1 expect(ActionMailer::Base.deliveries.count).to eq 1 - expect(ActionMailer::Base.deliveries.first.to).to eq @contract.delegated_user.emails + expect(ActionMailer::Base.deliveries.first.to).to eq @contract.delegated_user.emails end Then(/^the approval email is not sent to the delegated user$/) do - expect((ActionMailer::Base.deliveries.first.to & @contract.user.delegator_user.emails).empty?).to be true + expect( + (ActionMailer::Base.deliveries.first.to & @contract.user.delegator_user.emails).empty? + ).to be true end - When(/^I send a reminder for this take back$/) do step 'I navigate to the take back visits' - within('.line', text: /#{@contract.user}.*#{_("Latest reminder")}/) do + within('.line', text: /#{@contract.user}.*#{_('Latest reminder')}/) do within '.multibutton' do find('.dropdown-toggle').click find('a', text: _('Send reminder')).click @@ -50,7 +62,7 @@ end Then(/^the reminder is sent to the one who picked up the order$/) do - find('.line', text: /#{@contract.user}.*#{_("Reminder sent")}/) + find('.line', text: /#{@contract.user}.*#{_('Reminder sent')}/) #step "wird das Genehmigungsmail an den Besteller versendet" step 'the approval email is sent to the orderer' diff --git a/features/step_definitions/manage/delegation_steps.rb b/features/step_definitions/manage/delegation_steps.rb index 71f8d6f645..2c34a4b4f4 100644 --- a/features/step_definitions/manage/delegation_steps.rb +++ b/features/step_definitions/manage/delegation_steps.rb @@ -7,7 +7,8 @@ Then(/^I see all results for Julie or the delegation named Julie$/) do q = '%Julie%' - delegations = @current_inventory_pool.users.as_delegations.where(User.arel_table[:firstname].matches(q)) + delegations = + @current_inventory_pool.users.as_delegations.where(User.arel_table[:firstname].matches(q)) ([@user] + delegations).each do |u| find('#users .list-of-lines .line', match: :prefer_exact, text: u.to_s) end @@ -22,12 +23,13 @@ end Then(/^I can restrict the user list to show only (users|delegations)$/) do |arg1| - t, b = case arg1 - when 'users' - [_('Users'), false] - when 'delegations' - [_('Delegations'), true] - end + t, b = + case arg1 + when 'users' + [_('Users'), false] + when 'delegations' + [_('Delegations'), true] + end find('#user-index-view form#list-filters select#type').select t within '#user-list.list-of-lines' do @@ -90,14 +92,16 @@ When(/^I enter exactly one responsible person$/) do @responsible ||= @current_inventory_pool.users.not_as_delegations.first - find('.row.emboss', text: _('Responsible')).find("input[data-type='autocomplete']").set @responsible.name + find('.row.emboss', text: _('Responsible')).find( + "input[data-type='autocomplete']" + ).set @responsible.name find('ul.ui-autocomplete > li').click end Then(/^the new delegation is saved with the current information$/) do delegation = User.find_by_firstname(@name) expect(delegation.delegator_user).to eq @responsible - delegation.delegated_users.each {|du| @delegated_users.include? du.name} + delegation.delegated_users.each { |du| @delegated_users.include? du.name } delegation.delegated_users.count == (@delegated_users + [@resonsible]).uniq.count end @@ -108,7 +112,10 @@ end When(/^I hover over the delegation name$/) do - find('#delegations .list-of-lines .line', match: :prefer_exact, text: @delegation.to_s).find("[data-type='user-cell']").hover + find('#delegations .list-of-lines .line', match: :prefer_exact, text: @delegation.to_s).find( + "[data-type='user-cell']" + ) + .hover end Then(/^the tooltip shows name and responsible person for the delegation$/) do @@ -123,7 +130,7 @@ When(/^I pick a delegation to represent$/) do within(all('.line').to_a.sample) do - id = find('.line-actions a.button')[:href].gsub(/.*\//, '') + id = find('.line-actions a.button')[:href].gsub(%r{.*\/}, '') @delegation = @current_user.delegations.customers.find(id) find('strong', match: :prefer_exact, text: @delegation.to_s) find('.line-actions a.button').click @@ -131,15 +138,13 @@ end Then(/^I am logged in as that delegation$/) do - find("nav.topbar ul.topbar-navigation .topbar-item", text: @delegation.short_name) + find('nav.topbar ul.topbar-navigation .topbar-item', text: @delegation.short_name) @delegated_user = @current_user @current_user = @delegation end Then(/^the delegation is saved as borrower$/) do - (@contracts or @reservations).each do |entity| - expect(entity.user).to eq @delegation - end + (@contracts or @reservations).each { |entity| expect(entity.user).to eq @delegation } end Then(/^I am saved as contact person$/) do @@ -149,31 +154,30 @@ end Given(/^there is an order for a delegation$/) do - @order = @contract = @current_inventory_pool.orders.submitted.find {|c| c.user.delegation? } + @order = @contract = @current_inventory_pool.orders.submitted.find { |c| c.user.delegation? } expect(@contract).not_to be_nil end Given(/^I am editing a delegation's order$/) do - @order = @contract = @current_inventory_pool.orders.find do |o| - [:submitted, :approved].include?(o.state) and - o.reservations.any?(&:delegated_user) - o.user.delegated_users.count >= 2 - end + @order = + @contract = + @current_inventory_pool.orders.find do |o| + [:submitted, :approved].include?(o.state) and o.reservations.any?(&:delegated_user) + o.user.delegated_users.count >= 2 + end expect(@order).to be @delegation = @contract.user step 'I edit the order' end -Then(/^I see the delegation's name$/) do - expect(has_content?(@contract.user.name)).to be true -end +Then(/^I see the delegation's name$/) { expect(has_content?(@contract.user.name)).to be true } Then(/^I see the contact person$/) do expect(has_content?(@contract.delegated_user.name)).to be true end Given(/^there is an order placed by me personally$/) do - @order = @contract = @current_inventory_pool.orders.submitted.find {|c| not c.user.delegation? } + @order = @contract = @current_inventory_pool.orders.submitted.find { |c| nc.user.delegation? } expect(@contract).not_to be_nil end @@ -181,18 +185,21 @@ expect(has_content?(@contract.user.name)).to be true end -Then(/^I don't see any contact person$/) do - find('h2', text: @contract.user.name) -end +Then(/^I don't see any contact person$/) { find('h2', text: @contract.user.name) } Given(/^there is a hand over( for a delegation)?( with assigned items)?$/) do |arg1, arg2| - @hand_over = if arg1 and arg2 - @current_inventory_pool.visits.hand_over.find {|v| v.user.delegation? and v.reservations.all?(&:item) and Date.today >= v.date } - elsif arg1 - @current_inventory_pool.visits.hand_over.find {|v| v.user.delegation? and v.reservations.any? &:item and not v.date > Date.today } # NOTE v.date.future? doesn't work properly because timezone - else - @current_inventory_pool.visits.hand_over.first - end + @hand_over = + if arg1 and arg2 + @current_inventory_pool.visits.hand_over.find do |v| + v.user.delegation? and v.reservations.all?(&:item) and Date.today >= v.date + end + elsif arg1 + @current_inventory_pool.visits.hand_over.find do |v| + v.user.delegation? and v.reservations.any? &:item and nv.date > Date.today + end # NOTE v.date.future? doesn't work properly because timezone + else + @current_inventory_pool.visits.hand_over.first + end expect(@hand_over).not_to be_nil end @@ -207,39 +214,47 @@ el = find(".line[data-ids='#{ids}'] input[data-select-line]") el.click unless el.checked? end - else # hand over + else line_ids = all('.line[data-id]').map { |l| l['data-id'] } line_ids.each do |id| el = find(".line[data-id='#{id}'] input[data-select-line]") el.click unless el.checked? end end + # hand over end When(/^I change the delegation$/) do expect(has_selector?('input[data-select-line]', match: :first)).to be true step 'I select all reservations selecting all linegroups' - multibutton = first('.multibutton', text: _('Hand Over Selection')) || first('.multibutton', text: _('Edit Selection')) + multibutton = + first('.multibutton', text: _('Hand Over Selection')) || + first('.multibutton', text: _('Edit Selection')) multibutton.find('.dropdown-toggle').click find('#swap-user', match: :first).click find('.modal', match: :first) @contract ||= @hand_over.reservations.map(&:contract).uniq.first @order ||= @hand_over.reservations.map(&:order).uniq.first @old_delegation = (@contract || @order).user - @new_delegation = @current_inventory_pool.users.find {|u| u.delegation? and u.firstname != @old_delegation.firstname} + @new_delegation = + @current_inventory_pool.users.find do |u| + u.delegation? and u.firstname != @old_delegation.firstname + end find('input#user-id', match: :first).set @new_delegation.name find('.ui-menu-item a', match: :prefer_exact, text: @new_delegation.name).click - (@contract || @order).reservations.reload.all? {|c| c.user == @new_delegation } + (@contract || @order).reservations.reload.all? { |c| c.user == @new_delegation } end When(/^I try to change the delegation$/) do step 'I select all reservations selecting all linegroups' - multibutton = first('.multibutton', text: _('Hand Over Selection')) || first('.multibutton', text: _('Edit Selection')) + multibutton = + first('.multibutton', text: _('Hand Over Selection')) || + first('.multibutton', text: _('Edit Selection')) multibutton.find('.dropdown-toggle').click find('#swap-user', match: :first).click find('.modal', match: :first) find('input#user-id', match: :first) - @wrong_delegation = User.as_delegations.find {|d| not d.access_right_for @current_inventory_pool} + @wrong_delegation = User.as_delegations.find { |d| nd.access_right_for @current_inventory_pool } @valid_delegation = @current_inventory_pool.users.as_delegations.first end @@ -254,13 +269,13 @@ find('button', text: _('Hand Over Selection')).click @delegation = @hand_over.user @contact = @delegation.delegated_users.first - @not_contact = @current_inventory_pool.users.find {|u| not @delegation.delegated_users.include? u} + @not_contact = @current_inventory_pool.users.find { |u| n@delegation.delegated_users.include? u } end When(/^I try to change the order's contact person$/) do click_button 'swap-user' @contact = @delegation.delegated_users.first - @not_contact = @current_inventory_pool.users.find {|u| not @delegation.delegated_users.include? u} + @not_contact = @current_inventory_pool.users.find { |u| n@delegation.delegated_users.include? u } end Then(/^I can choose only those people that belong to the delegation group$/) do @@ -271,7 +286,11 @@ find('#selected-user', text: @contact.name) end -Then(/^I can choose only those people as contact person for the order that belong to the delegation group$/) do +Then( + / + ^I can choose only those people as contact person for the order that belong to the delegation group$ + / +) do within '#contact-person' do find('input#user-id', match: :first).click expect(has_no_selector?('.ui-menu-item a', text: @not_contact.name)).to be true @@ -303,10 +322,10 @@ @delegated_user = (@contract || @order).delegated_user @new_user = @current_inventory_pool.users.not_as_delegations.first expect(page).to have_content _('Availability loaded') - all('input[data-select-lines]', minimum: 1).map do |input| - input.click unless input.checked? - end - multibutton = first('.multibutton', text: _('Hand Over Selection')) || first('.multibutton', text: _('Edit Selection')) + all('input[data-select-lines]', minimum: 1).map { |input| input.click unless input.checked? } + multibutton = + first('.multibutton', text: _('Hand Over Selection')) || + first('.multibutton', text: _('Edit Selection')) multibutton.find('.dropdown-toggle').click if multibutton find('#swap-user', match: :first).click within '.modal' do @@ -329,33 +348,33 @@ Then(/^the order shows the user$/) do find('.content-wrapper', text: @new_user.name, match: :first) - @contract.reservations.each do |line| - expect(line.reload.user).to eq @new_user - end + @contract.reservations.each { |line| expect(line.reload.user).to eq @new_user } end Then(/^no contact person is shown$/) do expect(has_no_content?("(#{@delegated_user.name})")).to be true - @contract.reservations.each do |line| - expect(line.reload.delegated_user).to eq nil - end + @contract.reservations.each { |line| expect(line.reload.delegated_user).to eq nil } end When(/^there is no order, hand over or contract for a delegation$/) do - @delegations = User.as_delegations.select {|d| d.orders.blank?} + @delegations = User.as_delegations.select { |d| d.orders.blank? } end When(/^that delegation has no access rights to any inventory pool$/) do - @delegation = @delegations.find {|d| d.access_rights.empty?} + @delegation = @delegations.find { |d| d.access_rights.empty? } expect(@delegation).not_to be_nil end Then(/^I can delete that delegation$/) do - step %Q(I search for "%s") % @delegation.name + step 'I search for "%s"' % @delegation.name line = find('.row', text: @delegation.name) line.find('.dropdown-toggle').click find("[data-method='delete']").click - page.driver.browser.switch_to.alert.accept rescue nil + begin + page.driver.browser.switch_to.alert.accept + rescue StandardError + nil + end step 'I receive a notification of success' expect { @delegation.reload }.to raise_error ActiveRecord::RecordNotFound end @@ -372,14 +391,15 @@ expect(find("input[name='user[delegator_user_id]']", visible: false)['value'].empty?).to be true end -When(/^I do not enter any name$/) do - find("input[name='user[firstname]']").set '' -end +When(/^I do not enter any name$/) { find("input[name='user[firstname]']").set '' } When(/^I change the responsible person$/) do expect(has_no_selector?('ul.ui-autocomplete')).to be true - @responsible = @current_inventory_pool.users.not_as_delegations.find {|u| u != @delegation.delegator_user } - find('.row.emboss', text: _('Responsible')).find("input[data-type='autocomplete']").set @responsible.name + @responsible = + @current_inventory_pool.users.not_as_delegations.find { |u| u != @delegation.delegator_user } + find('.row.emboss', text: _('Responsible')).find( + "input[data-type='autocomplete']" + ).set @responsible.name sleep(0.55) # NOTE this sleep is required waiting the search result find('ul.ui-autocomplete > li > a', text: @responsible.name).click expect(has_no_selector?('ul.ui-autocomplete')).to be true @@ -387,8 +407,10 @@ When(/^I delete an existing user from the delegation$/) do @delegated_users = @delegation.delegated_users - inline_user_entry = find('.row.emboss', text: _('Users')).find('[data-users-list] .row.line', match: :first) - @removed_delegated_user = User.find {|u| u.name == inline_user_entry.find('[data-user-name]').text} + inline_user_entry = + find('.row.emboss', text: _('Users')).find('[data-users-list] .row.line', match: :first) + @removed_delegated_user = + User.find { |u| u.name == inline_user_entry.find('[data-user-name]').text } inline_user_entry.find('button[data-remove-user]').click @delegated_users.delete @removed_delegated_user end @@ -399,7 +421,7 @@ find('[data-search-users]').set ' ' el = find('ul.ui-autocomplete > li > a', match: :first) user_name = el.text - @delegated_users << User.find {|u| u.name == user_name} + @delegated_users << User.find { |u| u.name == user_name } el.click expect(has_no_selector?('ul.ui-autocomplete')).to be true find('#users .line', text: user_name) @@ -407,13 +429,16 @@ Then(/^the edited delegation is saved with its current information$/) do expect(@delegation.reload.delegator_user).to eq @responsible - @delegation.delegated_users.each {|du| @delegated_users.include? du} + @delegation.delegated_users.each { |du| @delegated_users.include? du } @delegation.delegated_users.count == (@delegated_users + [@responsible]).uniq.count expect(@delegation.entitlement_groups).to match_array @current_inventory_pool.entitlement_groups end When(/^I edit a delegation that has access to the current inventory pool$/) do - @delegation = @current_inventory_pool.users.find {|u| u.delegation? and not u.visits.take_back.exists? and u.inventory_pools.count >= 2} + @delegation = + @current_inventory_pool.users.find do |u| + u.delegation? and nu.visits.take_back.exists? and u.inventory_pools.count >= 2 + end expect(@delegation).not_to be_nil visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @delegation) end @@ -425,7 +450,7 @@ Then(/^no orders can be created for this delegation in the current inventory pool$/) do step 'I log out' - step %Q(I am logged in as '#{@delegation.delegator_user.login}' with password 'password') + step "I am logged in as '#{@delegation.delegator_user.login}' with password 'password'" find('.dropdown-holder', text: @current_user.lastname).click find(".dropdown-item[href*='delegations']").click find('.row.line', text: @delegation.name).click_link _('Switch to') @@ -435,9 +460,9 @@ end When(/^I create an order for a delegation$/) do - steps %{ + steps " When I hover over my name - And I click on "Delegations" + And I click on \"Delegations\" Then I see the delegations I am assigned to When I pick a delegation to represent Then I am logged in as that delegation @@ -452,7 +477,7 @@ And I submit the order Then the reservations' status changes to submitted And the delegation is saved as borrower - } + " end When(/^I hand over the items ordered for this delegation to "(.*?)"$/) do |contact_person| @@ -460,7 +485,7 @@ @contract.approve Faker::Lorem.sentence visit manage_hand_over_path(@current_inventory_pool, @delegation) expect(has_selector?('input[data-assign-item]')).to be true - all('input[data-assign-item]').detect{|el| not el.disabled?}.click + all('input[data-assign-item]').detect { |el| nel.disabled? }.click find('.ui-autocomplete .ui-menu-item', match: :first).click expect(has_selector? '[data-remove-assignment]').to be true find('.multibutton button[data-hand-over-selection]').click @@ -475,18 +500,19 @@ end Then(/^"(.*?)" is the new contact person for this contract$/) do |contact_person| - expect(@delegation.contracts.open.order('created_at DESC').first.delegated_user) - .to eq @contact + expect(@delegation.contracts.open.order('created_at DESC').first.delegated_user).to eq @contact end Then(/^the hand over shows the user$/) do find('.content-wrapper', text: @new_user.name, match: :first) expect(current_path).to eq manage_hand_over_path(@current_inventory_pool, @new_user) - expect(@delegation.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).empty?).to be true + expect( + @delegation.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).empty? + ).to be true end Then(/^I open a hand over for a delegation$/) do - @hand_over = @current_inventory_pool.visits.hand_over.find {|v| v.user.delegation? } + @hand_over = @current_inventory_pool.visits.hand_over.find { |v| v.user.delegation? } @delegation = @hand_over.user visit manage_hand_over_path @current_inventory_pool, @delegation end @@ -497,7 +523,9 @@ @delegation = @current_inventory_pool.users.as_delegations.first expect(has_selector?('input[data-select-lines]', match: :first)).to be true step 'I select all reservations selecting all linegroups' - multibutton = first('.multibutton', text: _('Hand Over Selection')) || first('.multibutton', text: _('Edit Selection')) + multibutton = + first('.multibutton', text: _('Hand Over Selection')) || + first('.multibutton', text: _('Edit Selection')) multibutton.find('.dropdown-toggle').click if multibutton find('#swap-user', match: :first).click find('.modal', match: :first) @@ -512,20 +540,20 @@ find('.ui-menu-item a', match: :first, text: @contact.name).click end -Then(/^the order shows the delegation$/) do - expect(has_content?(@delegation.name)).to be true -end +Then(/^the order shows the delegation$/) { expect(has_content?(@delegation.name)).to be true } Then(/^the order shows the name of the contact person$/) do expect(has_content?(@contact.name)).to be true end -When(/^I confirm the user change$/) do - find(".modal button[type='submit']").click -end +When(/^I confirm the user change$/) { find(".modal button[type='submit']").click } When(/^I hand over the items$/) do - line = find(".line[data-line-type='item_line'] input[id*='assigned-item'][value][disabled]", match: :first).find(:xpath, 'ancestor::div[@data-line-type]') + line = + find( + ".line[data-line-type='item_line'] input[id*='assigned-item'][value][disabled]", match: :first + ) + .find(:xpath, 'ancestor::div[@data-line-type]') line.find('input[data-select-line]').click find('.multibutton', text: _('Hand Over Selection')).find('button').click end @@ -539,14 +567,10 @@ end Then(/^the newly selected contact person is saved$/) do - @contract.reservations.each do |line| - expect(line.reload.delegated_user).to eq @contact - end + @contract.reservations.each { |line| expect(line.reload.delegated_user).to eq @contact } end -Then(/^I see exactly one contact person field$/) do - find('#contact-person') -end +Then(/^I see exactly one contact person field$/) { find('#contact-person') } When(/^I do not enter any contact person$/) do expect(find('#contact-person input#user-id', match: :first).value.empty?).to be true @@ -557,12 +581,18 @@ end When(/^I finish this hand over$/) do - find(:xpath, "//*[@data-line-type and descendant::*[contains(@id, 'assigned-item')]]//*[@data-select-line]", match: :first).click + find( + :xpath, + "//*[@data-line-type and descendant::*[contains(@id, 'assigned-item')]]//*[@data-select-line]", + match: :first + ) + .click find('button[data-hand-over-selection]').click end When(/^I choose a suspended contact person$/) do - delegated_user = @hand_over.user.delegated_users.detect {|u| u.suspended? @current_inventory_pool} + delegated_user = + @hand_over.user.delegated_users.detect { |u| u.suspended? @current_inventory_pool } find('input#user-id', match: :first).set delegated_user.name find('.ui-menu-item a', match: :first, text: delegated_user.name).click end @@ -573,7 +603,7 @@ end When(/^I assign a responsible person that is suspended for the current inventory pool$/) do - @responsible = @current_inventory_pool.users.detect {|u| u.suspended? @current_inventory_pool} + @responsible = @current_inventory_pool.users.detect { |u| u.suspended? @current_inventory_pool } #step 'ich genau einen Verantwortlichen eintrage' step 'I enter exactly one responsible person' end @@ -590,28 +620,27 @@ end When(/^I pick a contact person that is suspended for the current inventory pool$/) do - delegated_user = @delegation.delegated_users.detect {|u| u.suspended? @current_inventory_pool} - delegated_user ||= begin - user = @delegation.delegated_users.first - ensure_suspended_user(user, @current_inventory_pool) - user - end + delegated_user = @delegation.delegated_users.detect { |u| u.suspended? @current_inventory_pool } + delegated_user ||= + begin + user = @delegation.delegated_users.first + ensure_suspended_user(user, @current_inventory_pool) + user + end find('input#user-id', match: :first).set delegated_user.name find('.ui-menu-item a', match: :first, text: delegated_user.name).click end -And(/^I take note of the reservations$/) do - @reservations = @current_user.reservations.unsubmitted -end +And(/^I take note of the reservations$/) { @reservations = @current_user.reservations.unsubmitted } When(/^I switch from my user to a delegation$/) do - steps %{ + steps ' When I hover over my name And I click on "Delegations" Then I see the delegations I am assigned to When I pick a delegation to represent Then I am logged in as that delegation - } + ' end When(/^that delegation is enabled for an inventory pool$/) do @@ -623,51 +652,50 @@ end Then(/^I cannot place any reservations in this inventory pool$/) do - steps %{ + steps ' And I add a model to an order When I open my list of orders When I enter a purpose And I submit the order And I see an error message - } + ' end Given(/^there exists a delegation with 'Julie' in its name$/) do delegator = FactoryGirl.create(:user) - @delegation = \ - FactoryGirl.create(:user, - delegator_user: delegator, - firstname: "#{Faker::Lorem.word} Julie #{Faker::Lorem.word}") - FactoryGirl.create(:access_right, - role: 'customer', - user: delegator, - inventory_pool: @current_inventory_pool) - FactoryGirl.create(:access_right, - user: @delegation, - role: 'customer', - inventory_pool: @current_inventory_pool) + @delegation = + FactoryGirl.create( + :user, delegator_user: delegator, firstname: "#{Faker::Lorem.word} Julie #{Faker::Lorem.word}" + ) + FactoryGirl.create( + :access_right, role: 'customer', user: delegator, inventory_pool: @current_inventory_pool + ) + FactoryGirl.create( + :access_right, user: @delegation, role: 'customer', inventory_pool: @current_inventory_pool + ) end Then(/^I see all results in the users box for users matching Julie$/) do - expect(page).to have_selector "#users" - within("#users") do - find(".row", text: @user.name) - end -end - -Then(/^I see all results in delegations box for delegations matching Julie or delegations having members matching Julie$/) do - expect(page).to have_selector "#delegations" - within("#delegations") do - find(".row", text: @delegation.name) + expect(page).to have_selector '#users' + within('#users') { find('.row', text: @user.name) } +end + +Then( + / + ^I see all results in delegations box for delegations matching Julie or delegations having members matching Julie$ + / +) do + expect(page).to have_selector '#delegations' + within('#delegations') do + find('.row', text: @delegation.name) @current_inventory_pool.users.where(id: @user.delegations.map(&:id)).each do |delegation| - find(".row", text: delegation.name) + find('.row', text: delegation.name) end end end When(/^I choose another contact person for the order$/) do - @new_contact = \ - @delegation.delegated_users.find { |du| du != @contract.delegated_user } + @new_contact = @delegation.delegated_users.find { |du| du != @contract.delegated_user } within '#contact-person' do find('input#user-id', match: :first).set @new_contact.name find('.ui-menu-item a', match: :first, text: @new_contact.name).click @@ -677,4 +705,3 @@ Then(/^the contact person for the order has been changed accordingly$/) do expect(page).to have_content "(#{@new_contact.name})" end - diff --git a/features/step_definitions/manage/edit_item_steps.rb b/features/step_definitions/manage/edit_item_steps.rb index 57976842dc..baabda33c9 100644 --- a/features/step_definitions/manage/edit_item_steps.rb +++ b/features/step_definitions/manage/edit_item_steps.rb @@ -1,14 +1,18 @@ # -*- encoding : utf-8 -*- -Given(/^I edit an item that belongs to the current inventory pool( and is in stock)?( and is not part of any contract)?$/) do |in_stock, not_in_contract| - items = @current_inventory_pool.items.items.where(owner_id: @current_inventory_pool, models: {is_package: false}) +Given( + / + ^I edit an item that belongs to the current inventory pool( and is in stock)?( and is not part of any contract)?$ + / +) do |in_stock, not_in_contract| + items = + @current_inventory_pool.items.items.where( + owner_id: @current_inventory_pool, models: { is_package: false } + ) items = items.in_stock if in_stock - @item = if not_in_contract - items.detect { |i| Reservation.where(item_id: i.id).empty? } - else - items.first - end + @item = + not_in_contract ? items.detect { |i| Reservation.where(item_id: i.id).empty? } : items.first visit manage_edit_item_path @current_inventory_pool, @item expect(has_selector?('.row.emboss')).to be true @@ -30,9 +34,7 @@ all(".field[data-required='true']", visible: true).each do |field| expect(field.text[/\*/]).not_to be_nil end - all(".field:not([data-required='true'])").each do |field| - expect(field.text[/\*/]).to eq nil - end + all(".field:not([data-required='true'])").each { |field| expect(field.text[/\*/]).to eq nil } end Then(/^I cannot save the item if a required field is empty$/) do @@ -43,18 +45,16 @@ expect(@item.to_json).to eq @item.reload.to_json end - When(/^the required fields are highlighted in red$/) do all(".field[data-required='true']", visible: true).each do |field| if field.all('input[type=text]').any? { |input| input.value == 0 } or - field.all('textarea').any? { |textarea| textarea.value == 0 } or - (ips = field.all('input[type=radio]'); ips.all? { |input| not input.checked? } if not ips.empty?) + field.all('textarea').any? { |textarea| textarea.value == 0 } or + (ips = field.all('input[type=radio]'); ips.all? { |input| ninput.checked? } if nips.empty?) expect(field[:class][/invalid/]).not_to be_nil end end end - Then(/^I see form fields in the following order:$/) do |table| expected_values = [] expected_headlines = [] @@ -63,9 +63,10 @@ expected_values << tr[0].chomp if !tr[0].match(/^\-.*\-$/) end headlines = find('#flexible-fields').all('h2').map { |hl| "- #{hl.text} -" }.compact - values = find('#flexible-fields').all("div[data-type='key']").map do |element| - element.text.gsub(' *','').chomp - end + values = + find('#flexible-fields').all("div[data-type='key']").map do |element| + element.text.gsub(' *', '').chomp + end expect(headlines).to eq(expected_headlines) expect(values).to eq(expected_values) end @@ -94,14 +95,14 @@ end And(/^I navigate to the edit page of an item that has a supplier$/) do - @item = @current_inventory_pool.items.find { |i| not i.supplier.nil? } + @item = @current_inventory_pool.items.find { |i| ni.supplier.nil? } step "I go to this item's edit page" end When(/^I change the supplier$/) do @supplier = Supplier.first @new_supplier = @supplier.name # A later step looks for this instead of @supplier, maybe - # fix the later step instead? + # fix the later step instead? fill_in_autocomplete_field _('Supplier'), @supplier.name end @@ -112,16 +113,22 @@ end When(/^I change the responsible department$/) do - fill_in_autocomplete_field _('Responsible'), InventoryPool.where('id != ?', @item.inventory_pool.id).first.name + fill_in_autocomplete_field _('Responsible'), + InventoryPool.where('id != ?', @item.inventory_pool.id).first.name end When(/^I change the model$/) do - fill_in_autocomplete_field _('Model'), @current_inventory_pool.models.detect { |m| m != @item.model }.name + fill_in_autocomplete_field _('Model'), + @current_inventory_pool.models.detect { |m| m != @item.model }.name end When(/^I retire the item$/) do - find('.row.emboss', match: :prefer_exact, text: _('Retirement')).find('select', match: :first).select _('Yes') - find('.row.emboss', match: :prefer_exact, text: _('Reason for Retirement')).find('input, textarea', match: :first).set 'Retirement reason' + find('.row.emboss', match: :prefer_exact, text: _('Retirement')).find( + 'select', match: :first + ).select _('Yes') + find('.row.emboss', match: :prefer_exact, text: _('Reason for Retirement')).find( + 'input, textarea', match: :first + ).set 'Retirement reason' end Given(/^there is a model without a version$/) do @@ -129,16 +136,16 @@ expect(@model).not_to be_nil end -When(/^I assign this model to the item$/) do - fill_in_autocomplete_field _('Model'), @model.name -end +When(/^I assign this model to the item$/) { fill_in_autocomplete_field _('Model'), @model.name } Then(/^there is only product name in the input field of the model$/) do expect(find('div.field[data-id=model_id]').find('input').value).to eq @model.product end Given(/^exists an item that belongs to the current inventory pool but is not owned by it$/) do - @item = Item.where(inventory_pool: @current_inventory_pool).where.not(owner: @current_inventory_pool).first + @item = + Item.where(inventory_pool: @current_inventory_pool).where.not(owner: @current_inventory_pool) + .first expect(@item).to be end @@ -156,14 +163,10 @@ end end -Then(/^I cannot add attachments$/) do - expect(find('#attachments')).not_to have_selector('button') -end +Then(/^I cannot add attachments$/) { expect(find('#attachments')).not_to have_selector('button') } Then(/^I cannot remove attachments$/) do expect(find('#attachments')).not_to have_selector('.list-of-lines button') end -When(/^I edit the item$/) do - visit manage_edit_item_path @current_inventory_pool, @item -end +When(/^I edit the item$/) { visit manage_edit_item_path @current_inventory_pool, @item } diff --git a/features/step_definitions/manage/explorative_search_steps.rb b/features/step_definitions/manage/explorative_search_steps.rb index 263401cc6c..a943183994 100644 --- a/features/step_definitions/manage/explorative_search_steps.rb +++ b/features/step_definitions/manage/explorative_search_steps.rb @@ -13,13 +13,14 @@ c.click - find("#categories #category-current a[data-type='category-current'][data-id='#{c_id}']", text: @category.name) + find( + "#categories #category-current a[data-type='category-current'][data-id='#{c_id}']", + text: @category.name + ) end Then(/^I see that category's children$/) do - @category.children.each do |child| - find('#categories', match: :prefer_exact, text: child.name) - end + @category.children.each { |child| find('#categories', match: :prefer_exact, text: child.name) } end Then(/^I can select the child category$/) do @@ -40,26 +41,30 @@ within('#inventory') do all(".line[data-type='model']", minimum: 1).each do |model_line| model = Model.find_by_name(model_line.find('.col2of5 strong').text) - expect((model.categories.include?(@child_category) or @child_category.descendants.any? {|c| model.categories.include? c})).to be true + expect( + (model.categories.include?(@child_category) or + @child_category.descendants.any? { |c| model.categories.include? c }) + ).to be true end end end Then(/^I can navigate back to the current top-level category in one single step$/) do find('#category-root a').click - step 'I see that category\'s children' + step "I see that category's children" end Then(/^I can navigate back to the list of top-level categories in one single step$/) do step 'I can navigate to the parent category' Category.roots.each do |child| - find("#categories #category-list [data-type='category-filter']", match: :prefer_exact, text: child.name) + find( + "#categories #category-list [data-type='category-filter']", + match: :prefer_exact, text: child.name + ) end end -When(/^I collapse the category filter$/) do - find('#categories-toggle').click -end +When(/^I collapse the category filter$/) { find('#categories-toggle').click } Then(/^I see only the list of inventory$/) do expect(has_no_selector?('#categories #category-list', visible: true)).to be true @@ -75,20 +80,25 @@ Then(/^all categories whose names match the search term are shown$/) do within '#categories #category-list' do - Category.all.map(&:name).reject{|name| not name[@search_term]}.each do |name| + Category.all.map(&:name).reject { |name| nname[@search_term] }.each do |name| find("[data-type='category-filter']", match: :prefer_exact, text: name) end - expect(all("[data-type='category-filter']").size).to eq all("[data-type='category-filter']", text: @search_term).size + expect(all("[data-type='category-filter']").size).to eq all( + "[data-type='category-filter']", text: @search_term + ) + .size end end -Then(/^I see a search indicator with the current search term as well the currently selected category and its children$/) do +Then( + / + ^I see a search indicator with the current search term as well the currently selected category and its children$ + / +) do # find('#category-root .fa.fa-search') # find('#category-root', text: @search_term) find('#category-current', text: @child_category.name) - @child_category.children.each do |child| - find('#category-list', text: child.name) - end + @child_category.children.each { |child| find('#category-list', text: child.name) } end Given(/^I used the explorative search to get to a subcategory$/) do @@ -97,9 +107,7 @@ step 'I select a category' end -Then(/^I can navigate to the parent category$/) do - find('#category-current a').click -end +Then(/^I can navigate to the parent category$/) { find('#category-current a').click } Then(/^the explorative search shows only models from my inventory pool$/) do find("button.addon[type='submit'] .fa.fa-plus").click @@ -117,11 +125,11 @@ end Then(/^I see the models not assigned to any category$/) do - expected_models = @current_inventory_pool.models.select {|model| model.categories.empty? } + expected_models = @current_inventory_pool.models.select { |model| model.categories.empty? } # step 'I fetch all pages of the list' within '#inventory' do - while(all('.loading-bg').length > 0 || all('.line').length < expected_models.count) do + while (all('.loading-bg').length > 0 || all('.line').length < expected_models.count) page.execute_script 'window.scrollBy(0,10000)' end end diff --git a/features/step_definitions/manage/groups_steps.rb b/features/step_definitions/manage/groups_steps.rb index f5239dd619..c0d7c19cbd 100644 --- a/features/step_definitions/manage/groups_steps.rb +++ b/features/step_definitions/manage/groups_steps.rb @@ -4,7 +4,6 @@ visit manage_inventory_pool_groups_path(@current_inventory_pool) end - Then(/^I am listing groups$/) do @current_inventory_pool.entitlement_groups.reload.each do |group| find('.list-of-lines .line strong', text: group.name) @@ -29,27 +28,25 @@ end Then(/^the list is sorted alphabetically$/) do - expect((all('.list-of-lines .line strong').map(&:text).to_json == @current_inventory_pool.entitlement_groups.map(&:name).sort.to_json)).to be true + expect( + (all('.list-of-lines .line strong').map(&:text).to_json == + @current_inventory_pool.entitlement_groups.map(&:name).sort.to_json) + ).to be true end -When(/^I create a group$/) do - find('.button', text: _('New Group')).click -end +When(/^I create a group$/) { find('.button', text: _('New Group')).click } When(/^I fill in the group's name$/) do @name = Faker::Name.name fill_in 'group[name]', with: @name end - When(/^I add users to the group$/) do @users = @current_inventory_pool.users.customers @users.each do |user| find('input[data-search-users]').set user.name - within('.ui-autocomplete') do - find('.ui-menu-item', text: user.name) - end - page.execute_script %[ $(".ui-menu-item:contains('#{user.name}')").click() ] + within('.ui-autocomplete') { find('.ui-menu-item', text: user.name) } + page.execute_script " $(\".ui-menu-item:contains('#{user.name}')\").click() " end end @@ -59,10 +56,15 @@ @models.each do |model| find('input[data-search-models]').set model.name find('.ui-menu-item a', match: :prefer_exact, text: model.name).click - borrowable_items = model.items.where(inventory_pool_id: @current_inventory_pool.id).borrowable.size - 1 - partition = {model_id: model.id, quantity: (borrowable_items.zero? ? 0 : rand(borrowable_items)) + 1} + borrowable_items = + model.items.where(inventory_pool_id: @current_inventory_pool.id).borrowable.size - 1 + partition = { + model_id: model.id, quantity: (borrowable_items.zero? ? 0 : rand(borrowable_items)) + 1 + } @partitions.push partition - find('.list-of-lines .line', text: model.name).fill_in 'group[partitions_attributes][][quantity]', with: partition[:quantity] + find( + '.list-of-lines .line', text: model.name + ).fill_in 'group[partitions_attributes][][quantity]', with: partition[:quantity] end end @@ -74,7 +76,9 @@ Then(/^the group has users as well as models and their capacities$/) do expect(@group.users.reload.map(&:id).sort).to eq @users.map(&:id).sort - expect(Set.new(@group.entitlements.map{|p| {model_id: p.model_id, quantity: p.quantity}})).to eq Set.new(@partitions) + expect( + Set.new(@group.entitlements.map { |p| { model_id: p.model_id, quantity: p.quantity } }) + ).to eq Set.new(@partitions) end Then(/^the group list is sorted alphabetically$/) do @@ -84,15 +88,16 @@ When(/^I edit an existing( non verifiable| verifiable)? group$/) do |arg1| groups = @current_inventory_pool.entitlement_groups - groups = case arg1 - when ' non verifiable' - groups.where(is_verification_required: false) - when ' verifiable' - groups.where(is_verification_required: true) - else - groups - end - @group = groups.find {|g| g.models.length >= 2 and g.users.length >= 2} + groups = + case arg1 + when ' non verifiable' + groups.where(is_verification_required: false) + when ' verifiable' + groups.where(is_verification_required: true) + else + groups + end + @group = groups.find { |g| g.models.length >= 2 and g.users.length >= 2 } visit manage_edit_inventory_pool_group_path @group.inventory_pool_id, @group end @@ -111,29 +116,44 @@ When(/^I add and remove users from the group$/) do @users = @group.users - @users.sample(@users.size/2).each do |user| - find("input[name='group[users][][id]'][value='#{user.id}']", visible: false).first(:xpath, './..').find('.button[data-remove-user]', text: _('Remove')).click + @users.sample(@users.size / 2).each do |user| + find("input[name='group[users][][id]'][value='#{user.id}']", visible: false).first( + :xpath, './..' + ) + .find('.button[data-remove-user]', text: _('Remove')) + .click @users.delete user end end When(/^I add and remove models and their capacities from the group$/) do all("[name='group[partitions_attributes][][quantity]']").each do |existing_partition_line| - existing_partition_line.first(:xpath, './../../..').find('.button[data-remove-group]', text: _('Remove')).click + existing_partition_line.first(:xpath, './../../..').find( + '.button[data-remove-group]', text: _('Remove') + ) + .click end - model = (@current_inventory_pool.models-@group.models).first + model = (@current_inventory_pool.models - @group.models).first find('input[data-search-models]').set model.name find('.ui-menu-item a', match: :prefer_exact, text: model.name).click - partition = {model_id: model.id, quantity: rand(1..model.items.where(inventory_pool_id: @current_inventory_pool.id).borrowable.size)} + partition = { + model_id: model.id, + quantity: + rand(1..model.items.where(inventory_pool_id: @current_inventory_pool.id).borrowable.size) + } @partitions = [partition] - find('.list-of-lines .line', text: model.name).fill_in 'group[partitions_attributes][][quantity]', with: partition[:quantity] + find('.list-of-lines .line', text: model.name).fill_in 'group[partitions_attributes][][quantity]', + with: partition[:quantity] end - Then(/^I see any capacities that are still available for assignment$/) do @partitions.each do |partition| model = Model.find partition[:model_id] - expect(all("input[value='#{model.id}']", visible: false).first.parent.has_content?("/ #{model.items.where(inventory_pool_id: @current_inventory_pool.id).borrowable.size}")).to be true + expect( + all("input[value='#{model.id}']", visible: false).first.parent.has_content?( + "/ #{model.items.where(inventory_pool_id: @current_inventory_pool.id).borrowable.size}" + ) + ).to be true end end @@ -152,7 +172,6 @@ expect(EntitlementGroup.find_by_name(@group.name)).to eq nil end - When(/^I add one user to the group$/) do fill_in_autocomplete_field _('Users'), @user_name = @current_inventory_pool.users.first.name end @@ -161,7 +180,6 @@ find('#users .list-of-lines .line [data-user-name]', text: @user_name) end - When(/^I add a model to the group$/) do @model = @current_inventory_pool.models.first fill_in_autocomplete_field _('Models'), @model.name @@ -172,7 +190,6 @@ find('#models-allocations .list-of-lines .line', match: :first, text: @model.name) end - Then(/^the already present models are sorted alphabetically$/) do within('#models-allocations') do entries = all('.list-of-lines .line', minimum: 1) @@ -183,7 +200,9 @@ When(/^I add a model that is already present in the group$/) do @model = @group.models.first @quantity = 2 - find('#models-allocations .list-of-lines .line', match: :prefer_exact, text: @model.name).fill_in 'group[partitions_attributes][][quantity]', with: @quantity + find( + '#models-allocations .list-of-lines .line', match: :prefer_exact, text: @model.name + ).fill_in 'group[partitions_attributes][][quantity]', with: @quantity fill_in_autocomplete_field _('Models'), @model.name end @@ -210,5 +229,11 @@ end Then(/^the already existing model keeps whatever capacity was set for it$/) do - expect(find('#models-allocations .list-of-lines .line', match: :prefer_exact, text: @model.name).find("input[name='group[partitions_attributes][][quantity]']").value.to_i).to eq @quantity + expect( + find('#models-allocations .list-of-lines .line', match: :prefer_exact, text: @model.name).find( + "input[name='group[partitions_attributes][][quantity]']" + ) + .value + .to_i + ).to eq @quantity end diff --git a/features/step_definitions/manage/hand_over/add_steps.rb b/features/step_definitions/manage/hand_over/add_steps.rb index d4a83cf339..d434928a45 100644 --- a/features/step_definitions/manage/hand_over/add_steps.rb +++ b/features/step_definitions/manage/hand_over/add_steps.rb @@ -1,4 +1,6 @@ -When /^I add (a|an|a borrowable|an unborrowable) (item|license) to the hand over by providing an inventory code$/ do |item_attr, item_type| +When / + ^I add (a|an|a borrowable|an unborrowable) (item|license) to the hand over by providing an inventory code$ + / do |item_attr, item_type| item = FactoryGirl.create(item_type.to_sym, inventory_pool: @current_inventory_pool) case item_attr when 'a borrowable' @@ -19,33 +21,40 @@ expect(line_amount_before).to be < all('.line', minimum: 1).size end -When /^I add (a|an|a borrowable|an unborrowable) (item|license) to the hand over by using the search input field$/ do |item_attr, item_type| +When / + ^I add (a|an|a borrowable|an unborrowable) (item|license) to the hand over by using the search input field$ + / do |item_attr, item_type| items = @current_inventory_pool.items.unretired.send(item_type.pluralize) @inventory_codes ||= [] - @item = case item_attr - when 'a', 'an' - items.in_stock - when 'a borrowable' - items.in_stock.where(is_borrowable: true) - when 'an unborrowable' - items.in_stock.where(is_borrowable: false) - end.first + @item = + case item_attr + when 'a', 'an' + items.in_stock + when 'a borrowable' + items.in_stock.where(is_borrowable: true) + when 'an unborrowable' + items.in_stock.where(is_borrowable: false) + end + .first @model = @item.model @inventory_codes << @item.inventory_code rescue_displaced_flash do find('#assign-or-add-input input').set @item.model.name find('.ui-autocomplete .submenu-scroll li', text: @item.model.name).click - find('.line', text: @item.model.name, match: :first).find('form[data-assign-item-form] input').click + find('.line', text: @item.model.name, match: :first).find('form[data-assign-item-form] input') + .click find('.ui-menu-item', text: @item.inventory_code).click end end -Then /^the item is added to the hand over for the provided date range and the inventory code is already assigend$/ do +Then / + ^the item is added to the hand over for the provided date range and the inventory code is already assigend$ + / do expect( - @customer - .reservations - .approved - .find_by(inventory_pool_id: @current_inventory_pool, item_id: Item.find_by_inventory_code(@inventory_code)) + @customer.reservations.approved.find_by( + inventory_pool_id: @current_inventory_pool, + item_id: Item.find_by_inventory_code(@inventory_code) + ) ).to be assigned_inventory_codes = all('.line input[data-assign-item]').map(&:value) expect(assigned_inventory_codes).to include @inventory_code @@ -62,36 +71,38 @@ Then /^the (.*?) is added to the hand over$/ do |type| case type - when 'option' - find(".line[data-line-type='option_line'] .col1of10", match: :prefer_exact, text: @inventory_code) - option = Option.find_by_inventory_code(@inventory_code) - find('#flash', text: option.name) - @option_line = @reservation = \ - @customer - .reservations - .approved - .find_by(inventory_pool_id: @current_inventory_pool, option_id: option) - expect(@reservation).to be - when 'model' - find('#flash', text: 'Added') - @item_line = @reservation = \ - @customer - .reservations - .approved - .find_by(inventory_pool_id: @current_inventory_pool, model_id: @model) - expect(@reservation).to be - find(".line[data-line-type='item_line'] .col4of10", match: :prefer_exact, text: @model.name) + when 'option' + find( + ".line[data-line-type='option_line'] .col1of10", match: :prefer_exact, text: @inventory_code + ) + option = Option.find_by_inventory_code(@inventory_code) + find('#flash', text: option.name) + @option_line = + @reservation = + @customer.reservations.approved.find_by( + inventory_pool_id: @current_inventory_pool, option_id: option + ) + expect(@reservation).to be + when 'model' + find('#flash', text: 'Added') + @item_line = + @reservation = + @customer.reservations.approved.find_by( + inventory_pool_id: @current_inventory_pool, model_id: @model + ) + expect(@reservation).to be + find(".line[data-line-type='item_line'] .col4of10", match: :prefer_exact, text: @model.name) end end -When /^I add an option to the hand over which is already existing in the selected date range by providing an inventory code$/ do +When / + ^I add an option to the hand over which is already existing in the selected date range by providing an inventory code$ + / do option_line = @contract.option_lines.first @option = option_line.option @quantity_before = option_line.quantity @n = rand(2..5) - @n.times do - step 'I add an option to the hand over by providing an inventory code' - end + @n.times { step 'I add an option to the hand over by providing an inventory code' } end Then /^the existing option quantity is increased$/ do @@ -103,8 +114,9 @@ expect(@option_line.quantity).to eq (@quantity_before + @n) end -When /^I type the beginning of (.*?) name to the add\/assign input field$/ do |type| - @target_name = case type +When %r{^I type the beginning of (.*?) name to the add\/assign input field$} do |type| + @target_name = + case type when 'an option' @option = FactoryGirl.create(:option, inventory_pool: @current_inventory_pool) @inventory_code = @option.inventory_code @@ -117,7 +129,7 @@ when 'a template' @template = @current_inventory_pool.templates.first @template.name - end + end type_into_autocomplete '#assign-or-add-input input', @target_name[0..-2] end @@ -130,17 +142,21 @@ Then(/^I see that model in the list of suggested model names as "(.*?)"$/) do |arg1| case arg1 - when 'not borrowable' - find('.ui-autocomplete a.light-red', match: :prefer_exact, text: @target_name) - else - 'not found' + when 'not borrowable' + find('.ui-autocomplete a.light-red', match: :prefer_exact, text: @target_name) + else + 'not found' end end - When /^I select the (.*?) from the list$/ do |type| # trick closing possible tooltips - page.driver.browser.action.move_to(find('nav#topbar').native).perform + page + .driver + .browser + .action + .move_to(find('nav#topbar').native) + .perform within '.ui-autocomplete' do if type == 'option' @@ -167,14 +183,19 @@ start_date = Date.parse find('#add-start-date').value end_date = Date.parse find('#add-end-date').value av = @model.availability_in(@current_inventory_pool) - quantity_to_add = if @contract - av.maximum_available_in_period_summed_for_groups start_date, end_date, @contract.user.entitlement_groups.map(&:id) - elsif @order - av.maximum_available_in_period_summed_for_groups start_date, end_date, @order.user.entitlement_groups.map(&:id) - else - @model.items.size - end - @quantity_added = [quantity_to_add+1, 0].max + quantity_to_add = + if @contract + av.maximum_available_in_period_summed_for_groups start_date, + end_date, + @contract.user.entitlement_groups.map(&:id) + elsif @order + av.maximum_available_in_period_summed_for_groups start_date, + end_date, + @order.user.entitlement_groups.map(&:id) + else + @model.items.size + end + @quantity_added = [quantity_to_add + 1, 0].max @quantity_added.times do type_into_autocomplete '#assign-or-add-input input, #add-input input', @target_name step 'I see a list of suggested model names' @@ -185,9 +206,7 @@ Then /^I see that all reservations of that model have availability problems$/ do find(".line[data-line-type='item_line']", match: :prefer_exact, text: @target_name) @lines = all(".line[data-line-type='item_line']", text: @target_name) - @lines.each do |line| - line.find('.line-info.red') - end + @lines.each { |line| line.find('.line-info.red') } end When /^I add an item to the hand over$/ do @@ -197,7 +216,10 @@ end Given(/^there is a model or software which all items are set to "not borrowable"$/) do - @model = FactoryGirl.create(:model_with_items, inventory_pool: @current_inventory_pool, is_borrowable: false) + @model = + FactoryGirl.create( + :model_with_items, inventory_pool: @current_inventory_pool, is_borrowable: false + ) end Then(/^the quantity on the option line is (\d+)$/) do |quantity| diff --git a/features/step_definitions/manage/hand_over/assign_steps.rb b/features/step_definitions/manage/hand_over/assign_steps.rb index 50e346b069..7ee66c3447 100644 --- a/features/step_definitions/manage/hand_over/assign_steps.rb +++ b/features/step_definitions/manage/hand_over/assign_steps.rb @@ -1,20 +1,29 @@ When /^I click an inventory code input field of an item line$/ do - @item_line = @customer.reservations.approved.find_by(inventory_pool_id: @current_inventory_pool, item_id: nil) + @item_line = + @customer.reservations.approved.find_by( + inventory_pool_id: @current_inventory_pool, item_id: nil + ) @item_line_element = find('.line', match: :prefer_exact, text: @item_line.model.name) @item_line_element.find('[data-assign-item]').click end Then /^I see a list of inventory codes of items that are in stock and matching the model$/ do within @item_line_element.find('.ui-autocomplete') do - @item_line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).each do |item| - find('a', text: item.inventory_code) - end + @item_line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool) + .each { |item| find('a', text: item.inventory_code) } end end When /^I assign an item to the hand over by providing an inventory code and a date range$/ do - @inventory_code = @current_user.inventory_pools.managed.first.items.in_stock.first.inventory_code unless @inventory_code - model_already_there = @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).flat_map(&:reservations).any? {|l| l.model == Item.find_by_inventory_code(@inventory_code).model} + unless @inventory_code + @inventory_code = + @current_user.inventory_pools.managed.first.items.in_stock.first.inventory_code + end + model_already_there = + @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).flat_map( + &:reservations + ) + .any? { |l| l.model == Item.find_by_inventory_code(@inventory_code).model } line_amount_before = all('.line').count assigned_amount_before = all('.line [data-assign-item][disabled]').count @@ -24,12 +33,12 @@ line_amount_after = all('.line').count # if we add current_user item for whose model there is already a visit line, then not new line is created but the inv code is added to the existing one - expect(line_amount_before).to eq ( model_already_there ? line_amount_after : line_amount_after - 1 ) + expect(line_amount_before).to eq (model_already_there ? line_amount_after : line_amount_after - 1) expect(assigned_amount_before).to be < all('.line [data-assign-item][disabled]').count end When /^I select one of those$/ do - unless @item_line.is_a? OptionLine # assign inventory code applies only to items + unless @item_line.is_a? OptionLine # assign inventory code applies only to items within(".line[data-id='#{@item_line.id}']") do find('input[data-assign-item]').click x = find('.ui-autocomplete a', match: :first) @@ -48,10 +57,24 @@ find('[data-selected-lines-container] input[data-select-lines]', match: :first).click end -When /^I add an item which is matching the model of one of the selected unassigned reservations to the hand over by providing an inventory code$/ do +When / + ^I add an item which is matching the model of one of the selected unassigned reservations to the hand over by providing an inventory code$ + / do expect(has_selector?('.line')).to be true - selected_ids = all('.line [data-select-line]:checked').map {|cb| cb.find(:xpath, 'ancestor::div[@data-id]')['data-id']} - @item = @hand_over.reservations.select{|l| !l.item and selected_ids.include?(l.id.to_s) and l.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).exists?}.first.model.items.in_stock.first + selected_ids = + all('.line [data-select-line]:checked').map do |cb| + cb.find(:xpath, 'ancestor::div[@data-id]')['data-id'] + end + @item = + @hand_over.reservations.select do |l| + !l.item and selected_ids.include?(l.id.to_s) and + l.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).exists? + end + .first + .model + .items + .in_stock + .first find('#assign-or-add-input input').set @item.inventory_code find('#assign-or-add button').click end @@ -59,7 +82,7 @@ Then /^the first itemline in the selection matching the provided inventory code is assigned$/ do expect(has_selector?('.line.green')).to be true reloaded_visit = Visit.where(id: @hand_over.id).first - line = reloaded_visit.reservations.detect{|line| line.item == @item} + line = reloaded_visit.reservations.detect { |line| line.item == @item } expect(line).not_to be_nil end @@ -78,21 +101,21 @@ Then /^the assignment of the line to an inventory code is removed$/ do find('.notice', text: _('The assignment for %s was removed') % @item_line.model.name) - within(".line[data-line-type='item_line'][data-id='#{@item_line.id}']", text: @item_line.model.name) do - expect(find('[data-assign-item]').value.empty?).to be true - end + within( + ".line[data-line-type='item_line'][data-id='#{@item_line.id}']", text: @item_line.model.name + ) { expect(find('[data-assign-item]').value.empty?).to be true } expect(@item_line.reload.item).to eq nil end When(/^I click on the assignment field of software names$/) do - @reservation = @hand_over.reservations.find {|l| l.model.is_a? Software } + @reservation = @hand_over.reservations.find { |l| l.model.is_a? Software } find(".line[data-id='#{@reservation.id}'] input[data-assign-item]").click end Then(/^I see the inventory codes and the complete serial numbers of that software$/) do within '.ui-autocomplete' do @reservation.model.items.each do |item| - within(".ui-menu-item", text: item.inventory_code) do + within('.ui-menu-item', text: item.inventory_code) do find('.col3of4', text: item.serial_number) end end diff --git a/features/step_definitions/manage/hand_over/delete_steps.rb b/features/step_definitions/manage/hand_over/delete_steps.rb index c4080d2972..731dee455b 100644 --- a/features/step_definitions/manage/hand_over/delete_steps.rb +++ b/features/step_definitions/manage/hand_over/delete_steps.rb @@ -19,7 +19,8 @@ end When(/^I select multiple reservations$/) do - @selected_line_ids = @hand_over.reservations.limit(rand(1..@hand_over.reservations.count)).map &:id + @selected_line_ids = + @hand_over.reservations.limit(rand(1..@hand_over.reservations.count)).map &:id expect(has_selector?('.line[data-id]', match: :first)).to be true @selected_line_ids.each do |id| cb = find(".line[data-id='#{id}'] input[type='checkbox'][data-select-line]") @@ -38,23 +39,39 @@ @selected_line_ids.each do |line_id| expect(has_no_selector?(".line[data-id='#{line_id}']")).to be true end - @selected_line_ids.each {|id| expect { Reservation.find(id) }.to raise_error(ActiveRecord::RecordNotFound)} + @selected_line_ids.each do |id| + expect { Reservation.find(id) }.to raise_error(ActiveRecord::RecordNotFound) + end end -When(/^I delete all reservations of a model thats availability is blocked by these reservations$/) do - unless @customer.orders.approved.find_by(inventory_pool_id: @current_inventory_pool).reservations.first.available? +When( + /^I delete all reservations of a model thats availability is blocked by these reservations$/ +) do + unless @customer.orders.approved.find_by(inventory_pool_id: @current_inventory_pool).reservations + .first + .available? step 'I add an item to the hand over by providing an inventory code' @model = Item.find_by_inventory_code(@inventory_code).model - find('.line', match: :prefer_exact, text: @model.name).find("input[type='checkbox'][data-select-line]").click + find('.line', match: :prefer_exact, text: @model.name).find( + "input[type='checkbox'][data-select-line]" + ) + .click end step 'I add so many reservations that I break the maximal quantity of a model' step 'the availability is loaded' - target_linegroup = find('[data-selected-lines-container]', text: /#{find("#add-start-date").value}.*#{find("#add-end-date").value}/) + target_linegroup = + find( + '[data-selected-lines-container]', + text: /#{find('#add-start-date').value}.*#{find('#add-end-date').value}/ + ) - reference_line = target_linegroup.all('.line', text: @model.name).detect{|line| line.find('.line-info.red')} + reference_line = + target_linegroup.all('.line', text: @model.name).detect { |line| line.find('.line-info.red') } @reference_id = reference_line['data-id'] - line_ids = target_linegroup.all('.line', text: @model.name).select{|line| line.find('.line-info.red')}.map{|line| line['data-id']} + line_ids = + target_linegroup.all('.line', text: @model.name).select { |line| line.find('.line-info.red') } + .map { |line| line['data-id'] } line_ids.each do |id| if id != @reference_id rescue_displaced_flash do diff --git a/features/step_definitions/manage/hand_over/edit_contract_steps.rb b/features/step_definitions/manage/hand_over/edit_contract_steps.rb index 28d6a21f49..23ed577be6 100644 --- a/features/step_definitions/manage/hand_over/edit_contract_steps.rb +++ b/features/step_definitions/manage/hand_over/edit_contract_steps.rb @@ -4,30 +4,28 @@ cb = line.find('input[type=checkbox][data-select-line]') cb.click unless cb.checked? end - expect(all('.line input[type=checkbox][data-select-line]').all? {|x| x.checked? }).to be true + expect(all('.line input[type=checkbox][data-select-line]').all?(&:checked?)).to be true end When(/^I select an option line$/) do @option_line_el = find(".line[data-line-type='option_line']", match: :first) @option_line_el.find("input[type='checkbox'][data-select-line]").click - @option_line_el_id = @option_line_el["data-id"] + @option_line_el_id = @option_line_el['data-id'] @selected_items = [] @selected_items << Reservation.find(@option_line_el_id).option expect(@selected_items.size).to eq 1 end -When(/^I change the time range for all contract reservations, envolving option and item reservations$/) do +When( + /^I change the time range for all contract reservations, envolving option and item reservations$/ +) do step 'I add an option to the hand over by providing an inventory code' step 'I select all reservations' step 'I edit the timerange of the selection' @line = @hand_over.reservations.first @old_start_date = @line.start_date @new_start_date = - if @line.start_date + 1.day < Time.zone.today - Time.zone.today - else - @line.start_date + 1.day - end + @line.start_date + 1.day < Time.zone.today ? Time.zone.today : @line.start_date + 1.day get_fullcalendar_day_element(@new_start_date).click find('#set-start-date', text: _('Start date')).click step 'I save the booking calendar' @@ -35,14 +33,19 @@ end Then(/^the time range for all contract reservations is changed$/) do - @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).detect { |x| x.reservations.size > 1 }.reservations.each do |line| - expect(line.start_date).to eq @new_start_date + @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).detect do |x| + x.reservations.size > 1 end + .reservations + .each { |line| expect(line.start_date).to eq @new_start_date } end When(/^I change the time range for that option$/) do rescue_displaced_flash do - find(".line[data-line-type='option_line'][data-id='#{@option_line.id}']", text: @option_line.option.name) + find( + ".line[data-line-type='option_line'][data-id='#{@option_line.id}']", + text: @option_line.option.name + ) .find('.button', text: _('Change entry')) .click end @@ -100,13 +103,15 @@ @quantity = @option_line.quantity > 1 ? 1 : rand(2..9) find('#booking-calendar-quantity').set @quantity step 'I save the booking calendar' - expect(find(".line[data-id='#{@option_line.id}'] input[data-line-quantity]").value.to_i).to eq @quantity + expect( + find(".line[data-id='#{@option_line.id}'] input[data-line-quantity]").value.to_i + ).to eq @quantity end Then(/^I see the quantity for this option$/) do within('.modal') do within('.modal-body') do - find(".row", text: /#{@quantity}.*#{@selected_items.first.model.name}/) + find('.row', text: /#{@quantity}.*#{@selected_items.first.model.name}/) end end end diff --git a/features/step_definitions/manage/hand_over/sign_contract_steps.rb b/features/step_definitions/manage/hand_over/sign_contract_steps.rb index 9fbc0d17fc..e86924ed6b 100644 --- a/features/step_definitions/manage/hand_over/sign_contract_steps.rb +++ b/features/step_definitions/manage/hand_over/sign_contract_steps.rb @@ -1,13 +1,15 @@ # -*- encoding : utf-8 -*- Given(/^there exists an approved option reservation for a normal user beginning today$/) do - @option_line = FactoryGirl.create(:option_line, - start_date: Date.today, - end_date: Date.tomorrow, - status: :approved, - user: FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool), - inventory_pool: @current_inventory_pool) + @option_line = + FactoryGirl.create( + :option_line, + start_date: Date.today, + end_date: Date.tomorrow, + status: :approved, + user: FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool), + inventory_pool: @current_inventory_pool + ) @customer = @option_line.user end @@ -17,59 +19,63 @@ end When(/^I open a hand over$/) do - @customer = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool) - @contract = @order = FactoryGirl.create(:order, - state: :approved, - user: @customer, - inventory_pool: @current_inventory_pool) + @customer = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) + @contract = + @order = + FactoryGirl.create( + :order, state: :approved, user: @customer, inventory_pool: @current_inventory_pool + ) 3.times do - FactoryGirl.create(:reservation, - status: :approved, - user: @customer, - order: @order, - inventory_pool: @current_inventory_pool) + FactoryGirl.create( + :reservation, + status: :approved, user: @customer, order: @order, inventory_pool: @current_inventory_pool + ) end step 'I open a hand over for this customer' expect(has_selector?('#hand-over-view', visible: true)).to be true end When(/^I open a hand over with at least one unassigned line for today$/) do - @current_inventory_pool = @current_user.inventory_pools.managed.detect do |ip| - @customer = ip.users.not_as_delegations.detect do |user| - user.visits.hand_over.any? do |v| - v.reservations.size >= 3 and v.reservations.any? do |l| - not l.item and l.start_date == ip.next_open_date(Time.zone.today) + @current_inventory_pool = + @current_user.inventory_pools.managed.detect do |ip| + @customer = + ip.users.not_as_delegations.detect do |user| + user.visits.hand_over.any? do |v| + v.reservations.size >= 3 and + v.reservations.any? do |l| + nl.item and l.start_date == ip.next_open_date(Time.zone.today) + end + end end - end end - end open_hand_over_and_set_contract end When(/^I open a hand over for today$/) do - @current_inventory_pool = @current_user.inventory_pools.managed.detect do |ip| - @customer = ip.users.not_as_delegations.detect do |user| - user.visits.hand_over.find { |ho| ho.date == Date.today} + @current_inventory_pool = + @current_user.inventory_pools.managed.detect do |ip| + @customer = + ip.users.not_as_delegations.detect do |user| + user.visits.hand_over.find { |ho| ho.date == Date.today } + end end - end open_hand_over_and_set_contract end When(/^I open a hand over( with options| with models)$/) do |with_options_or_models| - @customer = @current_inventory_pool.users.not_as_delegations.detect do |user| - user.visits.hand_over.where(inventory_pool_id: @current_inventory_pool.id).any? do |v| - v.reservations.any? do |l| - l.is_a? \ - case with_options_or_models + @customer = + @current_inventory_pool.users.not_as_delegations.detect do |user| + user.visits.hand_over.where(inventory_pool_id: @current_inventory_pool.id).any? do |v| + v.reservations.any? do |l| + l.is_a? case with_options_or_models when ' with options' OptionLine when ' with models' ItemLine end + end end end - end open_hand_over_and_set_contract end @@ -82,24 +88,27 @@ def open_hand_over_and_set_contract @contract = @customer.orders.where(inventory_pool_id: @current_inventory_pool).approved.first end -When(/^I open a hand over which has multiple( unassigned)? reservations( and models in stock)?( with software)?$/) do |arg1, arg2, arg3| - @hand_over = if arg1 - if arg2 - @models_in_stock = @current_inventory_pool.items.in_stock.map(&:model).uniq - @current_inventory_pool.visits.hand_over.detect { |v| - b = v.reservations.select { |l| !l.item and @models_in_stock.include? l.model }.count >= 2 - if arg3 - (b and !!v.reservations.detect {|cl| cl.model.is_a? Software }) - else - b - end - } - else - @current_inventory_pool.visits.hand_over.detect { |x| x.reservations.select { |l| !l.item }.count >= 2 } - end - else - @current_inventory_pool.visits.hand_over.detect { |x| x.reservations.size > 1 } - end +When( + / + ^I open a hand over which has multiple( unassigned)? reservations( and models in stock)?( with software)?$ + / +) do |arg1, arg2, arg3| + @hand_over = + if arg1 + if arg2 + @models_in_stock = @current_inventory_pool.items.in_stock.map(&:model).uniq + @current_inventory_pool.visits.hand_over.detect do |v| + b = v.reservations.select { |l| !l.item and @models_in_stock.include? l.model }.count >= 2 + arg3 ? (b and !!v.reservations.detect { |cl| cl.model.is_a? Software }) : b + end + else + @current_inventory_pool.visits.hand_over.detect do |x| + x.reservations.select { |l| !l.item }.count >= 2 + end + end + else + @current_inventory_pool.visits.hand_over.detect { |x| x.reservations.size > 1 } + end expect(@hand_over).not_to be_nil @customer = @hand_over.user @@ -108,39 +117,51 @@ def open_hand_over_and_set_contract end When(/^I open a hand over with reservations that have assigned inventory codes$/) do - steps %Q{ + steps ' When I open a hand over which has multiple unassigned reservations and models in stock And I click an inventory code input field of an item line Then I see a list of inventory codes of items that are in stock and matching the model When I select one of those Then the item line is assigned to the selected inventory code - } + ' end When(/^I open a hand over with overdue reservations$/) do @models_in_stock = @current_inventory_pool.items.in_stock.map(&:model).uniq - @customer = @current_inventory_pool.users.to_a.detect do |u| - u.orders.approved.exists? and u.orders.approved.any? do |c| - c.reservations.any? {|l| l.start_date < Date.today and l.end_date >= Date.today and @models_in_stock.include? l.model} + @customer = + @current_inventory_pool.users.to_a.detect do |u| + u.orders.approved.exists? and + u.orders.approved.any? do |c| + c.reservations.any? do |l| + l.start_date < Date.today and l.end_date >= Date.today and + @models_in_stock.include? l.model + end + end end - end expect(@customer).not_to be_nil step 'I open a hand over for this customer' end -Given(/^I open a hand over which has model which not all accessories are activated for this inventory pool$/) do - @item_line = @current_inventory_pool.item_lines.approved.detect {|il| il.model.accessories.active_in(@current_inventory_pool).count > 1 and il.available? } +Given( + / + ^I open a hand over which has model which not all accessories are activated for this inventory pool$ + / +) do + @item_line = + @current_inventory_pool.item_lines.approved.detect do |il| + il.model.accessories.active_in(@current_inventory_pool).count > 1 and il.available? + end expect(@item_line).not_to be_nil @customer = @item_line.user expect(@customer).not_to be_nil accessory = nil - if @item_line.model.accessories.all? {|a| a.inventory_pools.include? @current_inventory_pool } + if @item_line.model.accessories.all? { |a| a.inventory_pools.include? @current_inventory_pool } accessory = @item_line.model.accessories.sample accessory.inventory_pools.delete @current_inventory_pool end - expect(@item_line.model.accessories.all?{|a| a.active_in? @current_inventory_pool }).to be false - expect(@item_line.model.accessories.any?{|a| a.active_in? @current_inventory_pool }).to be true + expect(@item_line.model.accessories.all? { |a| a.active_in? @current_inventory_pool }).to be false + expect(@item_line.model.accessories.any? { |a| a.active_in? @current_inventory_pool }).to be true expect(accessory.active_in? @current_inventory_pool).to be false if accessory step 'I open a hand over for this customer' @@ -149,7 +170,11 @@ def open_hand_over_and_set_contract When(/^I add the same model$/) do hand_over_assign_or_add @item_line.model.to_s - @item_line = @current_inventory_pool.item_lines.approved.where(item_id: nil, user_id: @customer).order("created_at DESC").first + @item_line = + @current_inventory_pool.item_lines.approved.where(item_id: nil, user_id: @customer).order( + 'created_at DESC' + ) + .first expect(@item_line).not_to be_nil end @@ -184,31 +209,39 @@ def open_hand_over_and_set_contract When(/^I select (an item|a license) line and assign an inventory code$/) do |arg1| @models_in_stock = @current_inventory_pool.items.in_stock.map(&:model).uniq - reservations = @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).flat_map(&:reservations) - - @item_line = @line = case arg1 - when 'an item' - reservations.detect {|l| l.class.to_s == 'ItemLine' and l.item_id.nil? and @models_in_stock.include? l.model } - when 'a license' - reservations.detect {|l| l.class.to_s == 'ItemLine' and l.item_id.nil? and @models_in_stock.include? l.model and l.model.is_a? Software } - else - raise - end + reservations = + @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).flat_map( + &:reservations + ) + + @item_line = + @line = + case arg1 + when 'an item' + reservations.detect do |l| + l.class.to_s == 'ItemLine' and l.item_id.nil? and @models_in_stock.include? l.model + end + when 'a license' + reservations.detect do |l| + l.class.to_s == 'ItemLine' and l.item_id.nil? and @models_in_stock.include? l.model and + l.model.is_a? Software + end + else + raise + end expect(@item_line).not_to be_nil step 'I assign an inventory code to the item line' find('#flash .fa-times-circle').click - find(".button[data-edit-lines][data-ids='[#{"\"#{@item_line.id}"}\"]']").click + find(".button[data-edit-lines][data-ids='[#{"undefined#{@item_line.id}"}undefined]']").click step "I set the start date in the calendar to '#{I18n.l(Date.today)}'" step 'I save the booking calendar' - find(".button[data-edit-lines][data-ids='[#{"\"#{@item_line.id}"}\"]']") + find(".button[data-edit-lines][data-ids='[#{"undefined#{@item_line.id}"}undefined]']") end Then(/^I see a summary of the things I selected for hand over$/) do within('.modal') do - @selected_items.each do |item| - expect(has_content?(item.model.name)).to be true - end + @selected_items.each { |item| expect(has_content?(item.model.name)).to be true } end end @@ -228,21 +261,24 @@ def open_hand_over_and_set_contract end Then(/^the contract is signed for the selected items$/) do - @reservations_to_take_back = @customer.reservations.signed.where(inventory_pool_id: @current_inventory_pool) + @reservations_to_take_back = + @customer.reservations.signed.where(inventory_pool_id: @current_inventory_pool) to_take_back_items = @reservations_to_take_back.map(&:item) - @selected_items.each do |item| - expect(to_take_back_items.include?(item)).to be true - end - reservations = @selected_items.map do |item| - @reservations_to_take_back.find_by(item_id: item) - end + @selected_items.each { |item| expect(to_take_back_items.include?(item)).to be true } + reservations = @selected_items.map { |item| @reservations_to_take_back.find_by(item_id: item) } expect(reservations.map(&:contract).uniq.size).to be 1 - @contract = @customer.contracts.open.where(inventory_pool_id: @current_inventory_pool).detect {|contract| contract.reservations.include? reservations.first} + @contract = + @customer.contracts.open.where(inventory_pool_id: @current_inventory_pool).detect do |contract| + contract.reservations.include? reservations.first + end end When(/^I select an item without assigning an inventory code$/) do - @item_line = @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).first.reservations.detect {|l| l.is_a?(ItemLine) and not l.item } - find(".line[data-id='#{@item_line.id}'] input[type='checkbox'][data-select-line]", visible: true).click + @item_line = + @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).first.reservations + .detect { |l| l.is_a?(ItemLine) and nl.item } + find(".line[data-id='#{@item_line.id}'] input[type='checkbox'][data-select-line]", visible: true) + .click end Then(/^I got an error that i have to assign all selected item reservations$/) do @@ -251,12 +287,7 @@ def open_hand_over_and_set_contract When(/^I change the contract reservations time range to tomorrow$/) do step 'I open the booking calendar for this line' - @new_start_date = - if @line.start_date + 1.day < Date.today - Date.today - else - @line.start_date + 1.day - end + @new_start_date = @line.start_date + 1.day < Date.today ? Date.today : @line.start_date + 1.day expect(has_selector?('.fc-widget-content .fc-day-number')).to be true @new_start_date_element = get_fullcalendar_day_element(@new_start_date) puts "@new_start_date = #{@new_start_date}" @@ -273,12 +304,16 @@ def open_hand_over_and_set_contract end end -Then(/^the reservations start date is today$/) do - expect(@line.reload.start_date).to eq Date.today -end +Then(/^the reservations start date is today$/) { expect(@line.reload.start_date).to eq Date.today } When(/^I select an overdue item line and assign an inventory code$/) do - @item_line = @line = @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).detect{|v| v.date < Date.today}.reservations.detect {|l| l.class.to_s == 'ItemLine' and @models_in_stock.include? l.model} + @item_line = + @line = + @customer.visits.hand_over.where(inventory_pool_id: @current_inventory_pool).detect do |v| + v.date < Date.today + end + .reservations + .detect { |l| l.class.to_s == 'ItemLine' and @models_in_stock.include? l.model } expect(@item_line).not_to be_nil step 'I assign an inventory code to the item line' end diff --git a/features/step_definitions/manage/hand_over_steps.rb b/features/step_definitions/manage/hand_over_steps.rb index 318d0ed701..2359d3691b 100644 --- a/features/step_definitions/manage/hand_over_steps.rb +++ b/features/step_definitions/manage/hand_over_steps.rb @@ -9,9 +9,11 @@ end end - Given(/^there is a hand over with at least (\d+) assigned items for a user$/) do |count| - @hand_over = @current_inventory_pool.visits.hand_over.find {|ho| ho.reservations.select(&:item).size >= count.to_i} + @hand_over = + @current_inventory_pool.visits.hand_over.find do |ho| + ho.reservations.select(&:item).size >= count.to_i + end expect(@hand_over).not_to be_nil end @@ -22,12 +24,11 @@ Then(/^I see the already assigned items and their inventory codes$/) do @hand_over.reservations.each do |line| - next if not line.is_a?(ItemLine) or line.item_id.nil? + next if nline.is_a?(ItemLine) or line.item_id.nil? find("[data-assign-item][disabled][value='#{line.item.inventory_code}']") end end - When(/^the user in this hand over is suspended$/) do ensure_suspended_user(@customer, @current_inventory_pool) step 'I open a hand over to this customer' @@ -35,48 +36,60 @@ # Superseded by sign_contract_steps.rb Given(/^I open a hand over containing software$/) do - @hand_over = @current_inventory_pool.visits.hand_over.detect {|v| v.reservations.any?{|cl| cl.model.is_a? Software } } + @hand_over = + @current_inventory_pool.visits.hand_over.detect do |v| + v.reservations.any? { |cl| cl.model.is_a? Software } + end step 'I open the hand over' end Given(/^there is a hand over with at least one unproblematic model( and an option)?$/) do |arg1| @models_in_stock = @current_inventory_pool.items.in_stock.map(&:model).uniq - @hand_over = @current_inventory_pool.visits.hand_over.detect do |v| - b = v.reservations.select do |line| - !line.start_date.past? and !line.item and @models_in_stock.include?(line.model) - end.count >= 1 - if arg1 and b - b = (b and v.reservations.any? {|line| line.is_a? OptionLine }) + @hand_over = + @current_inventory_pool.visits.hand_over.detect do |v| + b = + v.reservations.select do |line| + !line.start_date.past? and !line.item and @models_in_stock.include?(line.model) + end + .count >= + 1 + b = (b and v.reservations.any? { |line| line.is_a? OptionLine }) if arg1 and b + b end - b - end expect(@hand_over).not_to be_nil end - -Given(/^there is a hand over with at least (one problematic line|an item without room or shelf)$/) do |arg1| - @hand_over = @current_inventory_pool.visits.hand_over.find do |ho| - ho.reservations.any? do |l| - if l.is_a? ItemLine - case arg1 +Given( + /^there is a hand over with at least (one problematic line|an item without room or shelf)$/ +) do |arg1| + @hand_over = + @current_inventory_pool.visits.hand_over.find do |ho| + ho.reservations.any? do |l| + if l.is_a? ItemLine + case arg1 when 'one problematic line' - #old# - # av = l.model.availability_in(@current_inventory_pool).maximum_available_in_period_summed_for_groups(l.start_date, l.end_date, ho.user.entitlement_group_ids) - # l.start_date.past? and av > 1 - not l.complete? + nl.complete? when 'an item without room or shelf' - l.item and (l.item.location.nil? or (l.item.location.room.blank? and l.item.location.shelf.blank?)) + l.item and + (l.item.location.nil? or + (l.item.location.room.blank? and l.item.location.shelf.blank?)) else raise + end end + #old# + # av = l.model.availability_in(@current_inventory_pool).maximum_available_in_period_summed_for_groups(l.start_date, l.end_date, ho.user.entitlement_group_ids) + # l.start_date.past? and av > 1 end end - end expect(@hand_over).not_to be_nil end When(/^I assign an inventory code to the unproblematic model$/) do - @reservation = @hand_over.reservations.find {|l| !l.start_date.past? and !l.item and @models_in_stock.include?(l.model) } + @reservation = + @hand_over.reservations.find do |l| + !l.start_date.past? and !l.item and @models_in_stock.include?(l.model) + end @line_css = ".line[data-id='#{@reservation.id}']" within @line_css do find('input[data-assign-item]').click @@ -89,16 +102,12 @@ expect(@reservation.reload.item).not_to be_nil end - -Then(/^the line is selected$/) do - find(@line_css).find('input[type=checkbox]:checked') -end +Then(/^the line is selected$/) { find(@line_css).find('input[type=checkbox]:checked') } Then(/^the line is highlighted in green$/) do expect(find(@line_css).native.attribute('class')).to include 'green' end - When(/^I deselect the line$/) do rescue_displaced_flash do within @line_css do @@ -124,14 +133,13 @@ end Then(/^problem notifications are shown for the problematic model$/) do - @reservation = @hand_over.reservations.find do |l| - if l.is_a? ItemLine + @reservation = + @hand_over.reservations.find do |l| + nl.complete? if l.is_a? ItemLine #old# # av = l.model.availability_in(@current_inventory_pool).maximum_available_in_period_summed_for_groups(l.start_date, l.end_date, @hand_over.user.entitlement_group_ids) # l.start_date.past? and av > 1 - not l.complete? end - end @line_css = ".line[data-id='#{@reservation.id}']" step 'the problem notifications remain on the line' end @@ -151,9 +159,8 @@ end When(/^I assign an already added item$/) do - @reservation = @hand_over.reservations.find {|l| l.is_a? ItemLine and l.item} - @number_of_lines_with_item_model = \ - all(".line", text: @reservation.model.name).size + @reservation = @hand_over.reservations.find { |l| l.is_a? ItemLine and l.item } + @number_of_lines_with_item_model = all('.line', text: @reservation.model.name).size @line_css = ".line[data-id='#{@reservation.id}']" find(@line_css).find("input[type='checkbox']").click @@ -161,22 +168,21 @@ find('form#assign-or-add button .fa.fa-plus', match: :first).click end - - Then(/^I see the error message 'XY is already assigned to this contract'$/) do - find '#flash', text: _('%s is already assigned to this contract') % @reservation.item.inventory_code + find '#flash', + text: _('%s is already assigned to this contract') % @reservation.item.inventory_code end - Given(/^I open a hand over with at least one assigned item$/) do - @hand_over = @current_inventory_pool.visits.hand_over.find {|ho| ho.reservations.any? &:item_id} + @hand_over = @current_inventory_pool.visits.hand_over.find { |ho| ho.reservations.any? &:item_id } step 'I open the hand over' end Given(/^I open a hand over with at least one assigned item for a normal user$/) do - @hand_over = @current_inventory_pool.visits.hand_over.find do |ho| - ho.reservations.any?(&:item_id) and not ho.user.delegation? - end + @hand_over = + @current_inventory_pool.visits.hand_over.find do |ho| + ho.reservations.any?(&:item_id) and nho.user.delegation? + end step 'I open the hand over' end @@ -190,39 +196,29 @@ Then(/^no new line for this model is added$/) do visit manage_hand_over_path(@current_inventory_pool, @hand_over.user) - find(".line", text: @reservation.model.name) - expect(all(".line", text: @reservation.model.name).size) - .to be == @number_of_lines_with_item_model + find('.line', text: @reservation.model.name) + expect(all('.line', text: @reservation.model.name).size).to be == @number_of_lines_with_item_model end Given(/^there is a default contract note for the inventory pool$/) do expect(@current_inventory_pool.default_contract_note).not_to be_nil end +Then(/^a hand over dialog appears$/) { expect(has_selector?('.modal [data-hand-over]')).to be true } -Then(/^a hand over dialog appears$/) do - expect(has_selector?('.modal [data-hand-over]')).to be true -end - -Then(/^a dialog appears$/) do - expect(has_selector?('.modal')).to be true -end - +Then(/^a dialog appears$/) { expect(has_selector?('.modal')).to be true } Then(/^the contract note field in this dialog is already filled in with the default note$/) do find("textarea[name='note']", text: @current_inventory_pool.default_contract_note) end -Then(/^I can enter some text in the contract note field$/) do - find("textarea[name='note']") -end +Then(/^I can enter some text in the contract note field$/) { find("textarea[name='note']") } When(/^I enter "(.*?)" in the contract note field$/) do |string| field = find("textarea[name='note']") fill_in field[:id], with: string end - When(/^I change the quantity to "(.*?)"$/) do |arg1| within @line_css do find('input[data-line-quantity]').set arg1 @@ -232,7 +228,7 @@ Then(/^the quantity will be restored to the original value$/) do within @line_css do - expect(find("input[data-line-quantity]").value).to eq @option_line.reload.quantity.to_s + expect(find('input[data-line-quantity]').value).to eq @option_line.reload.quantity.to_s end end @@ -248,7 +244,11 @@ end Given(/^a line with an assigned item which doesn't have a location is marked$/) do - @reservation = @hand_over.reservations.where(type: 'ItemLine').find {|l| l.item and (l.item.location.nil? or (l.item.location.room.blank? and l.item.location.shelf.blank?)) } + @reservation = + @hand_over.reservations.where(type: 'ItemLine').find do |l| + l.item and + (l.item.location.nil? or (l.item.location.room.blank? and l.item.location.shelf.blank?)) + end @line_css = ".line[data-id='#{@reservation.id}']" step 'I reselect the line' end @@ -265,7 +265,10 @@ end Given(/^there is a model with a problematic item$/) do - @item = @current_inventory_pool.items.borrowable.in_stock.find {|item| item.is_broken? or item.is_incomplete?} + @item = + @current_inventory_pool.items.borrowable.in_stock.find do |item| + item.is_broken? or item.is_incomplete? + end expect(@item).not_to be_nil @model = @item.model expect(@model).not_to be_nil @@ -291,7 +294,10 @@ end Given(/^there is a model with a retired and a borrowable item$/) do - @model = @current_inventory_pool.models.find { |m| m.items.borrowable.where(retired: nil).exists? and m.items.retired.exists? } + @model = + @current_inventory_pool.models.find do |m| + m.items.borrowable.where(retired: nil).exists? and m.items.retired.exists? + end expect(@model).not_to be_nil @item = @model.items.retired.first end @@ -300,11 +306,15 @@ expect(page).not_to have_selector('.ui-menu .ui-menu-item', text: @item.inventory_code) end -Given(/^there exists an item owned by the current inventory pool but in responsibility of pool "(.*?)"$/) do |arg1| - @item = FactoryGirl.create(:item, - owner: @current_inventory_pool, - inventory_pool: FactoryGirl.create(:inventory_pool, - name: arg1)) +Given( + /^there exists an item owned by the current inventory pool but in responsibility of pool "(.*?)"$/ +) do |arg1| + @item = + FactoryGirl.create( + :item, + owner: @current_inventory_pool, + inventory_pool: FactoryGirl.create(:inventory_pool, name: arg1) + ) end When(/^I assign an owned item where other inventory pool is responsible$/) do @@ -312,6 +322,4 @@ find('#assign-or-add button').click end -Then(/^I unfocus the option line$/) do - find('body').click -end +Then(/^I unfocus the option line$/) { find('body').click } diff --git a/features/step_definitions/manage/inventory_expert_search_steps.rb b/features/step_definitions/manage/inventory_expert_search_steps.rb index c0704d16a0..65edce1f26 100644 --- a/features/step_definitions/manage/inventory_expert_search_steps.rb +++ b/features/step_definitions/manage/inventory_expert_search_steps.rb @@ -1,11 +1,9 @@ # encoding: utf-8 def with_disabled_triggers - ActiveRecord::Base.connection.execute \ - 'SET session_replication_role = REPLICA;' + ActiveRecord::Base.connection.execute 'SET session_replication_role = REPLICA;' yield - ActiveRecord::Base.connection.execute \ - 'SET session_replication_role = DEFAULT;' + ActiveRecord::Base.connection.execute 'SET session_replication_role = DEFAULT;' end def login_as_user(user, _) @@ -26,7 +24,9 @@ def create_inventory_pool end def enable_manager_for_inventory_pool(user, inventory_pool) - FactoryGirl.create(:access_right, user: user, inventory_pool: inventory_pool, role: 'inventory_manager') + FactoryGirl.create( + :access_right, user: user, inventory_pool: inventory_pool, role: 'inventory_manager' + ) end def click_expert_search @@ -43,10 +43,8 @@ def shared_prepare_data user = create_user inventory_pool = create_inventory_pool enable_manager_for_inventory_pool(user, inventory_pool) - { - user: user, - inventory_pool: inventory_pool - } + + { user: user, inventory_pool: inventory_pool } end def shared_open_expert_search(data) @@ -66,23 +64,21 @@ def create_item(inventory_pool) def check_result(expected_items) within('#inventory') do expect(page).to have_selector('.line', count: expected_items.length) - expected_items.each do |item| - find("div[data-item-id='#{item.id}']") - end + expected_items.each { |item| find("div[data-item-id='#{item.id}']") } end end def step_field_generic(field_config, fill_item_1, fill_field) data = shared_prepare_data delete_all_fields - field = create_field(field_config.()) + field = create_field(field_config.call) item_1 = create_item(data[:inventory_pool]) item_2 = create_item(data[:inventory_pool]) - fill_item_1.(item_1, item_2) if fill_item_1 + fill_item_1.call(item_1, item_2) if fill_item_1 shared_open_expert_search(data) check_result([item_1, item_2]) select_field(field) - fill_field.(field, item_1) + fill_field.call(field, item_1) check_result([item_1]) end @@ -90,7 +86,7 @@ def step_field_inventory_code step_field_generic( -> { field_config_inventory_code }, nil, - -> (field, item_1) { fill_type_input(field, item_1.inventory_code) } + ->(field, item_1) { fill_type_input(field, item_1.inventory_code) } ) end @@ -98,7 +94,7 @@ def step_field_model_id step_field_generic( -> { field_config_model_id }, nil, - -> (field, item_1) { fill_type_search_autocomplete(field, item_1.model.product) } + ->(field, item_1) { fill_type_search_autocomplete(field, item_1.model.product) } ) end @@ -106,55 +102,55 @@ def step_field_serial_number step_field_generic( -> { field_config_serial_number }, nil, - -> (field, item_1) { fill_type_input(field, item_1.serial_number) } + ->(field, item_1) { fill_type_input(field, item_1.serial_number) } ) end def step_field_properties_mac_address step_field_generic( -> { field_config_properties_mac_address }, - -> (item_1, item_2) do + lambda do |item_1, item_2| item_1.properties['mac_address'] = 'test-mac-address' item_1.save! item_1.reload end, - -> (field, item_1) { fill_type_input(field, item_1.properties['mac_address']) } + ->(field, item_1) { fill_type_input(field, item_1.properties['mac_address']) } ) end def step_field_properties_imei_number step_field_generic( -> { field_config_properties_imei_number }, - -> (item_1, item_2) do + lambda do |item_1, item_2| item_1.properties['imei_number'] = 'test-imei-number' item_1.save! item_1.reload end, - -> (field, item_1) { fill_type_input(field, item_1.properties['imei_number']) } + ->(field, item_1) { fill_type_input(field, item_1.properties['imei_number']) } ) end def step_field_name step_field_generic( -> { field_config_name }, - -> (item_1, item_2) do + lambda do |item_1, item_2| item_1.name = 'test-name' item_1.save! item_1.reload end, - -> (field, item_1) { fill_type_input(field, item_1.name) } + ->(field, item_1) { fill_type_input(field, item_1.name) } ) end def step_field_note step_field_generic( -> { field_config_note }, - -> (item_1, item_2) do + lambda do |item_1, item_2| item_1.note = 'test-note' item_1.save! item_1.reload end, - -> (field, item_1) { fill_type_textarea(field, item_1.note) } + ->(field, item_1) { fill_type_textarea(field, item_1.note) } ) end @@ -244,12 +240,12 @@ def step_field_is_borrowable def step_field_status_note step_field_generic( -> { field_config_status_note }, - -> (item_1, item_2) do + lambda do |item_1, item_2| item_1.status_note = 'test-status-note' item_1.save! item_1.reload end, - -> (field, item_1) { fill_type_textarea(field, item_1.status_note) } + ->(field, item_1) { fill_type_textarea(field, item_1.status_note) } ) end @@ -274,12 +270,12 @@ def step_fields_building_id_and_room_id def step_field_shelf step_field_generic( -> { field_config_shelf }, - -> (item_1, item_2) do + lambda do |item_1, item_2| item_1.shelf = 'test-shelf' item_1.save! item_1.reload end, - -> (field, item_1) { fill_type_input(field, item_1.shelf) } + ->(field, item_1) { fill_type_input(field, item_1.shelf) } ) end @@ -305,7 +301,7 @@ def step_field_owner_id step_field_generic( -> { field_config_owner_id }, nil, - -> (field, item_1) { fill_type_search_autocomplete(field, item_1.owner.name) } + ->(field, item_1) { fill_type_search_autocomplete(field, item_1.owner.name) } ) end @@ -356,12 +352,12 @@ def step_field_inventory_pool_id def step_field_responsible step_field_generic( -> { field_config_responsible }, - -> (item_1, item_2) do + lambda do |item_1, item_2| item_1.responsible = 'test-responsible' item_1.save! item_1.reload end, - -> (field, item_1) { fill_type_input(field, item_1.responsible) } + ->(field, item_1) { fill_type_input(field, item_1.responsible) } ) end @@ -427,7 +423,7 @@ def fill_type_search_autocomplete(field, text) end def fill_type_date(fromTo, field, text_date) - label = \ + label = if fromTo == :from 'von' elsif fromTo == :to @@ -435,14 +431,17 @@ def fill_type_date(fromTo, field, text_date) else throw 'Unexpected from/to: ' + fromTo.to_s end - input = find_field_box(field).find('div.col1of2[data-type=value]').find('div', text: label).find('input') + input = + find_field_box(field).find('div.col1of2[data-type=value]').find('div', text: label).find( + 'input' + ) input.set('') input.native.send_key :enter input.set(text_date) end def fill_type_currency(minMax, field, text_value) - label = \ + label = if minMax == :min 'min' elsif minMax == :max @@ -450,606 +449,463 @@ def fill_type_currency(minMax, field, text_value) else throw 'Unexpected from/to: ' + fromTo.to_s end - find_field_box(field).find('div.col1of2[data-type=value]').find('div', text: label).find('input').set(text_value) + find_field_box(field).find('div.col1of2[data-type=value]').find('div', text: label).find('input') + .set(text_value) end -Then(/^Step Field Inventory Code$/) do - step_field_inventory_code -end +Then(/^Step Field Inventory Code$/) { step_field_inventory_code } -Then(/^Step Field Model Id$/) do - step_field_model_id -end +Then(/^Step Field Model Id$/) { step_field_model_id } -Then(/^Step Field Serial Number$/) do - step_field_serial_number -end +Then(/^Step Field Serial Number$/) { step_field_serial_number } -Then(/^Step Field Properties Mac Address$/) do - step_field_properties_mac_address -end +Then(/^Step Field Properties Mac Address$/) { step_field_properties_mac_address } -Then(/^Step Field Properties Imei Number$/) do - step_field_properties_imei_number -end +Then(/^Step Field Properties Imei Number$/) { step_field_properties_imei_number } -Then(/^Step Field Name$/) do - step_field_name -end +Then(/^Step Field Name$/) { step_field_name } -Then(/^Step Field Note$/) do - step_field_note -end +Then(/^Step Field Note$/) { step_field_note } -Then(/^Step Fields Retired and Retired Reason$/) do - step_field_retired_and_retired_reason -end +Then(/^Step Fields Retired and Retired Reason$/) { step_field_retired_and_retired_reason } -Then(/^Step Field Is Broken$/) do - step_field_is_broken -end +Then(/^Step Field Is Broken$/) { step_field_is_broken } -Then(/^Step Field Is Incomplete$/) do - step_field_is_incomplete -end +Then(/^Step Field Is Incomplete$/) { step_field_is_incomplete } -Then(/^Step Field Is Borrowable$/) do - step_field_is_borrowable -end +Then(/^Step Field Is Borrowable$/) { step_field_is_borrowable } -Then(/^Step Field Status Note$/) do - step_field_status_note -end +Then(/^Step Field Status Note$/) { step_field_status_note } -Then(/^Step Fields Building Id and Room Id$/) do - step_fields_building_id_and_room_id -end +Then(/^Step Fields Building Id and Room Id$/) { step_fields_building_id_and_room_id } -Then(/^Step Field Shelf$/) do - step_field_shelf -end +Then(/^Step Field Shelf$/) { step_field_shelf } -Then(/^Step Field Is Inventory Relevant$/) do - step_field_is_inventory_relevant -end +Then(/^Step Field Is Inventory Relevant$/) { step_field_is_inventory_relevant } -Then(/^Step Field Owner Id$/) do - step_field_owner_id -end +Then(/^Step Field Owner Id$/) { step_field_owner_id } -Then(/^Step Field Last Check$/) do - step_field_last_check -end +Then(/^Step Field Last Check$/) { step_field_last_check } -Then(/^Step Field Inventory Pool Id$/) do - step_field_inventory_pool_id -end +Then(/^Step Field Inventory Pool Id$/) { step_field_inventory_pool_id } -Then(/^Step Field Responsible$/) do - step_field_responsible -end +Then(/^Step Field Responsible$/) { step_field_responsible } -Then(/^Step Field Price$/) do - step_field_price -end +Then(/^Step Field Price$/) { step_field_price } def field_config_inventory_code { - "id":"inventory_code", - "data":{ - "label":"Inventory Code", - "attribute":"inventory_code", - "required":true, - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "type":"text", - "group":nil, - "forPackage":true - }, - "active":true, - "position":1 + :"id" => 'inventory_code', + :"data" => { + :"label" => 'Inventory Code', + :"attribute" => 'inventory_code', + :"required" => true, + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"type" => 'text', + :"group" => nil, + :"forPackage" => true + }, + :"active" => true, + :"position" => 1 } end def field_config_model_id { - "id":"model_id", - "data":{ - "label":"Model", - "attribute":[ - "model", - "id" - ], - "item_value_label":[ - "model", - "product" - ], - "item_value_label_ext":[ - "model", - "version" - ], - "form_name":"model_id", - "required":true, - "type":"autocomplete-search", - "target_type":"item", - "search_path":"models", - "search_attr":"search_term", - "value_attr":"id", - "display_attr":"product", - "display_attr_ext":"version", - "group":nil - }, - "active":true, - "position":2 + :"id" => 'model_id', + :"data" => { + :"label" => 'Model', + :"attribute" => ['model', 'id'], + :"item_value_label" => ['model', 'product'], + :"item_value_label_ext" => ['model', 'version'], + :"form_name" => 'model_id', + :"required" => true, + :"type" => 'autocomplete-search', + :"target_type" => 'item', + :"search_path" => 'models', + :"search_attr" => 'search_term', + :"value_attr" => 'id', + :"display_attr" => 'product', + :"display_attr_ext" => 'version', + :"group" => nil + }, + :"active" => true, + :"position" => 2 } end def field_config_software_model_id { - "id":"software_model_id", - "data":{ - "label":"Software", - "attribute":[ - "model", - "id" - ], - "item_value_label":[ - "model", - "product" - ], - "item_value_label_ext":[ - "model", - "version" - ], - "form_name":"model_id", - "required":true, - "type":"autocomplete-search", - "target_type":"license", - "search_path":"software", - "search_attr":"search_term", - "value_attr":"id", - "display_attr":"product", - "display_attr_ext":"version", - "group":nil - }, - "active":true, - "position":3 + :"id" => 'software_model_id', + :"data" => { + :"label" => 'Software', + :"attribute" => ['model', 'id'], + :"item_value_label" => ['model', 'product'], + :"item_value_label_ext" => ['model', 'version'], + :"form_name" => 'model_id', + :"required" => true, + :"type" => 'autocomplete-search', + :"target_type" => 'license', + :"search_path" => 'software', + :"search_attr" => 'search_term', + :"value_attr" => 'id', + :"display_attr" => 'product', + :"display_attr_ext" => 'version', + :"group" => nil + }, + :"active" => true, + :"position" => 3 } end def field_config_serial_number { - "id":"serial_number", - "data":{ - "label":"Serial Number", - "attribute":"serial_number", - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"text", - "group":"General Information" - }, - "active":true, - "position":4 + :"id" => 'serial_number', + :"data" => { + :"label" => 'Serial Number', + :"attribute" => 'serial_number', + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'text', + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 4 } end def field_config_properties_mac_address { - "id":"properties_mac_address", - "data":{ - "label":"MAC-Address", - "attribute":[ - "properties", - "mac_address" - ], - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"text", - "target_type":"item", - "group":"General Information" - }, - "active":true, - "position":5 + :"id" => 'properties_mac_address', + :"data" => { + :"label" => 'MAC-Address', + :"attribute" => ['properties', 'mac_address'], + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'text', + :"target_type" => 'item', + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 5 } end def field_config_properties_imei_number { - "id":"properties_imei_number", - "data":{ - "label":"IMEI-Number", - "attribute":[ - "properties", - "imei_number" - ], - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"text", - "target_type":"item", - "group":"General Information" - }, - "active":true, - "position":6 + :"id" => 'properties_imei_number', + :"data" => { + :"label" => 'IMEI-Number', + :"attribute" => ['properties', 'imei_number'], + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'text', + :"target_type" => 'item', + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 6 } end def field_config_name { - "id":"name", - "data":{ - "label":"Name", - "attribute":"name", - "type":"text", - "target_type":"item", - "group":"General Information", - "forPackage":true - }, - "active":true, - "position":7 + :"id" => 'name', + :"data" => { + :"label" => 'Name', + :"attribute" => 'name', + :"type" => 'text', + :"target_type" => 'item', + :"group" => 'General Information', + :"forPackage" => true + }, + :"active" => true, + :"position" => 7 } end def field_config_note { - "id":"note", - "data":{ - "label":"Note", - "attribute":"note", - "type":"textarea", - "group":"General Information", - "forPackage":true - }, - "active":true, - "position":8 + :"id" => 'note', + :"data" => { + :"label" => 'Note', + :"attribute" => 'note', + :"type" => 'textarea', + :"group" => 'General Information', + :"forPackage" => true + }, + :"active" => true, + :"position" => 8 } end def field_config_retired { - "id":"retired", - "data":{ - "label":"Retirement", - "attribute":"retired", - "type":"select", - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "values":[ - { - "label":"No", - "value":false - }, - { - "label":"Yes", - "value":true - } - ], - "default":false, - "group":"Status" - }, - "active":true, - "position":9 + :"id" => 'retired', + :"data" => { + :"label" => 'Retirement', + :"attribute" => 'retired', + :"type" => 'select', + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"values" => [ + { :"label" => 'No', :"value" => false }, { :"label" => 'Yes', :"value" => true } + ], + :"default" => false, + :"group" => 'Status' + }, + :"active" => true, + :"position" => 9 } end def field_config_retired_reason { - "id":"retired_reason", - "data":{ - "label":"Reason for Retirement", - "attribute":"retired_reason", - "type":"textarea", - "required":true, - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "visibility_dependency_field_id":"retired", - "visibility_dependency_value":"true", - "group":"Status" - }, - "active":true, - "position":10 + :"id" => 'retired_reason', + :"data" => { + :"label" => 'Reason for Retirement', + :"attribute" => 'retired_reason', + :"type" => 'textarea', + :"required" => true, + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"visibility_dependency_field_id" => 'retired', + :"visibility_dependency_value" => 'true', + :"group" => 'Status' + }, + :"active" => true, + :"position" => 10 } end def field_config_is_broken { - "id":"is_broken", - "data":{ - "label":"Working order", - "attribute":"is_broken", - "type":"radio", - "target_type":"item", - "values":[ - { - "label":"OK", - "value":false - }, - { - "label":"Broken", - "value":true - } - ], - "default":false, - "group":"Status", - "forPackage":true - }, - "active":true, - "position":11 + :"id" => 'is_broken', + :"data" => { + :"label" => 'Working order', + :"attribute" => 'is_broken', + :"type" => 'radio', + :"target_type" => 'item', + :"values" => [ + { :"label" => 'OK', :"value" => false }, { :"label" => 'Broken', :"value" => true } + ], + :"default" => false, + :"group" => 'Status', + :"forPackage" => true + }, + :"active" => true, + :"position" => 11 } end def field_config_is_incomplete { - "id":"is_incomplete", - "data":{ - "label":"Completeness", - "attribute":"is_incomplete", - "type":"radio", - "target_type":"item", - "values":[ - { - "label":"OK", - "value":false - }, - { - "label":"Incomplete", - "value":true - } - ], - "default":false, - "group":"Status", - "forPackage":true - }, - "active":true, - "position":12 + :"id" => 'is_incomplete', + :"data" => { + :"label" => 'Completeness', + :"attribute" => 'is_incomplete', + :"type" => 'radio', + :"target_type" => 'item', + :"values" => [ + { :"label" => 'OK', :"value" => false }, { :"label" => 'Incomplete', :"value" => true } + ], + :"default" => false, + :"group" => 'Status', + :"forPackage" => true + }, + :"active" => true, + :"position" => 12 } end def field_config_is_borrowable { - "id":"is_borrowable", - "data":{ - "label":"Borrowable", - "attribute":"is_borrowable", - "type":"radio", - "values":[ - { - "label":"OK", - "value":true - }, - { - "label":"Unborrowable", - "value":false - } - ], - "default":false, - "group":"Status", - "forPackage":true - }, - "active":true, - "position":13 + :"id" => 'is_borrowable', + :"data" => { + :"label" => 'Borrowable', + :"attribute" => 'is_borrowable', + :"type" => 'radio', + :"values" => [ + { :"label" => 'OK', :"value" => true }, { :"label" => 'Unborrowable', :"value" => false } + ], + :"default" => false, + :"group" => 'Status', + :"forPackage" => true + }, + :"active" => true, + :"position" => 13 } end def field_config_status_note { - "id":"status_note", - "data":{ - "label":"Status note", - "attribute":"status_note", - "type":"textarea", - "target_type":"item", - "group":"Status", - "forPackage":true - }, - "active":true, - "position":14 + :"id" => 'status_note', + :"data" => { + :"label" => 'Status note', + :"attribute" => 'status_note', + :"type" => 'textarea', + :"target_type" => 'item', + :"group" => 'Status', + :"forPackage" => true + }, + :"active" => true, + :"position" => 14 } end def field_config_building_id { - "id":"building_id", - "data":{ - "label":"Building", - "attribute":[ - "room", - "building_id" - ], - "required":true, - "exclude_from_submit":true, - "type":"autocomplete", - "target_type":"item", - "values":"all_buildings", - "group":"Location", - "forPackage":true - }, - "active":true, - "position":15 + :"id" => 'building_id', + :"data" => { + :"label" => 'Building', + :"attribute" => ['room', 'building_id'], + :"required" => true, + :"exclude_from_submit" => true, + :"type" => 'autocomplete', + :"target_type" => 'item', + :"values" => 'all_buildings', + :"group" => 'Location', + :"forPackage" => true + }, + :"active" => true, + :"position" => 15 } end def field_config_room_id { - "id":"room_id", - "data":{ - "label":"Room", - "attribute":"room_id", - "required":true, - "type":"autocomplete", - "target_type":"item", - "values_dependency_field_id":"building_id", - "values_url":"/manage/rooms.json?building_id=$$$parent_value$$$", - "values_label_method":"to_s", - "group":"Location", - "forPackage":true - }, - "active":true, - "position":16 + :"id" => 'room_id', + :"data" => { + :"label" => 'Room', + :"attribute" => 'room_id', + :"required" => true, + :"type" => 'autocomplete', + :"target_type" => 'item', + :"values_dependency_field_id" => 'building_id', + :"values_url" => '/manage/rooms.json?building_id=$$$parent_value$$$', + :"values_label_method" => 'to_s', + :"group" => 'Location', + :"forPackage" => true + }, + :"active" => true, + :"position" => 16 } end def field_config_shelf { - "id":"shelf", - "data":{ - "label":"Shelf", - "attribute":"shelf", - "type":"text", - "target_type":"item", - "group":"Location", - "forPackage":true - }, - "active":true, - "position":17 + :"id" => 'shelf', + :"data" => { + :"label" => 'Shelf', + :"attribute" => 'shelf', + :"type" => 'text', + :"target_type" => 'item', + :"group" => 'Location', + :"forPackage" => true + }, + :"active" => true, + :"position" => 17 } end def field_config_is_inventory_relevant { - "id":"is_inventory_relevant", - "data":{ - "label":"Relevant for inventory", - "attribute":"is_inventory_relevant", - "type":"select", - "target_type":"item", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "values":[ - { - "label":"No", - "value":false - }, - { - "label":"Yes", - "value":true - } - ], - "default":true, - "group":"Inventory", - "forPackage":true - }, - "active":true, - "position":18 + :"id" => 'is_inventory_relevant', + :"data" => { + :"label" => 'Relevant for inventory', + :"attribute" => 'is_inventory_relevant', + :"type" => 'select', + :"target_type" => 'item', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"values" => [ + { :"label" => 'No', :"value" => false }, { :"label" => 'Yes', :"value" => true } + ], + :"default" => true, + :"group" => 'Inventory', + :"forPackage" => true + }, + :"active" => true, + :"position" => 18 } end def field_config_owner_id { - "id":"owner_id", - "data":{ - "label":"Owner", - "attribute":[ - "owner", - "id" - ], - "type":"autocomplete", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "values":"all_inventory_pools", - "group":"Inventory" - }, - "active":true, - "position":19 + :"id" => 'owner_id', + :"data" => { + :"label" => 'Owner', + :"attribute" => ['owner', 'id'], + :"type" => 'autocomplete', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"values" => 'all_inventory_pools', + :"group" => 'Inventory' + }, + :"active" => true, + :"position" => 19 } end def field_config_last_check { - "id":"last_check", - "data":{ - "label":"Last Checked", - "attribute":"last_check", - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "default":"today", - "type":"date", - "target_type":"item", - "group":"Inventory", - "forPackage":true - }, - "active":true, - "position":20 + :"id" => 'last_check', + :"data" => { + :"label" => 'Last Checked', + :"attribute" => 'last_check', + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"default" => 'today', + :"type" => 'date', + :"target_type" => 'item', + :"group" => 'Inventory', + :"forPackage" => true + }, + :"active" => true, + :"position" => 20 } end def field_config_inventory_pool_id { - "id":"inventory_pool_id", - "data":{ - "label":"Responsible department", - "attribute":[ - "inventory_pool", - "id" - ], - "type":"autocomplete", - "values":"all_inventory_pools", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"Inventory", - "forPackage":true - }, - "active":true, - "position":21 + :"id" => 'inventory_pool_id', + :"data" => { + :"label" => 'Responsible department', + :"attribute" => ['inventory_pool', 'id'], + :"type" => 'autocomplete', + :"values" => 'all_inventory_pools', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'Inventory', + :"forPackage" => true + }, + :"active" => true, + :"position" => 21 } end def field_config_responsible { - "id":"responsible", - "data":{ - "label":"Responsible person", - "attribute":"responsible", - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"text", - "target_type":"item", - "group":"Inventory", - "forPackage":true - }, - "active":true, - "position":22 - } + :"id" => 'responsible', + :"data" => { + :"label" => 'Responsible person', + :"attribute" => 'responsible', + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'text', + :"target_type" => 'item', + :"group" => 'Inventory', + :"forPackage" => true + }, + :"active" => true, + :"position" => 22 + } end def field_config_price { - "id":"price", - "data":{ - "label":"Initial Price", - "attribute":"price", - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"text", - "currency":true, - "group":"Invoice Information", - "forPackage":true - }, - "active":true, - "position":28 + :"id" => 'price', + :"data" => { + :"label" => 'Initial Price', + :"attribute" => 'price', + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'text', + :"currency" => true, + :"group" => 'Invoice Information', + :"forPackage" => true + }, + :"active" => true, + :"position" => 28 } end @@ -1075,723 +931,426 @@ def fields_config field_config_owner_id, field_config_last_check, field_config_inventory_pool_id, - field_config_responsible, - { - "id":"user_name", - "data":{ - "label":"User/Typical usage", - "attribute":"user_name", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "type":"text", - "target_type":"item", - "group":"Inventory", - "forPackage":true - }, - "active":true, - "position":23 - }, - { - "id":"properties_reference", - "data":{ - "label":"Reference", - "attribute":[ - "properties", - "reference" - ], - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "required":true, - "values":[ - { - "label":"Running Account", - "value":"invoice" - }, - { - "label":"Investment", - "value":"investment" - } - ], - "default":"invoice", - "type":"radio", - "group":"Invoice Information" - }, - "active":true, - "position":24 - }, - { - "id":"properties_project_number", - "data":{ - "label":"Project Number", - "attribute":[ - "properties", - "project_number" - ], - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "type":"text", - "required":true, - "visibility_dependency_field_id":"properties_reference", - "visibility_dependency_value":"investment", - "group":"Invoice Information" - }, - "active":true, - "position":25 - }, - { - "id":"invoice_number", - "data":{ - "label":"Invoice Number", - "attribute":"invoice_number", - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"text", - "target_type":"item", - "group":"Invoice Information" - }, - "active":true, - "position":26 - }, - { - "id":"invoice_date", - "data":{ - "label":"Invoice Date", - "attribute":"invoice_date", - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"date", - "group":"Invoice Information" - }, - "active":true, - "position":27 - }, - field_config_price, - { - "id":"supplier_id", - "data":{ - "label":"Supplier", - "attribute":[ - "supplier", - "id" - ], - "type":"autocomplete", - "extensible":true, - "extended_key":[ - "supplier", - "name" - ], - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "values":"all_suppliers", - "group":"Invoice Information" - }, - "active":true, - "position":29 - }, - { - "id":"properties_warranty_expiration", - "data":{ - "label":"Warranty expiration", - "attribute":[ - "properties", - "warranty_expiration" - ], - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"date", - "target_type":"item", - "group":"Invoice Information" - }, - "active":true, - "position":30 - }, - { - "id":"properties_contract_expiration", - "data":{ - "label":"Contract expiration", - "attribute":[ - "properties", - "contract_expiration" - ], - "permissions":{ - "role":"lending_manager", - "owner":true - }, - "type":"date", - "target_type":"item", - "group":"Invoice Information" - }, - "active":true, - "position":31 - }, - { - "id":"properties_activation_type", - "data":{ - "label":"Activation Type", - "attribute":[ - "properties", - "activation_type" - ], - "type":"select", - "target_type":"license", - "values":[ - { - "label":"None", - "value":"none" - }, - { - "label":"Dongle", - "value":"dongle" - }, - { - "label":"Serial Number", - "value":"serial_number" - }, - { - "label":"License Server", - "value":"license_server" - }, - { - "label":"Challenge Response/System ID", - "value":"challenge_response" - } - ], - "default":"none", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"General Information" - }, - "active":true, - "position":32 - }, - { - "id":"properties_dongle_id", - "data":{ - "label":"Dongle ID", - "attribute":[ - "properties", - "dongle_id" - ], - "type":"text", - "target_type":"license", - "required":true, - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "visibility_dependency_field_id":"properties_activation_type", - "visibility_dependency_value":"dongle", - "group":"General Information" - }, - "active":true, - "position":33 - }, - { - "id":"properties_license_type", - "data":{ - "label":"License Type", - "attribute":[ - "properties", - "license_type" - ], - "type":"select", - "target_type":"license", - "values":[ - { - "label":"Free", - "value":"free" - }, - { - "label":"Single Workplace", - "value":"single_workplace" - }, - { - "label":"Multiple Workplace", - "value":"multiple_workplace" - }, - { - "label":"Site License", - "value":"site_license" - }, - { - "label":"Concurrent", - "value":"concurrent" - } - ], - "default":"free", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"General Information" - }, - "active":true, - "position":34 - }, - { - "id":"properties_total_quantity", - "data":{ - "label":"Total quantity", - "attribute":[ - "properties", - "total_quantity" - ], - "type":"text", - "target_type":"license", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "visibility_dependency_field_id":"properties_license_type", - "visibility_dependency_value":[ - "multiple_workplace", - "site_license", - "concurrent" - ], - "group":"General Information" - }, - "active":true, - "position":35 - }, - { - "id":"properties_quantity_allocations", - "data":{ - "label":"Quantity allocations", - "attribute":[ - "properties", - "quantity_allocations" - ], - "type":"composite", - "target_type":"license", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "visibility_dependency_field_id":"properties_total_quantity", - "data_dependency_field_id":"properties_total_quantity", - "group":"General Information" - }, - "active":true, - "position":36 - }, - { - "id":"properties_operating_system", - "data":{ - "label":"Operating System", - "attribute":[ - "properties", - "operating_system" - ], - "type":"checkbox", - "target_type":"license", - "values":[ - { - "label":"Windows", - "value":"windows" - }, - { - "label":"Mac OS X", - "value":"mac_os_x" - }, - { - "label":"Linux", - "value":"linux" - }, - { - "label":"iOS", - "value":"ios" - } - ], - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"General Information" - }, - "active":true, - "position":37 - }, - { - "id":"properties_installation", - "data":{ - "label":"Installation", - "attribute":[ - "properties", - "installation" - ], - "type":"checkbox", - "target_type":"license", - "values":[ - { - "label":"Citrix", - "value":"citrix" - }, - { - "label":"Local", - "value":"local" - }, - { - "label":"Web", - "value":"web" - } - ], - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"General Information" - }, - "active":true, - "position":38 - }, - { - "id":"properties_license_expiration", - "data":{ - "label":"License expiration", - "attribute":[ - "properties", - "license_expiration" - ], - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "type":"date", - "target_type":"license", - "group":"General Information" - }, - "active":true, - "position":39 - }, - { - "id":"properties_maintenance_contract", - "data":{ - "label":"Maintenance contract", - "attribute":[ - "properties", - "maintenance_contract" - ], - "type":"select", - "target_type":"license", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "values":[ - { - "label":"No", - "value":"false" - }, - { - "label":"Yes", - "value":"true" - } - ], - "default":"false", - "group":"Maintenance" - }, - "active":true, - "position":40 - }, - { - "id":"properties_maintenance_expiration", - "data":{ - "label":"Maintenance expiration", - "attribute":[ - "properties", - "maintenance_expiration" - ], - "type":"date", - "target_type":"license", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "visibility_dependency_field_id":"properties_maintenance_contract", - "visibility_dependency_value":"true", - "group":"Maintenance" - }, - "active":true, - "position":41 - }, - { - "id":"properties_maintenance_currency", - "data":{ - "label":"Currency", - "attribute":[ - "properties", - "maintenance_currency" - ], - "type":"select", - "values":"all_currencies", - "default":"CHF", - "target_type":"license", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "visibility_dependency_field_id":"properties_maintenance_expiration", - "group":"Maintenance" - }, - "active":true, - "position":42 - }, - { - "id":"properties_maintenance_price", - "data":{ - "label":"Price", - "attribute":[ - "properties", - "maintenance_price" - ], - "type":"text", - "currency":true, - "target_type":"license", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "visibility_dependency_field_id":"properties_maintenance_currency", - "group":"Maintenance" - }, - "active":true, - "position":43 - }, - { - "id":"properties_procured_by", - "data":{ - "label":"Procured by", - "attribute":[ - "properties", - "procured_by" - ], - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "type":"text", - "target_type":"license", - "group":"Invoice Information" - }, - "active":true, - "position":44 - }, - { - "id":"attachments", - "data":{ - "label":"Attachments", - "attribute":"attachments", - "type":"attachment", - "group":"General Information", - "permissions":{ - "role":"inventory_manager", - "owner":true - } - }, - "active":true, - "position":45 - }, - { - "id":"properties_umzug", - "data":{ - "label":"Umzug", - "attribute":[ - "properties", - "umzug" - ], - "type":"select", - "target_type":"item", - "values":[ - { - "label":"zügeln", - "value":"zügeln" - }, - { - "label":"sofort entsorgen", - "value":"sofort entsorgen" - }, - { - "label":"bei Umzug entsorgen", - "value":"bei Umzug entsorgen" - }, - { - "label":"bei Umzug verkaufen", - "value":"bei Umzug verkaufen" - } - ], - "default":"zügeln", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"Umzug" - }, - "active":true, - "position":46 - }, - { - "id":"properties_zielraum", - "data":{ - "label":"Zielraum", - "attribute":[ - "properties", - "zielraum" - ], - "type":"text", - "target_type":"item", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"Umzug" - }, - "active":true, - "position":47 - }, - { - "id":"properties_ankunftsdatum", - "data":{ - "label":"Ankunftsdatum", - "attribute":[ - "properties", - "ankunftsdatum" - ], - "type":"date", - "target_type":"item", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"Toni Ankunftskontrolle" - }, - "active":true, - "position":48 - }, - { - "id":"properties_ankunftszustand", - "data":{ - "label":"Ankunftszustand", - "attribute":[ - "properties", - "ankunftszustand" - ], - "type":"select", - "target_type":"item", - "values":[ - { - "label":"intakt", - "value":"intakt" - }, - { - "label":"transportschaden", - "value":"transportschaden" - } - ], - "default":"intakt", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"Toni Ankunftskontrolle" - }, - "active":true, - "position":49 - }, - { - "id":"properties_ankunftsnotiz", - "data":{ - "label":"Ankunftsnotiz", - "attribute":[ - "properties", - "ankunftsnotiz" - ], - "type":"textarea", - "target_type":"item", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"Toni Ankunftskontrolle" - }, - "active":true, - "position":50 - }, - { - "id":"properties_anschaffungskategorie", - "data":{ - "label":"Beschaffungsgruppe", - "attribute":[ - "properties", - "anschaffungskategorie" - ], - "value_label":[ - "properties", - "anschaffungskategorie" - ], - "required":true, - "type":"select", - "target_type":"item", - "values":[ - { - "label":"", - "value":nil - }, - { - "label":"Werkstatt-Technik", - "value":"Werkstatt-Technik" - }, - { - "label":"Produktionstechnik", - "value":"Produktionstechnik" - }, - { - "label":"AV-Technik", - "value":"AV-Technik" - }, - { - "label":"Musikinstrumente", - "value":"Musikinstrumente" - }, - { - "label":"Facility Management", - "value":"Facility Management" - }, - { - "label":"IC-Technik/Software", - "value":"IC-Technik/Software" - }, - { - "label":"Durch Kunde beschafft", - "value":"Durch Kunde beschafft" - } - ], - "default":nil, - "visibility_dependency_field_id":"is_inventory_relevant", - "visibility_dependency_value":"true", - "permissions":{ - "role":"inventory_manager", - "owner":true - }, - "group":"Inventory" - }, - "active":true, - "position":51 - } + field_config_responsible, { + :"id" => 'user_name', + :"data" => { + :"label" => 'User/Typical usage', + :"attribute" => 'user_name', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"type" => 'text', + :"target_type" => 'item', + :"group" => 'Inventory', + :"forPackage" => true + }, + :"active" => true, + :"position" => 23 + }, { + :"id" => 'properties_reference', + :"data" => { + :"label" => 'Reference', + :"attribute" => ['properties', 'reference'], + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"required" => true, + :"values" => [ + { :"label" => 'Running Account', :"value" => 'invoice' }, { + :"label" => 'Investment', :"value" => 'investment' + } + ], + :"default" => 'invoice', + :"type" => 'radio', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 24 + }, { + :"id" => 'properties_project_number', + :"data" => { + :"label" => 'Project Number', + :"attribute" => ['properties', 'project_number'], + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"type" => 'text', + :"required" => true, + :"visibility_dependency_field_id" => 'properties_reference', + :"visibility_dependency_value" => 'investment', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 25 + }, { + :"id" => 'invoice_number', + :"data" => { + :"label" => 'Invoice Number', + :"attribute" => 'invoice_number', + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'text', + :"target_type" => 'item', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 26 + }, { + :"id" => 'invoice_date', + :"data" => { + :"label" => 'Invoice Date', + :"attribute" => 'invoice_date', + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'date', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 27 + }, + field_config_price, { + :"id" => 'supplier_id', + :"data" => { + :"label" => 'Supplier', + :"attribute" => ['supplier', 'id'], + :"type" => 'autocomplete', + :"extensible" => true, + :"extended_key" => ['supplier', 'name'], + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"values" => 'all_suppliers', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 29 + }, { + :"id" => 'properties_warranty_expiration', + :"data" => { + :"label" => 'Warranty expiration', + :"attribute" => ['properties', 'warranty_expiration'], + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'date', + :"target_type" => 'item', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 30 + }, { + :"id" => 'properties_contract_expiration', + :"data" => { + :"label" => 'Contract expiration', + :"attribute" => ['properties', 'contract_expiration'], + :"permissions" => { :"role" => 'lending_manager', :"owner" => true }, + :"type" => 'date', + :"target_type" => 'item', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 31 + }, { + :"id" => 'properties_activation_type', + :"data" => { + :"label" => 'Activation Type', + :"attribute" => ['properties', 'activation_type'], + :"type" => 'select', + :"target_type" => 'license', + :"values" => [ + { :"label" => 'None', :"value" => 'none' }, { + :"label" => 'Dongle', :"value" => 'dongle' + }, { :"label" => 'Serial Number', :"value" => 'serial_number' }, { + :"label" => 'License Server', :"value" => 'license_server' + }, { :"label" => 'Challenge Response/System ID', :"value" => 'challenge_response' } + ], + :"default" => 'none', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 32 + }, { + :"id" => 'properties_dongle_id', + :"data" => { + :"label" => 'Dongle ID', + :"attribute" => ['properties', 'dongle_id'], + :"type" => 'text', + :"target_type" => 'license', + :"required" => true, + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"visibility_dependency_field_id" => 'properties_activation_type', + :"visibility_dependency_value" => 'dongle', + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 33 + }, { + :"id" => 'properties_license_type', + :"data" => { + :"label" => 'License Type', + :"attribute" => ['properties', 'license_type'], + :"type" => 'select', + :"target_type" => 'license', + :"values" => [ + { :"label" => 'Free', :"value" => 'free' }, { + :"label" => 'Single Workplace', :"value" => 'single_workplace' + }, { :"label" => 'Multiple Workplace', :"value" => 'multiple_workplace' }, { + :"label" => 'Site License', :"value" => 'site_license' + }, { :"label" => 'Concurrent', :"value" => 'concurrent' } + ], + :"default" => 'free', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 34 + }, { + :"id" => 'properties_total_quantity', + :"data" => { + :"label" => 'Total quantity', + :"attribute" => ['properties', 'total_quantity'], + :"type" => 'text', + :"target_type" => 'license', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"visibility_dependency_field_id" => 'properties_license_type', + :"visibility_dependency_value" => ['multiple_workplace', 'site_license', 'concurrent'], + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 35 + }, { + :"id" => 'properties_quantity_allocations', + :"data" => { + :"label" => 'Quantity allocations', + :"attribute" => ['properties', 'quantity_allocations'], + :"type" => 'composite', + :"target_type" => 'license', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"visibility_dependency_field_id" => 'properties_total_quantity', + :"data_dependency_field_id" => 'properties_total_quantity', + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 36 + }, { + :"id" => 'properties_operating_system', + :"data" => { + :"label" => 'Operating System', + :"attribute" => ['properties', 'operating_system'], + :"type" => 'checkbox', + :"target_type" => 'license', + :"values" => [ + { :"label" => 'Windows', :"value" => 'windows' }, { + :"label" => 'Mac OS X', :"value" => 'mac_os_x' + }, { :"label" => 'Linux', :"value" => 'linux' }, { :"label" => 'iOS', :"value" => 'ios' } + ], + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 37 + }, { + :"id" => 'properties_installation', + :"data" => { + :"label" => 'Installation', + :"attribute" => ['properties', 'installation'], + :"type" => 'checkbox', + :"target_type" => 'license', + :"values" => [ + { :"label" => 'Citrix', :"value" => 'citrix' }, { + :"label" => 'Local', :"value" => 'local' + }, { :"label" => 'Web', :"value" => 'web' } + ], + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 38 + }, { + :"id" => 'properties_license_expiration', + :"data" => { + :"label" => 'License expiration', + :"attribute" => ['properties', 'license_expiration'], + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"type" => 'date', + :"target_type" => 'license', + :"group" => 'General Information' + }, + :"active" => true, + :"position" => 39 + }, { + :"id" => 'properties_maintenance_contract', + :"data" => { + :"label" => 'Maintenance contract', + :"attribute" => ['properties', 'maintenance_contract'], + :"type" => 'select', + :"target_type" => 'license', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"values" => [ + { :"label" => 'No', :"value" => 'false' }, { :"label" => 'Yes', :"value" => 'true' } + ], + :"default" => 'false', + :"group" => 'Maintenance' + }, + :"active" => true, + :"position" => 40 + }, { + :"id" => 'properties_maintenance_expiration', + :"data" => { + :"label" => 'Maintenance expiration', + :"attribute" => ['properties', 'maintenance_expiration'], + :"type" => 'date', + :"target_type" => 'license', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"visibility_dependency_field_id" => 'properties_maintenance_contract', + :"visibility_dependency_value" => 'true', + :"group" => 'Maintenance' + }, + :"active" => true, + :"position" => 41 + }, { + :"id" => 'properties_maintenance_currency', + :"data" => { + :"label" => 'Currency', + :"attribute" => ['properties', 'maintenance_currency'], + :"type" => 'select', + :"values" => 'all_currencies', + :"default" => 'CHF', + :"target_type" => 'license', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"visibility_dependency_field_id" => 'properties_maintenance_expiration', + :"group" => 'Maintenance' + }, + :"active" => true, + :"position" => 42 + }, { + :"id" => 'properties_maintenance_price', + :"data" => { + :"label" => 'Price', + :"attribute" => ['properties', 'maintenance_price'], + :"type" => 'text', + :"currency" => true, + :"target_type" => 'license', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"visibility_dependency_field_id" => 'properties_maintenance_currency', + :"group" => 'Maintenance' + }, + :"active" => true, + :"position" => 43 + }, { + :"id" => 'properties_procured_by', + :"data" => { + :"label" => 'Procured by', + :"attribute" => ['properties', 'procured_by'], + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"type" => 'text', + :"target_type" => 'license', + :"group" => 'Invoice Information' + }, + :"active" => true, + :"position" => 44 + }, { + :"id" => 'attachments', + :"data" => { + :"label" => 'Attachments', + :"attribute" => 'attachments', + :"type" => 'attachment', + :"group" => 'General Information', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true } + }, + :"active" => true, + :"position" => 45 + }, { + :"id" => 'properties_umzug', + :"data" => { + :"label" => 'Umzug', + :"attribute" => ['properties', 'umzug'], + :"type" => 'select', + :"target_type" => 'item', + :"values" => [ + { :"label" => 'zügeln', :"value" => 'zügeln' }, { + :"label" => 'sofort entsorgen', :"value" => 'sofort entsorgen' + }, { :"label" => 'bei Umzug entsorgen', :"value" => 'bei Umzug entsorgen' }, { + :"label" => 'bei Umzug verkaufen', :"value" => 'bei Umzug verkaufen' + } + ], + :"default" => 'zügeln', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'Umzug' + }, + :"active" => true, + :"position" => 46 + }, { + :"id" => 'properties_zielraum', + :"data" => { + :"label" => 'Zielraum', + :"attribute" => ['properties', 'zielraum'], + :"type" => 'text', + :"target_type" => 'item', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'Umzug' + }, + :"active" => true, + :"position" => 47 + }, { + :"id" => 'properties_ankunftsdatum', + :"data" => { + :"label" => 'Ankunftsdatum', + :"attribute" => ['properties', 'ankunftsdatum'], + :"type" => 'date', + :"target_type" => 'item', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'Toni Ankunftskontrolle' + }, + :"active" => true, + :"position" => 48 + }, { + :"id" => 'properties_ankunftszustand', + :"data" => { + :"label" => 'Ankunftszustand', + :"attribute" => ['properties', 'ankunftszustand'], + :"type" => 'select', + :"target_type" => 'item', + :"values" => [ + { :"label" => 'intakt', :"value" => 'intakt' }, { + :"label" => 'transportschaden', :"value" => 'transportschaden' + } + ], + :"default" => 'intakt', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'Toni Ankunftskontrolle' + }, + :"active" => true, + :"position" => 49 + }, { + :"id" => 'properties_ankunftsnotiz', + :"data" => { + :"label" => 'Ankunftsnotiz', + :"attribute" => ['properties', 'ankunftsnotiz'], + :"type" => 'textarea', + :"target_type" => 'item', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'Toni Ankunftskontrolle' + }, + :"active" => true, + :"position" => 50 + }, { + :"id" => 'properties_anschaffungskategorie', + :"data" => { + :"label" => 'Beschaffungsgruppe', + :"attribute" => ['properties', 'anschaffungskategorie'], + :"value_label" => ['properties', 'anschaffungskategorie'], + :"required" => true, + :"type" => 'select', + :"target_type" => 'item', + :"values" => [ + { :"label" => '', :"value" => nil }, { + :"label" => 'Werkstatt-Technik', :"value" => 'Werkstatt-Technik' + }, { :"label" => 'Produktionstechnik', :"value" => 'Produktionstechnik' }, { + :"label" => 'AV-Technik', :"value" => 'AV-Technik' + }, { :"label" => 'Musikinstrumente', :"value" => 'Musikinstrumente' }, { + :"label" => 'Facility Management', :"value" => 'Facility Management' + }, { :"label" => 'IC-Technik/Software', :"value" => 'IC-Technik/Software' }, { + :"label" => 'Durch Kunde beschafft', :"value" => 'Durch Kunde beschafft' + } + ], + :"default" => nil, + :"visibility_dependency_field_id" => 'is_inventory_relevant', + :"visibility_dependency_value" => 'true', + :"permissions" => { :"role" => 'inventory_manager', :"owner" => true }, + :"group" => 'Inventory' + }, + :"active" => true, + :"position" => 51 + } ] end diff --git a/features/step_definitions/manage/inventory_helper_steps.rb b/features/step_definitions/manage/inventory_helper_steps.rb index a5577b298e..999739cb8d 100644 --- a/features/step_definitions/manage/inventory_helper_steps.rb +++ b/features/step_definitions/manage/inventory_helper_steps.rb @@ -8,7 +8,7 @@ Then /^I choose all fields through a list or by name$/ do i = find('#inventory-helper-view').find('#search-mask').find('#field-input') # i = find('#inventory-helper-view #field-input') - while(i.click and page.has_selector?('.ui-menu-item a', visible: true)) do + while (i.click and page.has_selector?('.ui-menu-item a', visible: true)) find('.ui-menu-item a', match: :first, visible: true).click end end @@ -20,63 +20,65 @@ next if @parent_el.all(".field[data-id='#{field.id}']").empty? field_el = @parent_el.find(".field[data-id='#{field.id}']") case field.data['type'] - when 'radio' - r = field_el.find('input[type=radio]', match: :first) - r.click - @data[field.id] = r.value - when 'textarea' - ta = field_el.find('textarea') - ta.set 'This is a text for a textarea' - @data[field.id] = ta.value - when 'select' - o = field_el.find('option', match: :first) - o.select_option - @data[field.id] = o.value - when 'text' - within field_el do - string = if all("input[name='item[inventory_code]']").empty? - 'This is a text for a input text' - else - '123456' - end - i = find("input[type='text']") - i.set string - @data[field.id] = i.value - end - when 'date' - dp = find(".field[data-id='#{field.id}'][data-type='date']").find('input') - ori_value = dp.value - dp.set '' - dp.set ori_value - within '.ui-datepicker-calendar' do - find('td a', text: Date.today.day.to_s).click - end - @data[field.id] = dp.value - when 'autocomplete' - find(".field[data-id='#{field.id}']").find('input').click - find('.ui-menu-item a', match: :first).click - @data[field.id] = find(".field[data-id='#{field.id}'][data-type='autocomplete']") - when 'autocomplete-search' - model = if @item and @item.children.exists? # item is a package - Model.all.find &:is_package? - else - Model.all.find {|m| not m.is_package?} - end - string = model.name - within ".field[data-id='#{field.id}']" do - find('input').click - find('input').set string + when 'radio' + r = field_el.find('input[type=radio]', match: :first) + r.click + @data[field.id] = r.value + when 'textarea' + ta = field_el.find('textarea') + ta.set 'This is a text for a textarea' + @data[field.id] = ta.value + when 'select' + o = field_el.find('option', match: :first) + o.select_option + @data[field.id] = o.value + when 'text' + within field_el do + string = + if all("input[name='item[inventory_code]']").empty? + 'This is a text for a input text' + else + '123456' + end + i = find("input[type='text']") + i.set string + @data[field.id] = i.value + end + when 'date' + dp = find(".field[data-id='#{field.id}'][data-type='date']").find('input') + ori_value = dp.value + dp.set '' + dp.set ori_value + within '.ui-datepicker-calendar' do + find('td a', text: Date.today.day.to_s).click + end + @data[field.id] = dp.value + when 'autocomplete' + find(".field[data-id='#{field.id}']").find('input').click + find('.ui-menu-item a', match: :first).click + @data[field.id] = find(".field[data-id='#{field.id}'][data-type='autocomplete']") + when 'autocomplete-search' + model = + if @item and @item.children.exists? # item is a package + Model.all.find &:is_package? + else + Model.all.find { |m| nm.is_package? } end - find('.ui-menu-item a', match: :prefer_exact, text: string).click - @data[field.id] = Model.find_by_name(string).id - when 'checkbox' - # currently we only have "ausgemustert" - field_el.find("input[type='checkbox']").click - find("[name='item[retired_reason]']").set 'This is a text for a input text' - @data[field.id] = 'This is a text for a input text' - else - raise 'field type not found' + string = model.name + within ".field[data-id='#{field.id}']" do + find('input').click + find('input').set string end + find('.ui-menu-item a', match: :prefer_exact, text: string).click + @data[field.id] = Model.find_by_name(string).id + when 'checkbox' + field_el.find("input[type='checkbox']").click + find("[name='item[retired_reason]']").set 'This is a text for a input text' + @data[field.id] = 'This is a text for a input text' + else + raise 'field type not found' + end + # currently we only have "ausgemustert" # if present, remove flash which gets displaced on cider and covers other elements first('#flash .fa-times-circle').try(:click) @@ -84,17 +86,18 @@ end Then /^I set the field "(.*?)" to "(.*?)"$/ do |field_name, value| - field = Field.find(find(".field.row.emboss", match: :prefer_exact, text: field_name)['data-id'].to_sym) + field = + Field.find(find('.field.row.emboss', match: :prefer_exact, text: field_name)['data-id'].to_sym) within(".field[data-id='#{field.id}']") do case field.data['type'] - when 'radio' - find('label', text: value).click - when 'select' - find('option', text: value).select_option - when 'checkbox' - find('label', text: value).click - else - raise 'unknown field' + when 'radio' + find('label', text: value).click + when 'select' + find('option', text: value).select_option + when 'checkbox' + find('label', text: value).click + else + raise 'unknown field' end end end @@ -107,20 +110,26 @@ end end - -Then /^I scan or enter the inventory code( of an item belonging to the current inventory pool)?$/ do |arg1| - @item ||= if arg1 - @current_inventory_pool.items.where(owner_id: @current_inventory_pool) - else - @current_inventory_pool.items - end.in_stock.first +Then / + ^I scan or enter the inventory code( of an item belonging to the current inventory pool)?$ + / do |arg1| + @item ||= + if arg1 + @current_inventory_pool.items.where(owner_id: @current_inventory_pool) + else + @current_inventory_pool.items + end + .in_stock + .first within('#item-selection') do find('[data-barcode-scanner-target]').set @item.inventory_code find('button[type=submit]', visible: false).click end end -Then /^I see all the values of the item in an overview with model name and the modified values are already saved$/ do +Then / + ^I see all the values of the item in an overview with model name and the modified values are already saved$ + / do FastGettext.locale = @current_user.language.locale_name.gsub(/-/, '_') Field.all.each do |field| next if all(".field[data-id='#{field.id}']").empty? @@ -136,17 +145,15 @@ field_el.has_content? value.day end elsif field.data['attribute'] == 'retired' - unless value.blank? - field_el.has_content? _(field.values.first['label']) - end + field_el.has_content? _(field.values.first['label']) unless value.blank? elsif field_type == 'radio' if value - value = field.values.detect{|v| v['value'] == value}['label'] + value = field.values.detect { |v| v['value'] == value }['label'] field_el.has_content? _(value) end elsif field_type == 'select' if value - value = field.values.detect{|v| v['value'] == value}['label'] + value = field.values.detect { |v| v['value'] == value }['label'] field_el.has_content? _(value) end elsif field_type == 'autocomplete' @@ -168,18 +175,29 @@ end end - find("#flexible-fields .field[data-id='#{Field.all.detect{|f| f.data['label'] == "Model" }.id}']", text: @item.reload.model.name) + find( + "#flexible-fields .field[data-id='#{Field.all.detect { |f| f.data['label'] == 'Model' }.id}']", + text: @item.reload.model.name + ) end Then /^the changed values are highlighted$/ do all('#field-selection .field', minimum: 1).each do |selected_field| - c = all("#item-section .field[data-id='#{selected_field['data-id']}'].success").count + all("#item-section .field[data-id='#{selected_field['data-id']}'].error").count + c = + all("#item-section .field[data-id='#{selected_field['data-id']}'].success").count + + all("#item-section .field[data-id='#{selected_field['data-id']}'].error").count expect(c).to eq 1 end end Then /^I choose the fields from a list or by name$/ do - field = Field.all.select{|f| f.data['readonly'] == nil and f.data['type'] != 'autocomplete-search' and f.data['target_type'] != 'license' and not f.data['visibility_dependency_field_id']}.last + field = + Field.all.select do |f| + f.data['readonly'] == nil and f.data['type'] != 'autocomplete-search' and + f.data['target_type'] != 'license' and + nf.data['visibility_dependency_field_id'] + end + .last within '#search-mask' do find('#field-input').click find('#field-input').set _(field.data['label']) @@ -194,9 +212,7 @@ within '#field-selection' do fields = all('.field input, #field-selection .field textarea', visible: true) expect(fields.count).to be > 0 - fields.each do |input| - input.set 'Test123' - end + fields.each { |input| input.set 'Test123' } end end @@ -209,11 +225,10 @@ end Then /^I start entering an item's inventory code$/ do - @item= @current_inventory_pool.items.first + @item = @current_inventory_pool.items.first find('#item-search-input').set @item.inventory_code[0..1] end - Then /^I choose the item from the list of results$/ do expect(has_selector?('.ui-menu-item')).to be true find('.ui-menu-item a', text: @item.inventory_code).click @@ -239,7 +254,7 @@ end Then /^my changes are saved$/ do - step %Q{I see all the values of the item in an overview with model name and the modified values are already saved} + step 'I see all the values of the item in an overview with model name and the modified values are already saved' end When /^I cancel$/ do @@ -266,8 +281,12 @@ end Given(/^there is an item that shares its location with another$/) do - location = Location.find {|l| l.items.where(inventory_pool_id: @current_inventory_pool, parent_id: nil).count >= 2} - @item, @item_2 = location.items.where(inventory_pool_id: @current_inventory_pool, parent_id: nil).limit(2) + location = + Location.find do |l| + l.items.where(inventory_pool_id: @current_inventory_pool, parent_id: nil).count >= 2 + end + @item, @item_2 = + location.items.where(inventory_pool_id: @current_inventory_pool, parent_id: nil).limit(2) @item_2_location = @item_2.location end @@ -279,7 +298,9 @@ expect(@item_2.reload.location).to eq @item_2_location end -When(/^"(.*?)" is selected and set to "(.*?)", then "(.*?)" must also be filled in$/) do |field, value, dependent_field| +When( + /^"(.*?)" is selected and set to "(.*?)", then "(.*?)" must also be filled in$/ +) do |field, value, dependent_field| within '#search-mask' do find('#field-input').click find('#field-input').set field @@ -290,54 +311,86 @@ end When(/^a required field is blank, the inventory helper cannot be used$/) do - step %Q{I scan or enter the inventory code} + step 'I scan or enter the inventory code' end Given(/^I edit the field "(.*?)" of an item that is not in stock$/) do |name| - step %Q{I select the field "#{name}"} + step "I select the field \"#{name}\"" @item = @current_inventory_pool.items.not_in_stock.first @item_before = @item.to_json - step %Q{I scan or enter the inventory code} -end - -Then(/^I see an error message that I can't change the responsible inventory pool for items that are not in stock$/) do - expect(page.has_content?( - _("The responsible inventory pool cannot be changed because it's not returned yet or has already been assigned to a contract line.")) + step 'I scan or enter the inventory code' +end + +Then( + / + ^I see an error message that I can't change the responsible inventory pool for items that are not in stock$ + / +) do + expect( + page.has_content?( + _( + "The responsible inventory pool cannot be changed because it's not returned yet or has already been assigned to a contract line." + ) + ) ).to be true expect(@item_before).to eq @item.reload.to_json end -Then(/^I see an error message that I can't retire the item because it's already handed over or assigned to a contract$/) do - expect(has_content?(_("The item cannot be retired because it's not returned yet or has already been assigned to a contract line."))).to be true +Then( + / + ^I see an error message that I can't retire the item because it's already handed over or assigned to a contract$ + / +) do + expect( + has_content?( + _( + "The item cannot be retired because it's not returned yet or has already been assigned to a contract line." + ) + ) + ).to be true expect(@item_before).to eq @item.reload.to_json end -Then(/^I see an error message that I can't change the model because the item is already handed over or assigned to a contract$/) do - expect(has_content?(_('The model cannot be changed because the item is used in contracts already.'))).to be true +Then( + / + ^I see an error message that I can't change the model because the item is already handed over or assigned to a contract$ + / +) do + expect( + has_content?(_('The model cannot be changed because the item is used in contracts already.')) + ).to be true expect(@item_before).to eq @item.reload.to_json end Given(/^I edit the field "(.*?)" of an item that is part of a contract$/) do |name| - step %Q{I select the field "#{name}"} + step "I select the field \"#{name}\"" @item = @current_inventory_pool.items.not_in_stock.first @item_before = @item.to_json - fill_in_autocomplete_field name, @current_inventory_pool.models.detect {|m| m != @item.model}.name - step %Q{I scan or enter the inventory code} + fill_in_autocomplete_field name, + @current_inventory_pool.models.detect { |m| m != @item.model }.name + step 'I scan or enter the inventory code' end Given(/^I retire an item that is not in stock$/) do - step %Q{I select the field "Retiremen"} + step 'I select the field "Retiremen"' find('.row.emboss', match: :prefer_exact, text: _('Retirement')).find('select').select _('Yes') - find('.row.emboss', match: :prefer_exact, text: _('Reason for Retirement')).find('input, textarea').set 'Retirement reason' + find('.row.emboss', match: :prefer_exact, text: _('Reason for Retirement')).find( + 'input, textarea' + ).set 'Retirement reason' @item = @current_inventory_pool.items.where(owner: @current_inventory_pool).not_in_stock.first @item_before = @item.to_json - step %Q{I scan or enter the inventory code} + step 'I scan or enter the inventory code' end -Given(/^I edit the field "Responsible department" of an item that isn't in stock and belongs to the current inventory pool$/) do - step %Q{I select the field "Responsible department"} +Given( + / + ^I edit the field "Responsible department" of an item that isn't in stock and belongs to the current inventory pool$ + / +) do + step 'I select the field "Responsible department"' @item = @current_inventory_pool.items.where(owner: @current_inventory_pool).not_in_stock.first @item_before = @item.to_json - fill_in_autocomplete_field 'Responsible department', InventoryPool.where.not(id: @current_inventory_pool).first.name - step %Q{I scan or enter the inventory code} + fill_in_autocomplete_field 'Responsible department', + InventoryPool.where.not(id: @current_inventory_pool).first.name + step 'I scan or enter the inventory code' end diff --git a/features/step_definitions/manage/inventory_steps.rb b/features/step_definitions/manage/inventory_steps.rb index fd97937bc6..3252515839 100644 --- a/features/step_definitions/manage/inventory_steps.rb +++ b/features/step_definitions/manage/inventory_steps.rb @@ -4,18 +4,14 @@ def check_existing_inventory_codes(items) inventory = find '#inventory' # clicking on all togglers via javascript is significantly faster than doing it with capybara in this case # page.execute_script %Q( $(".button[data-type='inventory-expander']").click() ) - all(".button[data-type='inventory-expander']").each { |b| b.click } + all(".button[data-type='inventory-expander']").each(&:click) inventory_text = find('#inventory').text - items.each do |i| - expect(inventory_text).to match /#{i.inventory_code}/ - end + items.each { |i| expect(inventory_text).to match /#{i.inventory_code}/ } end def check_amount_of_lines(amount) within '#inventory' do - while(all('.loading-bg').length > 0) do - page.execute_script 'window.scrollBy(0,10000)' - end + page.execute_script 'window.scrollBy(0,10000)' while (all('.loading-bg').length > 0) expect(all('.line').count).to eq amount end end @@ -31,42 +27,51 @@ def check_amount_of_lines(amount) table.hashes.each do |row| tab = nil case row['Choice'] - when 'All' - tab = section_tabs.find('a', match: :first) - expect(tab.text).to eq _('All') - inventory = items + options - amount = Model.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + Model.unused_for_inventory_pool(@current_inventory_pool).count + options.count - retired_unretired_option.select_option - used_unused_option.select_option - when 'Models' - tab = section_tabs.find("a[data-type='item']", match: :first) - expect(tab.text).to eq _('Models') - inventory = items.items.joins(:model).where(models: {is_package: false}) - models = Model.where(type: :Model, is_package: false) - amount = models.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + models.unused_for_inventory_pool(@current_inventory_pool).count - retired_unretired_option.select_option - used_unused_option.select_option - when 'Packages' - tab = section_tabs.find("a[data-type='item']", text: _('Packages')) - expect(tab.text).to eq _('Packages') - inventory = items.items.joins(:model).where(models: {is_package: true}) - models = Model.where(type: :Model, is_package: true) - amount = models.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + models.unused_for_inventory_pool(@current_inventory_pool).count - retired_unretired_option.select_option - used_unused_option.select_option - when 'Options' - tab = section_tabs.find("a[data-type='option']", match: :first) - expect(tab.text).to eq _('Options') - inventory = options - amount = inventory.count - when 'Software' - tab = section_tabs.find("a[data-type='license']") - expect(tab.text).to eq _('Software') - inventory = items.licenses - models = Model.where(type: :Software) - amount = models.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + models.unused_for_inventory_pool(@current_inventory_pool).count - retired_unretired_option.select_option - used_unused_option.select_option + when 'All' + tab = section_tabs.find('a', match: :first) + expect(tab.text).to eq _('All') + inventory = items + options + amount = + Model.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + + Model.unused_for_inventory_pool(@current_inventory_pool).count + + options.count + retired_unretired_option.select_option + used_unused_option.select_option + when 'Models' + tab = section_tabs.find("a[data-type='item']", match: :first) + expect(tab.text).to eq _('Models') + inventory = items.items.joins(:model).where(models: { is_package: false }) + models = Model.where(type: :Model, is_package: false) + amount = + models.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + + models.unused_for_inventory_pool(@current_inventory_pool).count + retired_unretired_option.select_option + used_unused_option.select_option + when 'Packages' + tab = section_tabs.find("a[data-type='item']", text: _('Packages')) + expect(tab.text).to eq _('Packages') + inventory = items.items.joins(:model).where(models: { is_package: true }) + models = Model.where(type: :Model, is_package: true) + amount = + models.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + + models.unused_for_inventory_pool(@current_inventory_pool).count + retired_unretired_option.select_option + used_unused_option.select_option + when 'Options' + tab = section_tabs.find("a[data-type='option']", match: :first) + expect(tab.text).to eq _('Options') + inventory = options + amount = inventory.count + when 'Software' + tab = section_tabs.find("a[data-type='license']") + expect(tab.text).to eq _('Software') + inventory = items.licenses + models = Model.where(type: :Software) + amount = + models.owned_or_responsible_by_inventory_pool(@current_inventory_pool).count + + models.unused_for_inventory_pool(@current_inventory_pool).count + retired_unretired_option.select_option + used_unused_option.select_option end tab.click @@ -83,21 +88,23 @@ def check_amount_of_lines(amount) Then(/^the tab "(.*?)" is active$/) do |arg1| case arg1 - when 'Active Inventory' - find('#list-tabs a.active', text: _('Active Inventory')) - when 'All' - find('#list-tabs a.active', text: _('All')) + when 'Active Inventory' + find('#list-tabs a.active', text: _('Active Inventory')) + when 'All' + find('#list-tabs a.active', text: _('All')) end end ######################################################################## -When(/^I see a model line for a model that is neither a package model nor part of a package model$/) do +When( + /^I see a model line for a model that is neither a package model nor part of a package model$/ +) do expect(has_selector?("#inventory > .line[data-type='model']")).to be true within '#inventory' do all(".line[data-type='model']").each do |model_line| @model = Model.find_by_name(model_line.find('.col2of5 strong').text) - next if @model.is_package? or @model.items.all? { |i| i.parent } + next if @model.is_package? or @model.items.all?(&:parent) @model_line = model_line and break end end @@ -111,14 +118,21 @@ def check_amount_of_lines(amount) Then /^the model line contains:$/ do |table| table.hashes.each do |row| case row['information'] - when 'Image' - @model_line.find "img[src*='image_thumb']" - when 'Model name' - @model_line.find '.col2of5 strong' - when 'Number available (now)' - @model_line.find '.col1of5:nth-child(3)', text: /#{@model.borrowable_items.in_stock.where(inventory_pool_id: @current_inventory_pool).count}.*?\// - when 'Number available (total)' - @model_line.find '.col1of5:nth-child(3)', text: /\/.*?#{@model.borrowable_items.where(inventory_pool_id: @current_inventory_pool).count}/ + when 'Image' + @model_line.find "img[src*='image_thumb']" + when 'Model name' + @model_line.find '.col2of5 strong' + when 'Number available (now)' + @model_line.find '.col1of5:nth-child(3)', + text: + %r{ + #{@model.borrowable_items.in_stock.where(inventory_pool_id: @current_inventory_pool) + .count}.*?\/ + } + when 'Number available (total)' + @model_line.find '.col1of5:nth-child(3)', + text: + %r{\/.*?#{@model.borrowable_items.where(inventory_pool_id: @current_inventory_pool).count}} end end end @@ -128,71 +142,76 @@ def check_amount_of_lines(amount) Then /^the (?:item|software license) line contains:$/ do |table| table.hashes.each do |row| case row['information'] - when 'Inventory code' - step 'the item line contains the inventory code' - when 'Location' - step 'the item line contains the location' - when 'Code of the building' - step 'the item line contains the code of the building' - when 'Room' - step 'the item line contains the room' - when 'Shelf' - step 'the item line contains the shelf' - when 'Current borrower' - step 'the item line contains the name of the current borrower' - when 'End date of contract' - step 'the item line contains the end date of the current contract' - when 'Responsible department' - step 'the item line contains the responsible department' - when 'Operating system' - step %Q(the license line contains the 'operating system' information) - when 'License type' - step %Q(the license line contains the 'license type' information) - when 'Quantity' - step %Q(the license line contains the 'quantity' information) - else - raise 'step not found' + when 'Inventory code' + step 'the item line contains the inventory code' + when 'Location' + step 'the item line contains the location' + when 'Code of the building' + step 'the item line contains the code of the building' + when 'Room' + step 'the item line contains the room' + when 'Shelf' + step 'the item line contains the shelf' + when 'Current borrower' + step 'the item line contains the name of the current borrower' + when 'End date of contract' + step 'the item line contains the end date of the current contract' + when 'Responsible department' + step 'the item line contains the responsible department' + when 'Operating system' + step "the license line contains the 'operating system' information" + when 'License type' + step "the license line contains the 'license type' information" + when 'Quantity' + step "the license line contains the 'quantity' information" + else + raise 'step not found' end end end Then /^the item line contains the (.*)$/ do |arg1| - s = case arg1 - when 'inventory code' - @item.inventory_code - when 'location of the item' - @item.location.to_s - when 'code of the building' - @item.room.building.code - when 'room' - @item.room.name - when 'shelf' - @item.shelf - when 'name of the current borrower' - @item.current_borrower.to_s - when 'end date of the current contract' - @item.current_return_date.year - @item.current_return_date.month - @item.current_return_date.day - when 'responsible department' - @item.inventory_pool.to_s - else - raise - end - expect((@item_line.is_a?(String) ? find(@item_line, match: :first) : @item_line).has_content?(s)).to be true + s = + case arg1 + when 'inventory code' + @item.inventory_code + when 'location of the item' + @item.location.to_s + when 'code of the building' + @item.room.building.code + when 'room' + @item.room.name + when 'shelf' + @item.shelf + when 'name of the current borrower' + @item.current_borrower.to_s + when 'end date of the current contract' + @item.current_return_date.year + @item.current_return_date.month + @item.current_return_date.day + when 'responsible department' + @item.inventory_pool.to_s + else + raise + end + expect( + (@item_line.is_a?(String) ? find(@item_line, match: :first) : @item_line).has_content?(s) + ).to be true end def fetch_item_line_and_item r1 = ".group-of-lines .line[data-type='item']" - r2 = within(r1, match: :first) do - inventory_code = find('.col2of5.text-align-left:nth-child(2) .row:nth-child(1)').text - Item.find_by_inventory_code(inventory_code) - end + r2 = + within(r1, match: :first) do + inventory_code = find('.col2of5.text-align-left:nth-child(2) .row:nth-child(1)').text + Item.find_by_inventory_code(inventory_code) + end [r1, r2] end When /^the item is in stock and my department is responsible for it$/ do - find("select[name='responsible_inventory_pool_id'] option[value='#{@current_inventory_pool.id}']").select_option + find("select[name='responsible_inventory_pool_id'] option[value='#{@current_inventory_pool.id}']") + .select_option find("input[name='in_stock']").click unless find("input[name='in_stock']").checked? find(".button[data-type='inventory-expander'] i.arrow.right", match: :first).click @item_line, @item = fetch_item_line_and_item @@ -200,18 +219,38 @@ def fetch_item_line_and_item When /^the item is not in stock and another department is responsible for it$/ do find("input[name='in_stock']").click if find("input[name='in_stock']").checked? - @item = @current_inventory_pool.own_items.items.detect{|i| not i.inventory_pool_id.nil? and i.inventory_pool != @current_inventory_pool and not i.in_stock?} - all("select[name='responsible_inventory_pool_id'] option").detect { |o| o.value == @item.inventory_pool.id }.select_option + @item = + @current_inventory_pool.own_items.items.detect do |i| + ni.inventory_pool_id.nil? and i.inventory_pool != @current_inventory_pool and ni.in_stock? + end + all("select[name='responsible_inventory_pool_id'] option").detect do |o| + o.value == @item.inventory_pool.id + end + .select_option step 'I search for "%s"' % @item.inventory_code step 'expand the corresponding model' @item_line, @item = fetch_item_line_and_item end -When /^my department is the owner but has given responsibility for the item to another department$/ do - all("select[name='responsible_inventory_pool_id'] option:not([selected])").detect{|o| o.value != @current_inventory_pool.id.to_s and o.value != ''}.select_option - find(".line[data-type='model'] .button[data-type='inventory-expander'] i.arrow.right", match: :first).click +When / + ^my department is the owner but has given responsibility for the item to another department$ + / do + all("select[name='responsible_inventory_pool_id'] option:not([selected])").detect do |o| + o.value != @current_inventory_pool.id.to_s and o.value != '' + end + .select_option + find( + ".line[data-type='model'] .button[data-type='inventory-expander'] i.arrow.right", match: :first + ) + .click @item_line = ".group-of-lines .line[data-type='item']" - @item = Item.find_by_inventory_code(find(@item_line, match: :first).find('.col2of5.text-align-left:nth-child(2) .row:nth-child(1)').text) + @item = + Item.find_by_inventory_code( + find(@item_line, match: :first).find( + '.col2of5.text-align-left:nth-child(2) .row:nth-child(1)' + ) + .text + ) end Then(/^the option line contains:$/) do |table| @@ -219,14 +258,15 @@ def fetch_item_line_and_item @option = Option.find_by_inventory_code @option_line.find('.col1of5:nth-child(1)').text table.hashes.each do |row| case row['information'] - when 'Barcode' - expect(@option_line.has_content? @option.inventory_code).to be true - when 'Name' - expect(@option_line.has_content? @option.name).to be true - when 'Price' - expect((@option.price * 100).to_i.to_s).to eq @option_line.find('.col1of5:nth-child(3)').text.gsub(/\D/, '') - else - raise "Can't find information called '#{row['information']}'" + when 'Barcode' + expect(@option_line.has_content? @option.inventory_code).to be true + when 'Name' + expect(@option_line.has_content? @option.name).to be true + when 'Price' + expect((@option.price * 100).to_i.to_s).to eq @option_line.find('.col1of5:nth-child(3)').text + .gsub(/\D/, '') + else + raise "Can't find information called '#{row['information']}'" end end end @@ -244,14 +284,15 @@ def fetch_item_line_and_item @items_element = @model_line.find(:xpath, "following-sibling::div[@class='group-of-lines']") items = @model.items.by_owner_or_responsible(@current_inventory_pool) expect(items).to exist - items.each do |item| - @items_element.find('.line', text: item.inventory_code) - end + items.each { |item| @items_element.find('.line', text: item.inventory_code) } end Then(/^such a line looks like an item line$/) do @item_line ||= @items_element.find('.line', match: :first) - @item ||= Item.find_by_inventory_code(@item_line.find('.col2of5.text-align-left:nth-child(2) .row:nth-child(1)').text) + @item ||= + Item.find_by_inventory_code( + @item_line.find('.col2of5.text-align-left:nth-child(2) .row:nth-child(1)').text + ) # this check is to cover the case where there is item assigned but the user has not signed yet if @item.in_stock? and @item.current_borrower and @item.inventory_pool == @current_inventory_pool @@ -261,7 +302,7 @@ def fetch_item_line_and_item step 'the item line contains the code of the building' step 'the item line contains the room' step 'the item line contains the shelf' - elsif not @item.in_stock? and @item.inventory_pool == @current_inventory_pool + elsif n@item.in_stock? and @item.inventory_pool == @current_inventory_pool step 'the item line contains the name of the current borrower' step 'the item line contains the end date of the current contract' elsif @item.owner == @current_inventory_pool and @item.inventory_pool != @current_inventory_pool @@ -273,7 +314,6 @@ def fetch_item_line_and_item step 'the item line contains the room' step 'the item line contains the shelf' end - end Then(/^I can expand each package model line$/) do @@ -292,7 +332,10 @@ def fetch_item_line_and_item expect(@packages_element.has_content? package.inventory_code).to be true end @item_line = @packages_element.all(".line[data-type='item']").to_a.sample - @item = Item.find_by_inventory_code(@item_line.find('.col2of5.text-align-left:nth-child(2) .row:nth-child(1)').text) + @item = + Item.find_by_inventory_code( + @item_line.find('.col2of5.text-align-left:nth-child(2) .row:nth-child(1)').text + ) end Then(/^I can expand this package line$/) do @@ -300,7 +343,8 @@ def fetch_item_line_and_item find(".button[data-type='inventory-expander'] i.arrow.right").click find(".button[data-type='inventory-expander'] i.arrow.down") end - @package_parts_element = @item_line.find(:xpath, "following-sibling::div[@class='group-of-lines']") + @package_parts_element = + @item_line.find(:xpath, "following-sibling::div[@class='group-of-lines']") end Then(/^I see the components of this package$/) do @@ -320,16 +364,16 @@ def parsed_query(export_format) find('.dropdown-toggle', text: _('Export'), match: :prefer_exact).hover href = find("##{export_format}-export")[:href] uri = URI.parse href - expect(uri.path).to eq send("manage_inventory_#{export_format}_export_path", @current_inventory_pool) + expect(uri.path).to eq send( + "manage_inventory_#{export_format}_export_path", @current_inventory_pool + ) Rack::Utils.parse_nested_query uri.query end Then /^I can export this items data as a (CSV|Excel) file$/ do |export_format| ef = export_format.downcase expect(parsed_query(ef)['retired']).to eq 'false' - if [nil, '0'].include? parsed_query(ef)['in_stock'] - find('input#in_stock').click - end + find('input#in_stock').click if [nil, '0'].include? parsed_query(ef)['in_stock'] expect(parsed_query(ef)['in_stock']).to eq '1' @params = ActionController::Parameters.new(parsed_query(ef)) end @@ -341,47 +385,56 @@ def parsed_query(export_format) Then /^the file contains the same lines as are shown right now, including any filtering$/ do # not really downloading the file, but invoking directly the model class method require 'csv' - @csv = CSV.parse InventoryPool.csv_export(@current_inventory_pool, @params), - {col_sep: ';', quote_char: "\"", force_quotes: true, headers: :first_row} + @csv = + CSV.parse InventoryPool.csv_export(@current_inventory_pool, @params), { + col_sep: ';', quote_char: '"', force_quotes: true, headers: :first_row + } step 'I fetch all pages of the list' within '#inventory' do ['model', 'software', 'option'].each do |type| selector = ".line[data-type='#{type}'] .button[data-type='inventory-expander'] i.arrow.right" - while has_selector?(selector) do - all(selector).each &:click - end + all(selector).each &:click while has_selector?(selector) end - item_line_codes = (all(".line[data-type='item']").to_a + all(".line[data-type='license']").to_a).map { |l| l.find('.col2of5 .row', match: :first).text } - option_line_codes = all(".line[data-type='option']").to_a.map { |l| l.find('.row .col1of5', match: :first).text } + item_line_codes = + (all(".line[data-type='item']").to_a + all(".line[data-type='license']").to_a).map do |l| + l.find('.col2of5 .row', match: :first).text + end + option_line_codes = + all(".line[data-type='option']").to_a.map { |l| l.find('.row .col1of5', match: :first).text } line_codes = item_line_codes + option_line_codes - csv_codes = @csv.map {|csv_row| csv_row['Inventory Code'] } + csv_codes = @csv.map { |csv_row| csv_row['Inventory Code'] } expect(csv_codes.sort).to eq line_codes.sort end end Then(/^the lines contain the following fields in order:$/) do |table| csv_headers = @csv.headers - table.hashes.each do |row| - expect(csv_headers).to include row['Fields'] - end + table.hashes.each { |row| expect(csv_headers).to include row['Fields'] } expect(csv_headers).to eq table.raw.flatten[1..-1] end When(/^I add a new (.+)/) do |entity| - @klass = case _(entity) - when 'model' then Model - when 'package' then Model - when 'software' then Software - end + @klass = + case _(entity) + when 'model' + Model + when 'package' + Model + when 'software' + Software + end find('.dropdown-holder', text: _('Add inventory')).click click_link entity end When(/^I add a (model|software) to the inventory/) do |entity| - @klass = case _(entity) - when 'model' then Model - when 'software' then Software - end + @klass = + case _(entity) + when 'model' + Model + when 'software' + Software + end if _(entity) == 'model' visit manage_new_model_path(@current_inventory_pool, type: Model) else @@ -389,20 +442,25 @@ def parsed_query(export_format) end end - When /^I (?:enter|edit)? ?the following details$/ do |table| - # table is a Cucumber::Ast::Table - find('.button.green', text: _('Save')) + find( + # table is a Cucumber::Ast::Table + '.button.green', + text: _('Save') + ) @table_hashes = table.hashes @table_hashes.each do |row| - input = find('.field .row', match: :prefer_exact, text: row['Field']).find(:xpath, './/input | .//textarea') + input = + find('.field .row', match: :prefer_exact, text: row['Field']).find( + :xpath, './/input | .//textarea' + ) input.set '' input.set row['Value'] end end Then /^the information is saved$/ do - search_string = @table_hashes.detect {|h| h['Field'] == 'Product'}['Value'] + search_string = @table_hashes.detect { |h| h['Field'] == 'Product' }['Value'] if has_selector?(:select, 'retired') find(:select, 'retired').first('option').select_option select _('all models'), from: 'used' @@ -422,9 +480,7 @@ def parsed_query(export_format) # check that the same model was modified # This step seems to be used starting from steps that define @model and # steps that don't, so we need to handle both here I guess. - if @model && !@model_id - @model_id = @model.id - end + @model_id = @model.id if @model && !@model_id expect((Rails.application.routes.recognize_path current_path)[:id]).to eq @model_id @table_hashes.each do |row| @@ -462,9 +518,7 @@ def parsed_query(export_format) end When /^I edit an existing (Model|Option|Package|)$/ do |entity| - if entity == 'Package' - if @model @package = @model.items.packages.where(inventory_pool_id: @current_inventory_pool).first find("#packages .line[data-id='#{@package.id}'] [data-edit-package]").click @@ -475,40 +529,42 @@ def parsed_query(export_format) find("[data-type='field']", match: :first) end else - @page_to_return = current_path - object_name = case entity - when 'Model' - @model = @current_inventory_pool.models.where(type: 'Model').first - @model.name - when 'Option' - find(:select, 'retired').first('option').select_option - @option = @current_inventory_pool.options.first - @option.name - end + object_name = + case entity + when 'Model' + @model = @current_inventory_pool.models.where(type: 'Model').first + @model.name + when 'Option' + find(:select, 'retired').first('option').select_option + @option = @current_inventory_pool.options.first + @option.name + end step 'I search for "%s"' % object_name select _('all models'), from: 'used' - find('.line', match: :prefer_exact, text: object_name).find('.button', text: "Edit #{entity}").click + find('.line', match: :prefer_exact, text: object_name).find('.button', text: "Edit #{entity}") + .click end end When /^I edit a model that exists, is in use and already has( activated)? accessories$/ do |arg1| - @model = @current_inventory_pool.models.to_a.detect do |m| - if arg1 - m.accessories.active_in(@current_inventory_pool) - else - m.accessories - end.exists? - end + @model = + @current_inventory_pool.models.to_a.detect do |m| + arg1 ? m.accessories.active_in(@current_inventory_pool) : m.accessories.exists? + end visit manage_edit_model_path(@current_inventory_pool, @model) end When /^I enter the name of an existing model$/ do model = Model.all.first - step %{I edit the following details}, table(%{ + step 'I edit the following details', + table( + " | Field | Value | - | Product | #{model.product} | - | Version | #{model.version} |}) + | Product | #{model + .product} | + | Version | #{model.version} |" + ) end Then /^the model is not saved because it does not have a (?:unique )?name$/ do @@ -517,16 +573,12 @@ def parsed_query(export_format) end Then /^I can enter the following information:$/ do |table| - table.raw.flatten.all? do |field_name| - find('.field', text: field_name) - end + table.raw.flatten.all? { |field_name| find('.field', text: field_name) } end Then /^I see all the accessories for this model$/ do within('.row.emboss', match: :prefer_exact, text: _('Accessories')) do - @model.accessories.each do |accessory| - find('.list-of-lines .line', text: accessory.name) - end + @model.accessories.each { |accessory| find('.list-of-lines .line', text: accessory.name) } end end @@ -559,7 +611,8 @@ def parsed_query(export_format) Then /^I can delete a single accessory if it is not active in any other pool$/ do accessory_to_delete = @model.accessories.detect { |x| x.inventory_pools.count <= 1 } within('.row.emboss', match: :prefer_exact, text: _('Accessories')) do - find('.list-of-lines .line', text: accessory_to_delete.name).find('button', text: _('Remove')).click + find('.list-of-lines .line', text: accessory_to_delete.name).find('button', text: _('Remove')) + .click end step 'I save' find('#inventory-index-view h1', match: :prefer_exact, text: _('List of Inventory')) @@ -573,7 +626,9 @@ def parsed_query(export_format) end step 'I save' find('#inventory-index-view h1', match: :prefer_exact, text: _('List of Inventory')) - expect { @current_inventory_pool.accessories.reload.find(accessory_to_deactivate.id) }.to raise_error(ActiveRecord::RecordNotFound) + expect do + @current_inventory_pool.accessories.reload.find(accessory_to_deactivate.id) + end.to raise_error(ActiveRecord::RecordNotFound) end When /^I add multiple images$/ do @@ -581,20 +636,21 @@ def parsed_query(export_format) end Then /^I can also remove those images$/ do - find('.row.emboss', match: :prefer_exact, text: _('Images')).find("[data-type='inline-entry']", text: 'image1.jpg').find('button[data-remove]', match: :first).click + find('.row.emboss', match: :prefer_exact, text: _('Images')).find( + "[data-type='inline-entry']", text: 'image1.jpg' + ) + .find('button[data-remove]', match: :first) + .click @images_to_save = [] - find('.row.emboss', match: :prefer_exact, text: _('Images')).all("[data-type='inline-entry']").each do |entry| - @images_to_save << entry.text.split(' ')[0] - end + find('.row.emboss', match: :prefer_exact, text: _('Images')).all("[data-type='inline-entry']") + .each { |entry| @images_to_save << entry.text.split(' ')[0] } end Then /^the images are resized to their thumbnail size when I see them in lists$/ do step 'I search for "%s"' % @model.name find(".line[data-id='#{@model.id}']").find('.button', text: 'Edit Model').click within '#images' do - @images_to_save.each do |image_name| - find('a', text: "#{image_name}") - end + @images_to_save.each { |image_name| find('a', text: "#{image_name}") } end end @@ -602,7 +658,6 @@ def parsed_query(export_format) expect(@model.images.map(&:filename).sort).to eq @images_to_save.sort end - When /^I save the model and its images$/ do @model_name_from_url = get_rails_model_name_from_url step 'I press "%s"' % (_('Save %s') % _("#{@model_name_from_url.capitalize}")) @@ -618,15 +673,20 @@ def parsed_query(export_format) Then /^I enter the product name "([^"]*)"$/ do |name| @product_name = name - step 'I enter the following details', table(%{ + step 'I enter the following details', + table(" | Field | Value | | Product | #{name} | - }) + ") end Then /^I can also remove attachments again$/ do attachment_to_remove = @attachment_filenames.delete(@attachment_filenames.sample) - find('.row.emboss', match: :prefer_exact, text: _('Attachments')).find("[data-type='inline-entry']", text: attachment_to_remove).find('button[data-remove]', match: :first).click + find('.row.emboss', match: :prefer_exact, text: _('Attachments')).find( + "[data-type='inline-entry']", text: attachment_to_remove + ) + .find('button[data-remove]', match: :first) + .click end Then /^the attachments are saved$/ do @@ -637,15 +697,15 @@ def parsed_query(export_format) end When(/^I make a search without any results$/) do - begin - search_term = Faker::Lorem.words.join - end while not @current_inventory_pool.inventory({search_term: search_term}).empty? - step %Q(I search for "%s") % search_term + while n@current_inventory_pool.inventory({ search_term: search_term }).empty? + begin + search_term = Faker::Lorem.words.join + end + end + step 'I search for "%s"' % search_term end -Then(/^I see 'No entries found'$/) do - find('#inventory', text: _('No entries found')) -end +Then(/^I see 'No entries found'$/) { find('#inventory', text: _('No entries found')) } Given(/^I open the list of inventory pools$/) do visit admin.inventory_pools_path if current_path != admin.inventory_pools_path @@ -656,9 +716,7 @@ def parsed_query(export_format) find("#list-tabs a[data-type='license']").click end -When(/^I press CSV-Export$/) do - find('#csv-export').click -end +When(/^I press CSV-Export$/) { find('#csv-export').click } When(/^I look at this license in the software list$/) do find("a[data-type='license']").click @@ -670,43 +728,70 @@ def parsed_query(export_format) el.find('i.arrow.down') end end - @item_line = @license_line = ".group-of-lines .line[data-type='license'][data-id='#{@license.id}']" + @item_line = + @license_line = ".group-of-lines .line[data-type='license'][data-id='#{@license.id}']" end Then(/^the license line contains the '(.*)' information$/) do |arg1| line = @license_line.is_a?(String) ? find(@license_line, match: :first) : @license_line case arg1 - when 'operating system' - @license.properties[:operating_system].map(&:titleize).each do |os| - expect(line.has_content? _(os)).to be true - end - when 'license type' - expect(line.has_content? _(@license.properties[:license_type].titleize)).to be true - when 'quantity' - expect(line.has_content? @license.properties[:total_quantity]).to be true - else - raise + when 'operating system' + @license.properties[:operating_system].map(&:titleize).each do |os| + expect(line.has_content? _(os)).to be true + end + when 'license type' + expect(line.has_content? _(@license.properties[:license_type].titleize)).to be true + when 'quantity' + expect(line.has_content? @license.properties[:total_quantity]).to be true + else + raise end end Given(/^there exists a software license$/) do - @item = @license = Item.licenses.where(inventory_pool_id: @current_inventory_pool.id).detect { |l| l.properties[:operating_system] and l.properties[:license_type] } + @item = + @license = + Item.licenses.where(inventory_pool_id: @current_inventory_pool.id).detect do |l| + l.properties[:operating_system] and l.properties[:license_type] + end expect(@license).not_to be_nil end Given(/^there exists a software license of one of the following types$/) do |table| types = table.hashes.map { |h| h['technical'] } - @item = @license = Item.licenses.where(inventory_pool_id: @current_inventory_pool.id).detect { |l| types.include?(l.properties[:license_type]) and l.properties[:operating_system] } + @item = + @license = + Item.licenses.where(inventory_pool_id: @current_inventory_pool.id).detect do |l| + types.include?(l.properties[:license_type]) and l.properties[:operating_system] + end expect(@license).not_to be_nil end -Given(/^there exists a software license, owned by my inventory pool, but given responsibility to another inventory pool$/) do - @item = @license = Item.licenses.where.not(inventory_pool_id: nil).where('owner_id = :ip_id AND inventory_pool_id != :ip_id', {ip_id: @current_inventory_pool.id}).detect { |l| l.properties[:operating_system] and l.properties[:license_type] } +Given( + / + ^there exists a software license, owned by my inventory pool, but given responsibility to another inventory pool$ + / +) do + @item = + @license = + Item.licenses.where.not(inventory_pool_id: nil).where( + 'owner_id = :ip_id AND inventory_pool_id != :ip_id', { ip_id: @current_inventory_pool.id } + ) + .detect { |l| l.properties[:operating_system] and l.properties[:license_type] } expect(@license).not_to be_nil end -Given(/^there exists a software license, which is not in stock and another inventory pool is responsible for it$/) do - @item = @license = Item.licenses.where.not(inventory_pool_id: nil).where('owner_id = :ip_id AND inventory_pool_id != :ip_id', {ip_id: @current_inventory_pool.id}).detect { |i| not i.in_stock? } +Given( + / + ^there exists a software license, which is not in stock and another inventory pool is responsible for it$ + / +) do + @item = + @license = + Item.licenses.where.not(inventory_pool_id: nil).where( + 'owner_id = :ip_id AND inventory_pool_id != :ip_id', { ip_id: @current_inventory_pool.id } + ) + .detect { |i| ni.in_stock? } expect(@license).not_to be_nil end @@ -731,22 +816,22 @@ def parsed_query(export_format) items = Item.by_owner_or_responsible(@current_inventory_pool).in_stock models = items.map(&:model).uniq elsif arg1 == 'Owned' - models = Model.joins(:items).where(items: {owner_id: @current_inventory_pool.id}).distinct + models = Model.joins(:items).where(items: { owner_id: @current_inventory_pool.id }).distinct else models = Model.owned_or_responsible_by_inventory_pool(@current_inventory_pool) case arg1 when 'borrowable' - models = models.where(items: {is_borrowable: true}) + models = models.where(items: { is_borrowable: true }) when 'unborrowable' - models = models.where(items: {is_borrowable: false}) + models = models.where(items: { is_borrowable: false }) when 'retired' - models = models.where.not(items: {retired: nil}) + models = models.where.not(items: { retired: nil }) when 'not retired' - models = models.where(items: {retired: nil}) + models = models.where(items: { retired: nil }) when 'Broken' - models = models.where(items: {is_broken: true}) + models = models.where(items: { is_broken: true }) when 'Incomplete' - models = models.where(items: {is_incomplete: true}) + models = models.where(items: { is_incomplete: true }) end end @@ -781,24 +866,21 @@ def parsed_query(export_format) end end -Given(/^one is on the list of the options$/) do - find('a', text: _('Options')).click -end +Given(/^one is on the list of the options$/) { find('a', text: _('Options')).click } When(/^I choose a certain responsible pool inside the whole inventory$/) do - @responsible_pool = \ - @current_inventory_pool - .own_items - .select(:inventory_pool_id, :id) - .where.not(items: {inventory_pool_id: [@current_inventory_pool.id, nil]}) - .distinct - .first - .inventory_pool + @responsible_pool = + @current_inventory_pool.own_items.select(:inventory_pool_id, :id).where.not( + items: { inventory_pool_id: [@current_inventory_pool.id, nil] } + ) + .distinct + .first + .inventory_pool find(:select, 'responsible_inventory_pool_id').find(:option, @responsible_pool.name).select_option end Then(/^only the inventory is shown for which this pool is responsible$/) do - inventory = @responsible_pool.items.where(items: {owner_id: @current_inventory_pool.id}) + inventory = @responsible_pool.items.where(items: { owner_id: @current_inventory_pool.id }) step 'I fetch all pages of the list' check_amount_of_lines inventory.joins(:model).select(:model_id).distinct.count check_existing_inventory_codes(inventory) @@ -850,11 +932,14 @@ def parsed_query(export_format) end Given(/^there exists an item with many problems$/) do - Item.select('items.id', :retired, :is_incomplete, :is_broken, :is_borrowable).by_owner_or_responsible(@current_inventory_pool).items.find do |i| + Item.select('items.id', :retired, :is_incomplete, :is_broken, :is_borrowable) + .by_owner_or_responsible(@current_inventory_pool) + .items + .find do |i| attrs = i.attributes item_id = attrs.delete('id') attrs['is_borrowable'] = !attrs['is_borrowable'] - attrs.values.select{|v| v}.count >= 2 and (@item_id = item_id) + attrs.values.select { |v| v }.count >= 2 and (@item_id = item_id) end @item = Item.find @item_id expect(@item).not_to be_nil @@ -865,7 +950,10 @@ def parsed_query(export_format) end When(/^I open the model line of this item$/) do - find(".line[data-type='model']", text: @item.model.name).find("[data-type='inventory-expander']", match: :first).click + find(".line[data-type='model']", text: @item.model.name).find( + "[data-type='inventory-expander']", match: :first + ) + .click end Then(/^the problems of this item are displayed separated by a comma$/) do diff --git a/features/step_definitions/manage/lending/lending_steps.rb b/features/step_definitions/manage/lending/lending_steps.rb index 364f81627d..ec1afa01a2 100644 --- a/features/step_definitions/manage/lending/lending_steps.rb +++ b/features/step_definitions/manage/lending/lending_steps.rb @@ -1,15 +1,13 @@ When(/^I open a hand over with an unassigned item line$/) do @event = 'hand_over' @customer = FactoryGirl.create(:user) - FactoryGirl.create(:access_right, - user: @customer, - inventory_pool: @current_inventory_pool, - role: :customer) - FactoryGirl.create(:reservation, - status: :approved, - item: nil, - inventory_pool: @current_inventory_pool, - user: @customer) + FactoryGirl.create( + :access_right, user: @customer, inventory_pool: @current_inventory_pool, role: :customer + ) + FactoryGirl.create( + :reservation, + status: :approved, item: nil, inventory_pool: @current_inventory_pool, user: @customer + ) visit manage_hand_over_path(@current_inventory_pool, @customer) end @@ -30,11 +28,13 @@ When /^I try to complete a hand over that contains a model with unborrowable items$/ do @reservation = nil - @order = @current_inventory_pool.orders.approved.detect do |c| - @reservation = c.item_lines.where(item_id: nil).detect do |l| - l.model.items.unborrowable.where(inventory_pool_id: @current_inventory_pool).first + @order = + @current_inventory_pool.orders.approved.detect do |c| + @reservation = + c.item_lines.where(item_id: nil).detect do |l| + l.model.items.unborrowable.where(inventory_pool_id: @current_inventory_pool).first + end end - end @model = @reservation.model @customer = @order.user step 'I open a hand over for this customer' @@ -57,14 +57,20 @@ end Given /^I (open|return to) the daily view$/ do |arg1| - @current_inventory_pool = @current_user.inventory_pools.managed.detect {|ip| ip.visits.hand_over.where(date: Date.today).exists? } + @current_inventory_pool = + @current_user.inventory_pools.managed.detect do |ip| + ip.visits.hand_over.where(date: Date.today).exists? + end visit manage_daily_view_path(@current_inventory_pool) find('#daily-view') end When(/^I edit an order for a user who is not suspended$/) do @event = 'order' - @order = @current_inventory_pool.orders.submitted.detect { |o| not o.user.suspended?(@current_inventory_pool) } + @order = + @current_inventory_pool.orders.submitted.detect do |o| + no.user.suspended?(@current_inventory_pool) + end @user = @order.user @customer = @order.user step 'I edit the order' @@ -80,9 +86,9 @@ When(/^I edit the latest problematic order$/) do @event = 'order' - @order = @current_inventory_pool.orders.submitted - .where(user_id: 'baf29045-ea7d-5880-be5b-efb8095a3216') - .first + @order = + @current_inventory_pool.orders.submitted.where(user_id: 'baf29045-ea7d-5880-be5b-efb8095a3216') + .first @user = @order.user @customer = @order.user step 'I edit the order' @@ -98,64 +104,61 @@ end When /^the chosen items contain some from a future hand over$/ do - find('#add-start-date').set I18n.l(Date.today+2.days) - find('#add-end-date').set I18n.l(Date.today+2.days) + find('#add-start-date').set I18n.l(Date.today + 2.days) + find('#add-end-date').set I18n.l(Date.today + 2.days) step 'I add an item to the hand over by providing an inventory code' end Then /^I see an error message( within the booking calendar)?$/ do |arg1| - if arg1 - within '.modal' do - find('#booking-calendar-errors', text: /.*/) - end - else - find('#flash .error') - end + arg1 ? within '.modal' dofind('#booking-calendar-errors', text: /.*/)end : find('#flash .error') end Then /^I see an error message in modal$/ do find('#error-modal') end - Then /^I cannot hand over the items$/ do expect(has_no_selector?('.hand_over .summary')).to be true end - Given /^the customer is in multiple groups$/ do - @customer = @current_inventory_pool.users.detect{|u| u.entitlement_groups.exists? } + @customer = @current_inventory_pool.users.detect { |u| u.entitlement_groups.exists? } expect(@customer).not_to be_nil end - When /^I open a hand over to this customer$/ do visit manage_hand_over_path(@current_inventory_pool, @customer) expect(has_selector?('#hand-over-view')).to be true step 'the availability is loaded' end - When /^I edit a line containing group partitions$/ do - @inventory_code = @current_inventory_pool.models.detect {|m| m.entitlements.size > 1}.items.in_stock.borrowable.first.inventory_code + @inventory_code = + @current_inventory_pool.models.detect { |m| m.entitlements.size > 1 }.items.in_stock.borrowable + .first + .inventory_code @model = Item.find_by_inventory_code(@inventory_code).model step 'I assign an item to the hand over by providing an inventory code and a date range' - find(:xpath, "//*[contains(@class, 'line') and descendant::input[@data-assign-item and @value='#{@inventory_code}']]", match: :first).find('button[data-edit-lines]').click + find( + :xpath, + "//*[contains(@class, 'line') and descendant::input[@data-assign-item and @value='#{@inventory_code}']]", + match: :first + ) + .find('button[data-edit-lines]') + .click end - When /^I expand the group selector$/ do find('#booking-calendar-partitions') end - Then /^I see which groups the customer is a member of$/ do @customer_group_ids = @customer.entitlement_groups.map(&:id) @model.entitlements.each do |partition| unless partition.entitlement_group_id.nil? if @customer_group_ids.include? partition.entitlement_group_id expect( - find("#booking-calendar-partitions optgroup[label='#{_("Groups of this customer")}']") + find("#booking-calendar-partitions optgroup[label='#{_('Groups of this customer')}']") ).to have_content partition.entitlement_group.name end end @@ -165,21 +168,24 @@ Then /^I see which groups the customer is not a member of$/ do @model.entitlements.each do |entitlement| unless entitlement.entitlement_group_id.nil? && - @customer_group_ids.include?(entitlement.entitlement_group_id) + @customer_group_ids.include?(entitlement.entitlement_group_id) expect( - find( "#booking-calendar-partitions optgroup[label='#{_("Other groups")}']") + find("#booking-calendar-partitions optgroup[label='#{_('Other groups')}']") ).to have_content entitlement.entitlement_group.name end end end - -When /^I open a hand over for a customer that has things to pick up today as well as in the future$/ do - @customer = @current_inventory_pool.users.detect{|u| u.visits.hand_over.to_a.size > 1} # NOTE count returns a Hash because the group() in default scope +When / + ^I open a hand over for a customer that has things to pick up today as well as in the future$ + / do + @customer = @current_inventory_pool.users.detect { |u| u.visits.hand_over.to_a.size > 1 } # NOTE count returns a Hash because the group() in default scope step 'I open a hand over to this customer' end -When /^I scan something \(assign it using its inventory code\) and it is already assigned to a future contract$/ do +When / + ^I scan something \(assign it using its inventory code\) and it is already assigned to a future contract$ + / do @customer.orders.approved.where(inventory_pool_id: @current_inventory_pool).detect do |order| order.models.detect do |model| @item = model.items.borrowable.in_stock.where(inventory_pool: @current_inventory_pool).first @@ -191,17 +197,18 @@ @assigned_line = find("[data-assign-item][disabled][value='#{@item.inventory_code}']") end - Then /^it is assigned \(whether it is selected or not\)$/ do @assigned_line.find(:xpath, './../../..').find("input[type='checkbox'][data-select-line]:checked") end When /^it doesn't exist in any future contracts$/ do - @model_not_in_order = (@current_inventory_pool.items.borrowable.in_stock.map(&:model).uniq - - @customer.orders.approved.find_by(inventory_pool_id: @current_inventory_pool).models).sample + @model_not_in_order = + (@current_inventory_pool.items.borrowable.in_stock.map(&:model).uniq - + @customer.orders.approved.find_by(inventory_pool_id: @current_inventory_pool).models) + .sample @item = @model_not_in_order.items.borrowable.in_stock.first - find('#add-start-date').set I18n.l(Date.today+7.days) - find('#add-end-date').set I18n.l(Date.today+8.days) + find('#add-start-date').set I18n.l(Date.today + 7.days) + find('#add-end-date').set I18n.l(Date.today + 8.days) find('#assign-or-add-input input').set @item.inventory_code @amount_lines_before = all('.line').size find('#assign-or-add button').click @@ -214,7 +221,6 @@ expect(@amount_lines_before).to be < all('.line').size end - Given /^I am doing a hand over( with models)?$/ do |with_models| @event = 'hand_over' step "I open a hand over#{with_models}" @@ -229,9 +235,7 @@ when 'Delegations' find('.dropdown-item', text: _('Delegations')).click else - rescue_displaced_flash do - step %Q(I press "#{arg1}") - end + rescue_displaced_flash { step "I press \"#{arg1}\"" } end end @@ -253,18 +257,13 @@ Then(/^there are inventory codes for item and license in the contract$/) do # Sleeps are not sexy, but for some reason on busy systems, the contract # window opens very slowly and then this test is reliably red. - if page.driver.browser.window_handles.count < 2 - sleep 2 - end + sleep 2 if page.driver.browser.window_handles.count < 2 page.driver.browser.switch_to.window(page.driver.browser.window_handles.last) - @inventory_codes.each {|inv_code| - expect(has_content?(inv_code)).to be true - } + @inventory_codes.each { |inv_code| expect(has_content?(inv_code)).to be true } end - Then /^I can inspect each item$/ do - line_ids = all(".line[data-line-type='item_line']", minimum: 1).map {|l| l['data-id']} + line_ids = all(".line[data-line-type='item_line']", minimum: 1).map { |l| l['data-id'] } line_ids.each do |id| within find(".line[data-id='#{id}'] .multibutton") do find('.dropdown-toggle').click @@ -273,7 +272,6 @@ end end - When /^I inspect an item$/ do within all(".line[data-line-type='item_line']", minimum: 1).to_a.sample.find('.multibutton') do @item = Reservation.find(JSON.parse(find('[data-ids]')['data-ids']).first).item @@ -321,9 +319,15 @@ check_printed_contract(window_handles, @current_inventory_pool, @item_line) end -When(/^start and end date are set to the corresponding dates of the hand over's first time window$/) do - first_dates = find('#hand-over-view #lines [data-selected-lines-container]', match: :first).find('.row .col1of2 p.paragraph-s', match: :first).text - start_date, end_date = first_dates.split('-').map{|x| Date.parse x} +When( + /^start and end date are set to the corresponding dates of the hand over's first time window$/ +) do + first_dates = + find('#hand-over-view #lines [data-selected-lines-container]', match: :first).find( + '.row .col1of2 p.paragraph-s', match: :first + ) + .text + start_date, end_date = first_dates.split('-').map { |x| Date.parse x } expect(Date.parse find('#add-start-date').value).to eq [start_date, Date.today].max expect(Date.parse find('#add-end-date').value).to eq [end_date, Date.today].max end @@ -334,30 +338,29 @@ find('#search_term').native.send_key :enter end - Then /^I see search results in the following categories:$/ do |table| within '#search-overview' do table.hashes.each do |t| case t[:category] - when 'Users' - find('#users .list-of-lines .line', match: :first) - when 'Models' - find('#models .list-of-lines .line', match: :first) - when 'Items' - find('#items .list-of-lines .line', match: :first) - when 'orders' - find('#orders .list-of-lines .line', match: :first) - when 'Orders' - find('#orders .list-of-lines .line', match: :first) - when 'Options' - find('#options .list-of-lines .line', match: :first) + when 'Users' + find('#users .list-of-lines .line', match: :first) + when 'Models' + find('#models .list-of-lines .line', match: :first) + when 'Items' + find('#items .list-of-lines .line', match: :first) + when 'orders' + find('#orders .list-of-lines .line', match: :first) + when 'Orders' + find('#orders .list-of-lines .line', match: :first) + when 'Options' + find('#options .list-of-lines .line', match: :first) end end end end Then /^I see at most the first (\d+) results from each category$/ do |amount| - amount = (amount.to_i+2) + amount = (amount.to_i + 2) expect(all('.user .list .line:not(.toggle)', visible: true).size).to be <= amount expect(all('.model .list .line:not(.toggle)', visible: true).size).to be <= amount expect(all('.item .list .line:not(.toggle)', visible: true).size).to be <= amount @@ -373,42 +376,37 @@ end Then /^I can choose to see more results from that category$/ do - - @lists.each do |list| - list.find('.toggle', match: :first) - end + @lists.each { |list| list.find('.toggle', match: :first) } end When /^I choose to see more results$/ do - @lists.each do |list| - list.find('.toggle .text', match: :first).click - end + @lists.each { |list| list.find('.toggle .text', match: :first).click } end - Then /^I see the first (\d+) results$/ do |amount| amount = amount.to_i + 2 @lists.each do |list| - if list.all('.show-all').size > 0 - expect(list.all('.line').size).to eq amount - end + expect(list.all('.line').size).to eq amount if list.all('.show-all').size > 0 end end When /^the category has more than (\d+) results$/ do |amount| amount = amount.to_i - @list_with_more_matches = all('.inlinetabs .badge').map do |badge| - badge.first(:xpath, '../../..').find('.list', match: :first) if badge.text.to_i > amount - end.compact + @list_with_more_matches = + all('.inlinetabs .badge').map do |badge| + badge.first(:xpath, '../../..').find('.list', match: :first) if badge.text.to_i > amount + end + .compact end Then /^I can choose to see all results$/ do - @links_of_more_results = @list_with_more_matches.map do |list| - list.find('.line.show-all a', visible: false)[:href] - end + @links_of_more_results = + @list_with_more_matches.map { |list| list.find('.line.show-all a', visible: false)[:href] } end -When /^I choose to see all results, I receive a separate list with all results from this category$/ do +When / + ^I choose to see all results, I receive a separate list with all results from this category$ + / do @links_of_more_results.each do |link| visit link find('#search_results.focused') @@ -436,16 +434,17 @@ Then /^each line shows the sum of items of the respective model$/ do within('.tooltipster-default', match: :first, visible: true) do - quantities = all('.row .col1of8:nth-child(1)', minimum: 1, text: /.+/).map{|x| x.text.to_i} + quantities = all('.row .col1of8:nth-child(1)', minimum: 1, text: /.+/).map { |x| x.text.to_i } expect(quantities.sum).to be >= quantities.size end end Then /^I open an order( placed by "(.*?)")$/ do |arg0, arg1| - step %Q(I uncheck the "No verification required" button) + step 'I uncheck the "No verification required" button' if arg0 - @order = @current_inventory_pool.orders.find find('.line', match: :prefer_exact, text: arg1)['data-id'] + @order = + @current_inventory_pool.orders.find find('.line', match: :prefer_exact, text: arg1)['data-id'] within('.line', match: :prefer_exact, text: arg1) do find('.line-actions .multibutton .dropdown-holder').click find('.dropdown-item', text: _('Edit')).click @@ -463,7 +462,6 @@ find('#daily-view strong', text: _('Last Visitors:')) end - Then(/^I see the previously opened order's user as last visitor$/) do find('#daily-view #last-visitors', text: @order.user.name) end @@ -473,20 +471,24 @@ end Then(/^I see search results matching that user's name$/) do - find('#search-overview h1', text: _("Search Results for \"%s\"") % @order.user.name) + find('#search-overview h1', text: _('Search Results for "%s"') % @order.user.name) end When(/^I enter something in the "(.*?)" field$/) do |field_label| case field_label - when 'Inventory Code/Name' - find('#assign-or-add-input input, #assign-input').set ' ' - else - raise + when 'Inventory Code/Name' + find('#assign-or-add-input input, #assign-input').set ' ' + else + raise end end When(/^I open a take back that contains options$/) do - @customer = @current_inventory_pool.users.all.select {|x| x.contracts.open.exists? and !x.contracts.open.detect{|c| c.options.exists? }.nil? }.first + @customer = + @current_inventory_pool.users.all.select do |x| + x.contracts.open.exists? and !x.contracts.open.detect { |c| c.options.exists? }.nil? + end + .first visit manage_take_back_path(@current_inventory_pool, @customer) expect(has_selector?('#take-back-view')).to be true end diff --git a/features/step_definitions/manage/lending/tabs_navigation_steps.rb b/features/step_definitions/manage/lending/tabs_navigation_steps.rb index 62314fad8a..a27ceb3188 100644 --- a/features/step_definitions/manage/lending/tabs_navigation_steps.rb +++ b/features/step_definitions/manage/lending/tabs_navigation_steps.rb @@ -1,11 +1,11 @@ Then /^I can navigate all navigation items and nested tabs$/ do - texts = find('#daily-view nav', match: :first).all('ul li a').map{|x| x.text} + texts = find('#daily-view nav', match: :first).all('ul li a').map(&:text) texts.shift texts.each do |text| find_link(text).click within '#list-tabs' do expect(has_selector?('.inline-tab-item')).to be true - tab_texts = all('.inline-tab-item').map{|x| x.text} + tab_texts = all('.inline-tab-item').map(&:text) tab_texts.each do |tab_text| find('.inline-tab-item', text: tab_text, match: :prefer_exact).click expect(find('.inline-tab-item.active').text[tab_text]).to be @@ -15,16 +15,18 @@ end When(/^I hover over the navigation toggler$/) do - find("nav.topbar .topbar-navigation.float-right > .topbar-item", match: :first).hover + find('nav.topbar .topbar-navigation.float-right > .topbar-item', match: :first).hover end When(/^I click the navigation toggler$/) do - find("nav.navbar .navbar-right > .dropdown", match: :first).click + find('nav.navbar .navbar-right > .dropdown', match: :first).click end Then(/^I see all inventory pools for which I am a manager$/) do within '#ip-dropdown-menu' do - @current_user.inventory_pools.managed.each {|ip| has_content? ip.name unless ip == @current_inventory_pool} + @current_user.inventory_pools.managed.each do |ip| + has_content? ip.name unless ip == @current_inventory_pool + end end end @@ -37,6 +39,8 @@ end Then(/^I switch to that inventory pool$/) do - find("nav.topbar .topbar-navigation.float-right > .topbar-item", match: :first, text: @changed_to_ip.name) + find( + 'nav.topbar .topbar-navigation.float-right > .topbar-item', + match: :first, text: @changed_to_ip.name + ) end - diff --git a/features/step_definitions/manage/lending_steps.rb b/features/step_definitions/manage/lending_steps.rb index e26bcc47a1..77d8194feb 100644 --- a/features/step_definitions/manage/lending_steps.rb +++ b/features/step_definitions/manage/lending_steps.rb @@ -1,8 +1,8 @@ # -*- encoding : utf-8 -*- - Then /^I see those items that are part of this take back$/ do - @customer.visits.take_back.where(inventory_pool_id: @current_inventory_pool).first.reservations.each do |line| + @customer.visits.take_back.where(inventory_pool_id: @current_inventory_pool).first.reservations + .each do |line| expect(find('.ui-autocomplete', match: :first).has_content? line.item.inventory_code).to be true end end @@ -18,7 +18,9 @@ def check_printed_contract(window_handles, ip = nil, reservation = nil) page.driver.browser.switch_to.window new_window within_window new_window do find('.contract') - expect(current_path).to eq manage_contract_path(ip, reservation.reload.contract) if ip and reservation + if ip and reservation + expect(current_path).to eq manage_contract_path(ip, reservation.reload.contract) + end expect(page.evaluate_script('window.printed')).to eq 1 end end diff --git a/features/step_definitions/manage/linegroup/selection_steps.rb b/features/step_definitions/manage/linegroup/selection_steps.rb index f04e9e7533..cba80be2a0 100644 --- a/features/step_definitions/manage/linegroup/selection_steps.rb +++ b/features/step_definitions/manage/linegroup/selection_steps.rb @@ -3,13 +3,13 @@ type = possible_types.sample case type when 'take_back' - @customer = @current_inventory_pool.users.detect {|x| x.contracts.open.exists? } + @customer = @current_inventory_pool.users.detect { |x| x.contracts.open.exists? } visit manage_take_back_path(@current_inventory_pool, @customer) when 'hand_over' - @customer = @current_inventory_pool.users.detect {|x| x.orders.approved.exists? } + @customer = @current_inventory_pool.users.detect { |x| x.orders.approved.exists? } step 'I open a hand over for this customer' when 'contract' - @customer = @current_inventory_pool.users.detect {|x| x.orders.submitted.exists? } + @customer = @current_inventory_pool.users.detect { |x| x.orders.submitted.exists? } @entity = @customer.orders.submitted.first visit manage_edit_order_path(@current_inventory_pool, @entity) end @@ -20,9 +20,7 @@ @linegroup = find('[data-selected-lines-container]', match: :first) within @linegroup do find('.line input[type=checkbox][data-select-line]', match: :first) - all('.line input[type=checkbox][data-select-line]', match: :first).map do |c| - c.click - end + all('.line input[type=checkbox][data-select-line]', match: :first).map(&:click) end end end @@ -32,7 +30,11 @@ end Then /^the count matches the amount of selected reservations$/ do - expect(all('input[type=checkbox][data-select-line]').select{|x| x.checked? }.size).to eq find('#line-selection-counter').text.to_i + expect(all('input[type=checkbox][data-select-line]').select(&:checked?).size).to eq find( + '#line-selection-counter' + ) + .text + .to_i end When /^I select the linegroup$/ do diff --git a/features/step_definitions/manage/model_properties_steps.rb b/features/step_definitions/manage/model_properties_steps.rb index 32e4db83f8..2a6bd74f14 100644 --- a/features/step_definitions/manage/model_properties_steps.rb +++ b/features/step_definitions/manage/model_properties_steps.rb @@ -4,13 +4,13 @@ #step 'ich ein neues Modell hinzufüge' step 'I add a new Model' #step 'ich erfasse die folgenden Details', table(%{ - step 'I enter the following details', table(%{ + step 'I enter the following details', + table(' | Field | Value | | Product | Test Model | - }) + ') end - When /^I add some properties and fill in their keys and values$/ do step 'I add the property "Dimensions" "(20x40cm)"' step 'I add the property "Power consumption" "2kWh"' @@ -18,30 +18,30 @@ step 'I add the property "Color" "Blue"' end -When /^I add the property "(.*?)" "(.*?)"$/ do |k,v| +When /^I add the property "(.*?)" "(.*?)"$/ do |k, v| find('.button.green', text: _('Save %s') % _('Model')) find('#add-property').click find("[name='model[properties_attributes][][key]']", match: :first).set k find("[name='model[properties_attributes][][value]']", match: :first).set v end - When /^I sort the properties$/ do within '#properties' do find('.list-of-lines.ui-sortable') # real sorting is not possible with capybara/selenium - @properties = all('.list-of-lines .line').map{|line| {key: line.find("input[name='model[properties_attributes][][key]']").value, value: line.find("input[name='model[properties_attributes][][value]']").value}} + @properties = + all('.list-of-lines .line').map do |line| + { + key: line.find("input[name='model[properties_attributes][][key]']").value, + value: line.find("input[name='model[properties_attributes][][value]']").value + } + end end end - Then /^this model's properties are saved in the order they were given$/ do find('.line', match: :first) # can't seem to find the proper model otherwise - if @model - model = @model - else - model = Model.order('created_at DESC').first - end + @model ? model = @model : model = Model.order('created_at DESC').first expect(model.properties.empty?).to be false model.properties.each_with_index do |property, i| expect(property.key).to eq @properties[i][:key] @@ -78,6 +78,12 @@ When /^I delete one or more existing properties$/ do within '#properties' do find('.list-of-lines .line:not(.striked) .button[data-remove]', match: :first).click - @properties = all('.list-of-lines .line:not(.striked)').map{|line| {key: line.find("input[name='model[properties_attributes][][key]']").value, value: line.find("input[name='model[properties_attributes][][value]']").value}} + @properties = + all('.list-of-lines .line:not(.striked)').map do |line| + { + key: line.find("input[name='model[properties_attributes][][key]']").value, + value: line.find("input[name='model[properties_attributes][][value]']").value + } + end end end diff --git a/features/step_definitions/manage/modell_steps.rb b/features/step_definitions/manage/modell_steps.rb index 43f2af1d44..406afbecde 100644 --- a/features/step_definitions/manage/modell_steps.rb +++ b/features/step_definitions/manage/modell_steps.rb @@ -10,25 +10,30 @@ Then(/^a compatible model has been added to the model I am editing$/) do find('#flash') expect(@model.compatibles.size).to be 2 - expect(@model.compatibles.any? {|m| m.name == @comp1.name}).to be true - expect(@model.compatibles.any? {|m| m.name == @comp2.name}).to be true + expect(@model.compatibles.any? { |m| m.name == @comp1.name }).to be true + expect(@model.compatibles.any? { |m| m.name == @comp2.name }).to be true end When(/^I open a model that already has compatible models$/) do - @model = @current_inventory_pool.models.detect {|m| m.compatibles.exists? } - - @model ||= begin - @current_inventory_pool = @current_user.inventory_pools.managed.select {|ip| not ip.models.empty? and ip.models.any? {|m| m.compatibles.exists?} }.sample - step 'I open the inventory' - @current_inventory_pool.models.detect {|m| m.compatibles.exists? } - end + @model = @current_inventory_pool.models.detect { |m| m.compatibles.exists? } + + @model ||= + begin + @current_inventory_pool = + @current_user.inventory_pools.managed.select do |ip| + nip.models.empty? and ip.models.any? { |m| m.compatibles.exists? } + end + .sample + step 'I open the inventory' + @current_inventory_pool.models.detect { |m| m.compatibles.exists? } + end step 'I search for "%s"' % @model.name find('.line', match: :first, text: @model.name).find('.button', text: _('Edit Model')).click end When(/^I remove a compatible model$/) do - find('.field', match: :first, text: _('Compatibles')).all('[data-remove]').each {|comp| comp.click} + find('.field', match: :first, text: _('Compatibles')).all('[data-remove]').each(&:click) end Then(/^the model is saved without the compatible model that I removed$/) do @@ -54,50 +59,54 @@ end Given(/^there is a? (.+) with the following conditions:$/) do |entity, table| - conditions = table.raw.flatten.map do |condition| - case condition + conditions = + table.raw.flatten.map do |condition| + case condition when 'not in any contract', 'not in any order' - lambda {|m| m.reservations.empty?} + lambda { |m| m.reservations.empty? } when 'no items assigned' - lambda {|m| m.items.items.empty?} + lambda { |m| m.items.items.empty? } when 'has no licenses' - lambda {|m| m.items.licenses.empty?} + lambda { |m| m.items.licenses.empty? } when 'has group capacities' - lambda {|m| Entitlement.find_by_model_id(m.id)} + lambda { |m| Entitlement.find_by_model_id(m.id) } when 'has properties' - lambda {|m| not m.properties.empty?} + lambda { |m| nm.properties.empty? } when 'has accessories' - lambda {|m| not m.accessories.empty?} + lambda { |m| nm.accessories.empty? } when 'has images' - lambda {|m| not m.images.empty?} + lambda { |m| nm.images.empty? } when 'has attachments' - lambda {|m| not m.attachments.empty?} + lambda { |m| nm.attachments.empty? } when 'is assigned to categories' - lambda {|m| not m.categories.empty?} + lambda { |m| nm.categories.empty? } when 'has compatible models' - lambda {|m| not m.compatibles.empty?} + lambda { |m| nm.compatibles.empty? } else false + end end - end - klass = case entity - when 'model' then Model - when 'software' then Software - end - @model = klass.find {|m| conditions.map{|c| c.class == Proc ? c.call(m) : c}.all?} + klass = + case entity + when 'model' + Model + when 'software' + Software + end + @model = klass.find { |m| conditions.map { |c| c.class == Proc ? c.call(m) : c }.all? } expect(@model).not_to be_nil end - Given /^the model has an assigned (.+)$/ do |assoc| - @model = @current_inventory_pool.models.find do |m| - case assoc + @model = + @current_inventory_pool.models.find do |m| + case assoc when 'contract', 'order' - not m.reservations.empty? + nm.reservations.empty? when 'item' - not m.items.empty? + nm.items.empty? + end end - end end Then(/^I cannot delete the model from the list$/) do @@ -116,30 +125,32 @@ expect(Image.where(target_id: @model.id).empty?).to be true expect(Attachment.where(model_id: @model.id).empty?).to be true expect(ModelLink.where(model_id: @model.id).empty?).to be true - expect(Model.all {|n| n.compatibles.include? Model.find_by_name('Windows Laptop')}.include?(@model)).to be false + expect( + Model.all { |n| n.compatibles.include? Model.find_by_name('Windows Laptop') }.include?(@model) + ).to be false end Then(/^the (?:.+) was deleted from the list$/) do - [@model, @group, @template].compact.each {|entity| + [@model, @group, @template].compact.each do |entity| expect(has_no_content?(entity.name)).to be true - } + end end Given(/^I edit a model that exists and has group capacities allocated to it$/) do - @model = @current_inventory_pool.models.find{|m| m.entitlements.exists? } + @model = @current_inventory_pool.models.find { |m| m.entitlements.exists? } visit manage_edit_model_path(@current_inventory_pool, @model) end When(/^I remove existing allocations$/) do - find('.field', match: :first, text: _('Allocations')).all('button', text: _('Remove')).each {|comp| comp.click} + find('.field', match: :first, text: _('Allocations')).all('button', text: _('Remove')) + .each(&:click) end When(/^I add new allocations$/) do - @groups = @current_inventory_pool.entitlement_groups - @model.entitlements.map(&:entitlement_group) + @groups = + @current_inventory_pool.entitlement_groups - @model.entitlements.map(&:entitlement_group) - @groups.each do |group| - fill_in_autocomplete_field _('Allocations'), group.name - end + @groups.each { |group| fill_in_autocomplete_field _('Allocations'), group.name } end Then(/^the changed allocations are saved$/) do @@ -183,9 +194,12 @@ Then(/^the (.+) is deleted$/) do |entity| find('#flash') - klass = case entity - when 'model' then Model - when 'software' then Software - end + klass = + case entity + when 'model' + Model + when 'software' + Software + end expect(klass.find_by_id(@model.id)).to eq nil end diff --git a/features/step_definitions/manage/old_timeline_steps.rb b/features/step_definitions/manage/old_timeline_steps.rb index 052b3676ed..570dfeb0a8 100644 --- a/features/step_definitions/manage/old_timeline_steps.rb +++ b/features/step_definitions/manage/old_timeline_steps.rb @@ -1,23 +1,22 @@ # -*- encoding : utf-8 -*- - def for_each_visible_model_I_can_see_the_Timeline(in_new_window) line_selector = nil parent_id = nil - if not all('#edit-contract-view').empty? + if nall('#edit-contract-view').empty? line_selector = '.order-line' parent_id = '#edit-contract-view' - elsif not all('#hand-over-view').empty? + elsif nall('#hand-over-view').empty? line_selector = ".line[data-line-type='item_line']" parent_id = '#hand-over-view' - elsif not all('#take-back-view').empty? + elsif nall('#take-back-view').empty? line_selector = ".line[data-line-type='item_line']" parent_id = '#take-back-view' - elsif not all('#search-overview').empty? + elsif nall('#search-overview').empty? line_selector = ".line[data-type='model']" parent_id = '#search-overview' - elsif not all('#inventory').empty? + elsif nall('#inventory').empty? line_selector = ".line[data-type='model']" parent_id = '#inventory' else @@ -28,10 +27,10 @@ def for_each_visible_model_I_can_see_the_Timeline(in_new_window) current_role = @current_user.access_right_for(@current_inventory_pool).role - line_texts = find(parent_id).all(line_selector, visible: true).map do |line_element| - line_element.find('.test-fix-timeline').text - end - + line_texts = + find(parent_id).all(line_selector, visible: true).map do |line_element| + line_element.find('.test-fix-timeline').text + end line_texts[0..5].each do |line_text| line = find(line_selector, text: line_text) @@ -45,7 +44,7 @@ def for_each_visible_model_I_can_see_the_Timeline(in_new_window) end end if in_new_window - new_window = window_opened_by { timeline_button.click } + new_window = window_opened_by { timeline_button.click } within_window new_window do find('div.row > div > div > div', text: 'Total') new_window.close @@ -53,7 +52,7 @@ def for_each_visible_model_I_can_see_the_Timeline(in_new_window) else timeline_button.click find('.modal iframe') - evaluate_script %Q{ $(".modal iframe").contents().first("#my_timeline").length; } + evaluate_script ' $(".modal iframe").contents().first("#my_timeline").length; ' find('.modal .button', text: _('Close')).click step 'the modal is closed' end diff --git a/features/step_definitions/manage/orders_steps.rb b/features/step_definitions/manage/orders_steps.rb index 02283422ff..74bf664206 100644 --- a/features/step_definitions/manage/orders_steps.rb +++ b/features/step_definitions/manage/orders_steps.rb @@ -21,15 +21,22 @@ find('span.darkred-text', text: '%s!' % _('Suspended')) end -def ensure_suspended_user(user, inventory_pool, suspended_until = rand(1.years.from_now..3.years.from_now).to_date, suspended_reason = Faker::Lorem.paragraph) +def ensure_suspended_user(user, inventory_pool, suspended_until = rand( + 1.years.from_now..3.years.from_now +) + .to_date, suspended_reason = Faker::Lorem.paragraph) unless user.suspended?(inventory_pool) - user.access_rights.active.where(inventory_pool_id: inventory_pool).first.update_attributes(suspended_until: suspended_until, suspended_reason: suspended_reason) + user.access_rights.active.where(inventory_pool_id: inventory_pool).first.update_attributes( + suspended_until: suspended_until, suspended_reason: suspended_reason + ) expect(user.suspended?(inventory_pool)).to be true end end Given(/^an order contains overbooked models$/) do - @contract = @current_inventory_pool.orders.submitted.joins(:reservations).with_verifiable_user_and_model.detect {|c| not c.approvable?} + @contract = + @current_inventory_pool.orders.submitted.joins(:reservations).with_verifiable_user_and_model + .detect { |c| nc.approvable? } expect(@contract).not_to be_nil end @@ -55,20 +62,18 @@ def ensure_suspended_user(user, inventory_pool, suspended_until = rand(1.years.f Then(/^I see the tabs "(.*?)"$/) do |tabs| within '.inline-tab-navigation' do - tabs.split(', ').each do |tab| - find('.inline-tab-item', text: tab) - end + tabs.split(', ').each { |tab| find('.inline-tab-item', text: tab) } end end - Given(/^a verifiable order exists$/) do @contract = Order.joins(:reservations).with_verifiable_user_and_model.first expect(@contract).not_to be_nil end Then(/^this order was created by a user that is in a group whose orders require verification$/) do - EntitlementGroup.where(is_verification_required: true).flat_map(&:users).uniq.include? @contract.user + EntitlementGroup.where(is_verification_required: true).flat_map(&:users).uniq.include? @contract + .user end Then(/^this order contains a model from a group whose orders require verification$/) do @@ -83,36 +88,28 @@ def ensure_suspended_user(user, inventory_pool, suspended_until = rand(1.years.f Then(/^I see all verifiable orders$/) do step 'I scroll to the end of the list' - @contracts = \ - @current_inventory_pool - .orders - .where(state: [:submitted, :approved, :rejected]) - .joins(:reservations) - .with_verifiable_user_and_model - .with_some_line_not_in_any_contract - @contracts.each {|c| - expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true - } + @contracts = + @current_inventory_pool.orders.where(state: [:submitted, :approved, :rejected]).joins( + :reservations + ) + .with_verifiable_user_and_model + .with_some_line_not_in_any_contract + @contracts.each { |c| expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true } end Then(/^these orders are ordered by creation date$/) do - expect(all("[data-type='order']").map { |x| x['data-id'] }) - .to be == @contracts.order('created_at DESC').map(&:id) + expect(all("[data-type='order']").map { |x| x['data-id'] }).to be == + @contracts.order('created_at DESC').map(&:id) end Then(/^I see all pending verifiable orders$/) do step 'I scroll to the end of the list' - @contracts = \ - @current_inventory_pool - .orders - .where(state: :submitted) - .joins(:reservations) - .with_verifiable_user_and_model - @contracts.each {|c| - expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true - } + @contracts = + @current_inventory_pool.orders.where(state: :submitted).joins(:reservations) + .with_verifiable_user_and_model + @contracts.each { |c| expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true } @contract = @contracts.first - @line_css = "[data-type='order'][data-id='#{@contract.id}']" + @line_css = "[data-type='order'][data-id='#{@contract.id}']" end Then(/^I see who placed this order on the order line and can view a popup with user details$/) do @@ -123,36 +120,41 @@ def ensure_suspended_user(user, inventory_pool, suspended_until = rand(1.years.f Then(/^I see the order's creation date on the order line$/) do extend ActionView::Helpers::DateHelper - text = if @contract.created_at.today? - _('Today') - elsif @contract.created_at.to_date == Date.yesterday - _('one day ago') - else - "#{time_ago_in_words(@contract.created_at)} ago" - end + text = + if @contract.created_at.today? + _('Today') + elsif @contract.created_at.to_date == Date.yesterday + _('one day ago') + else + "#{time_ago_in_words(@contract.created_at)} ago" + end find(@line_css, text: text) end -Then(/^I see the number of items on the order line and can view a popup containing the items ordered$/) do +Then( + /^I see the number of items on the order line and can view a popup containing the items ordered$/ +) do sum_quantity = @contract.reservations.map(&:quantity).sum - find("#{@line_css} [data-type='lines-cell']", text: "#{sum_quantity} #{n_("Item", "Items", sum_quantity)}") + find( + "#{@line_css} [data-type='lines-cell']", + text: "#{sum_quantity} #{n_('Item', 'Items', sum_quantity)}" + ) .hover within find('.tooltipster-base') do - @contract.models.each do |m| - page.should have_content m.name - end + @contract.models.each { |m| page.should have_content m.name } end end Then(/^I see the duration of the order on the order line$/) do - expect(find(@line_css).has_content? "#{@contract.max_range} #{n_("day", "days", @contract.max_range)}").to be true + expect( + find(@line_css).has_content? "#{@contract.max_range} #{n_('day', 'days', @contract.max_range)}" + ).to be true end Then(/^I see the purpose on the order line$/) do expect(find(@line_css).has_content? @contract.purpose.to_s).to be true end - Then(/^I can approve the order$/) do expect(find(@line_css).has_selector? '[data-order-approve]').to be true end @@ -162,7 +164,12 @@ def ensure_suspended_user(user, inventory_pool, suspended_until = rand(1.years.f end Then(/^I can edit the order$/) do - expect(find(@line_css).has_selector? "[href*='#{manage_edit_order_path(@current_inventory_pool, @contract)}']", visible: false).to be true + expect( + find(@line_css).has_selector? "[href*='#{manage_edit_order_path( + @current_inventory_pool, @contract + )}']", + visible: false + ).to be true end Then(/^I cannot hand over orders$/) do @@ -171,18 +178,13 @@ def ensure_suspended_user(user, inventory_pool, suspended_until = rand(1.years.f Then(/^I see all verified and approved orders$/) do step 'I scroll to the end of the list' - @contracts = \ - @current_inventory_pool - .orders - .where(state: :approved) - .joins(:reservations) - .with_verifiable_user_and_model - .with_some_line_not_in_any_contract - @contracts.each {|c| - expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true - } + @contracts = + @current_inventory_pool.orders.where(state: :approved).joins(:reservations) + .with_verifiable_user_and_model + .with_some_line_not_in_any_contract + @contracts.each { |c| expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true } @contract = @contracts.first - @line_css = "[data-type='order'][data-id='#{@contract.id}']" + @line_css = "[data-type='order'][data-id='#{@contract.id}']" end Then(/^I see the order's status on the order line$/) do @@ -191,36 +193,26 @@ def ensure_suspended_user(user, inventory_pool, suspended_until = rand(1.years.f Then(/^I see all verifiable rejected orders$/) do step 'I scroll to the end of the list' - @contracts = \ - @current_inventory_pool - .orders - .where(state: :rejected) - .joins(:reservations) - .with_verifiable_user_and_model - @contracts.each {|c| - expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true - } + @contracts = + @current_inventory_pool.orders.where(state: :rejected).joins(:reservations) + .with_verifiable_user_and_model + @contracts.each { |c| expect(has_selector?("[data-type='order'][data-id='#{c.id}']")).to be true } @contract = @contracts.first - @line_css = "[data-type='order'][data-id='#{@contract.id}']" + @line_css = "[data-type='order'][data-id='#{@contract.id}']" end -When(/^I uncheck the filter "(.*?)"$/) do |filter| - uncheck filter -end +When(/^I uncheck the filter "(.*?)"$/) { |filter| uncheck filter } Then(/^I see orders placed by users in groups requiring verification$/) do step 'I scroll to the end of the list' within '#contracts' do - @contracts = \ - @current_inventory_pool - .orders - .joins(:reservations) - .where(state: [:submitted, :approved, :rejected]) - .with_verifiable_user - .with_some_line_not_in_any_contract - @contracts.each do |contract| - find(".line[data-type='order'][data-id='#{contract.id}']") - end + @contracts = + @current_inventory_pool.orders.joins(:reservations).where( + state: [:submitted, :approved, :rejected] + ) + .with_verifiable_user + .with_some_line_not_in_any_contract + @contracts.each { |contract| find(".line[data-type='order'][data-id='#{contract.id}']") } end end @@ -257,11 +249,20 @@ def hand_over_assign_or_add(s) end Then(/^I can add models$/) do - @model = if @current_user.access_right_for(@current_inventory_pool).role == :group_manager - @current_inventory_pool.models.select {|m| m.availability_in(@current_inventory_pool).maximum_available_in_period_summed_for_groups(Date.today, Date.today) > 0 } - else - @current_inventory_pool.models - end.detect {|m| m.items.where(inventory_pool_id: @current_inventory_pool, parent_id: nil).exists? } + @model = + if @current_user.access_right_for(@current_inventory_pool).role == :group_manager + @current_inventory_pool.models.select do |m| + m.availability_in(@current_inventory_pool).maximum_available_in_period_summed_for_groups( + Date.today, Date.today + ) > + 0 + end + else + @current_inventory_pool.models + end + .detect do |m| + m.items.where(inventory_pool_id: @current_inventory_pool, parent_id: nil).exists? + end hand_over_assign_or_add @model.to_s end @@ -270,7 +271,6 @@ def hand_over_assign_or_add(s) hand_over_assign_or_add option.to_s end - But(/^I cannot assign items$/) do find("[data-line-type='item_line']", minimum: 1, match: :first) all("[data-line-type='item_line']", minimum: 1).each do |dom_line| @@ -285,72 +285,67 @@ def hand_over_assign_or_add(s) When(/^I am listing the (orders|contracts|visits)$/) do |arg1| case arg1 + when 'orders' + visit manage_orders_path(@current_inventory_pool, state: [:approved, :submitted, :rejected]) + when 'contracts' + visit manage_contracts_path(@current_inventory_pool, state: [:open, :closed]) + when 'visits' + visit manage_inventory_pool_visits_path(@current_inventory_pool) + else + raise + end +end + +Given(/^(orders|contracts|visits) exist$/) do |arg1| + @contracts = + case arg1 when 'orders' - visit manage_orders_path(@current_inventory_pool, state: [:approved, :submitted, :rejected]) + @current_inventory_pool.orders.where(state: [:submitted, :approved, :rejected]) when 'contracts' - visit manage_contracts_path(@current_inventory_pool, state: [:open, :closed]) + @current_inventory_pool.contracts when 'visits' - visit manage_inventory_pool_visits_path(@current_inventory_pool) + @current_inventory_pool.visits.where(is_approved: true) else raise - end -end - -Given(/^(orders|contracts|visits) exist$/) do |arg1| - @contracts = case arg1 - when 'orders' - @current_inventory_pool.orders.where(state: [:submitted, :approved, :rejected]) - when 'contracts' - @current_inventory_pool.contracts - when 'visits' - @current_inventory_pool.visits.where(is_approved: true) - else - raise - end + end expect(@contracts.exists?).to be true end When(/^I search for an order which does not need verification using the user name$/) do - @contract = \ - @current_inventory_pool - .orders - .joins(:reservations) - .with_some_line_not_in_any_contract - .no_verification_required - .first + @contract = + @current_inventory_pool.orders.joins(:reservations).with_some_line_not_in_any_contract + .no_verification_required + .first @search_term = @contract.user.to_s within '#contracts-index-view' do - step %Q(I search for "%s") % @search_term + step 'I search for "%s"' % @search_term end end When(/^I search for an order which does not need verification using the purpose$/) do - @contract = \ - @current_inventory_pool - .orders - .joins(:reservations) - .with_some_line_not_in_any_contract - .no_verification_required - .first + @contract = + @current_inventory_pool.orders.joins(:reservations).with_some_line_not_in_any_contract + .no_verification_required + .first @search_term = @contract.purpose within '#contracts-index-view' do - step %Q(I search for "%s") % @search_term + step 'I search for "%s"' % @search_term end end -When(/^I search( globally)? for (an order|a contract|a visit)( with its purpose)?$/) do |arg0, arg1, arg2| +When( + /^I search( globally)? for (an order|a contract|a visit)( with its purpose)?$/ +) do |arg0, arg1, arg2| if arg1 == 'a contract' @contract = @current_inventory_pool.contracts.first elsif arg1 == 'an order' - @contract = @current_inventory_pool.orders.joins(:reservations).with_some_line_not_in_any_contract.first + @contract = + @current_inventory_pool.orders.joins(:reservations).with_some_line_not_in_any_contract.first elsif arg1 == 'a visit' @contract = @current_inventory_pool.visits.where(is_approved: true).first end - @search_term = if arg2 - @contract.purpose.split.sample.gsub(/^\W*/, '').gsub(/\W*$/, '') - else - @contract.user.to_s - end + @search_term = + arg2 ? @contract.purpose.split.sample.gsub(/^\W*/, '').gsub(/\W*$/, '') : @contract.user.to_s if arg0 within '#topbar #search' do find('input#search_term').set @search_term @@ -359,7 +354,7 @@ def hand_over_assign_or_add(s) else el = arg1 == 'a visit' ? '#visits-index-view' : '#contracts-index-view' within el do - step %Q(I search for "%s") % @search_term + step 'I search for "%s"' % @search_term end end end @@ -367,11 +362,9 @@ def hand_over_assign_or_add(s) Then(/^all listed visits match the search term$/) do within '.list-of-lines' do find(".line[data-id='#{@contract.id}']") - contract_ids = all('.line').map{|x| x['data-id'] }.sort - matching_contracts_ids = \ - @contracts - .filter2(search_term: @search_term) - .map(&:id).map(&:to_s).sort + contract_ids = all('.line').map { |x| x['data-id'] }.sort + matching_contracts_ids = + @contracts.filter2(search_term: @search_term).map(&:id).map(&:to_s).sort expect(contract_ids).to eq matching_contracts_ids end end @@ -379,12 +372,10 @@ def hand_over_assign_or_add(s) Then(/^all listed (?:orders|contracts) match the search term$/) do within '.list-of-lines' do find(".line[data-id='#{@contract.id}']") - contract_ids = all('.line').map{|x| x['data-id'] }.sort - matching_contracts_ids = \ - @contracts - .no_verification_required - .filter2(search_term: @search_term) - .map(&:id).map(&:to_s).sort + contract_ids = all('.line').map { |x| x['data-id'] }.sort + matching_contracts_ids = + @contracts.no_verification_required.filter2(search_term: @search_term).map(&:id).map(&:to_s) + .sort expect(contract_ids).to eq matching_contracts_ids end end diff --git a/features/step_definitions/manage/package_steps.rb b/features/step_definitions/manage/package_steps.rb index fe531a753a..293c9168d4 100644 --- a/features/step_definitions/manage/package_steps.rb +++ b/features/step_definitions/manage/package_steps.rb @@ -2,7 +2,8 @@ When /^I fill in at least the required fields$/ do @model_name = 'Test Model Package' - find('.row.emboss', match: :prefer_exact, text: _('Product')).fill_in 'model[product]', with: @model_name + find('.row.emboss', match: :prefer_exact, text: _('Product')).fill_in 'model[product]', + with: @model_name end When /^I add one or more packages$/ do @@ -24,13 +25,16 @@ Then /^the model is created and the packages and their assigned items are saved$/ do expect(has_selector?('.success')).to be true - @model = Model.find {|m| [m.name, m.product].include? @model_name} + @model = Model.find { |m| [m.name, m.product].include? @model_name } expect(@model.nil?).to be false expect(@model.is_package?).to be true @packages = @model.items expect(@packages.count).to eq 1 - expect(@packages.first.children.map(&:inventory_code)) - .to match_array ['beam123', 'beam345', 'bose123'] + expect(@packages.first.children.map(&:inventory_code)).to match_array [ + 'beam123', + 'beam345', + 'bose123' + ] end Then /^the packages have their own inventory codes$/ do @@ -39,12 +43,13 @@ Given /^a (never|once) handed over item package is currently in stock$/ do |arg1| item_packages = @current_inventory_pool.items.packages.in_stock - @package = case arg1 - when 'never' - item_packages.detect {|p| p.item_lines.empty? } - when 'once' - item_packages.detect {|p| p.item_lines.exists? } - end + @package = + case arg1 + when 'never' + item_packages.detect { |p| p.item_lines.empty? } + when 'once' + item_packages.detect { |p| p.item_lines.exists? } + end end When(/^edit the related model package$/) do @@ -61,20 +66,18 @@ Then(/^the item package has been (deleted|retired)$/) do |arg1| case arg1 - when 'deleted' - expect(Item.find_by_id(@package.id).nil?).to be true - expect { @package.reload }.to raise_error(ActiveRecord::RecordNotFound) - when 'retired' - expect(Item.find_by_id(@package.id).nil?).to be false - expect(@package.reload.retired).to eq Date.today + when 'deleted' + expect(Item.find_by_id(@package.id).nil?).to be true + expect { @package.reload }.to raise_error(ActiveRecord::RecordNotFound) + when 'retired' + expect(Item.find_by_id(@package.id).nil?).to be false + expect(@package.reload.retired).to eq Date.today end end Then /^the packaged items are not part of that item package anymore$/ do expect(@package_item_ids.size).to be > 0 - @package_item_ids.each do |id| - expect(Item.find(id).parent_id).to eq nil - end + @package_item_ids.each { |id| expect(Item.find(id).parent_id).to eq nil } end Then(/^that item package is not listed$/) do @@ -87,32 +90,41 @@ end Then /^I can't delete the package$/ do - expect(has_no_selector?("[data-type='inline-entry'][data-id='#{@package_not_in_stock.id}'] [data-remove]")).to be true + expect( + has_no_selector?( + "[data-type='inline-entry'][data-id='#{@package_not_in_stock.id}'] [data-remove]" + ) + ).to be true end When /^I edit a model that already has packages( in mine and other inventory pools)?$/ do |arg1| step 'I open the inventory' - @model = @current_inventory_pool.models.detect do |m| - b = (not m.items.empty? and m.is_package?) - if arg1 - b = (b and m.items.map(&:inventory_pool_id).uniq.size > 1) + @model = + @current_inventory_pool.models.detect do |m| + b = (nm.items.empty? and m.is_package?) + b = (b and m.items.map(&:inventory_pool_id).uniq.size > 1) if arg1 + b end - b - end expect(@model).not_to be_nil @model_name = @model.name step 'I search for "%s"' % @model.name expect(has_selector?('.line', text: @model.name)).to be true - find('.line', match: :prefer_exact, text: @model.name).find('.button', match: :first, text: _('Edit Model')).click + find('.line', match: :prefer_exact, text: @model.name).find( + '.button', match: :first, text: _('Edit Model') + ) + .click end When /^I edit a model that already has items$/ do step 'I open the inventory' - @model = @current_inventory_pool.models.detect {|m| not (m.items.empty? and m.is_package?)} + @model = @current_inventory_pool.models.detect { |m| n(m.items.empty? and m.is_package?) } @model_name = @model.name step 'I search for "%s"' % @model.name expect(has_selector?('.line', text: @model.name)).to be true - find('.line', match: :prefer_exact, text: @model.name).find('.button', match: :first, text: _('Edit Model')).click + find('.line', match: :prefer_exact, text: @model.name).find( + '.button', match: :first, text: _('Edit Model') + ) + .click end Then /^I cannot assign packages to that model$/ do @@ -128,13 +140,13 @@ Then /^I can only save this package if I also assign items$/ do find('#save-package').click expect(has_content?(_('You can not create a package without any item'))).to be true - find("h3", text: _('Package')) + find('h3', text: _('Package')) find('.modal-close').click expect(has_no_selector?("[data-type='field-inline-entry']")).to be true end When /^I edit a package$/ do - @model = Model.find {|m| [m.name, m.product].include? 'Kamera Set' } + @model = Model.find { |m| [m.name, m.product].include? 'Kamera Set' } visit manage_edit_model_path(@current_inventory_pool, @model) @package_to_edit = @model.items.detect &:in_stock? find(".line[data-id='#{@package_to_edit.id}']").find('button[data-edit-package]').click @@ -159,7 +171,7 @@ expect(page).to have_selector('#inventory .row') @package_to_edit.reload expect(@package_to_edit.children.count).to eq (@number_of_items_before - 1) - expect(@package_to_edit.children.detect {|i| i.inventory_code == @item_to_remove}).to eq nil + expect(@package_to_edit.children.detect { |i| i.inventory_code == @item_to_remove }).to eq nil end When /^I save the package$/ do @@ -172,7 +184,7 @@ end Then /^the package has all the entered information$/ do - model = Model.find {|m| [m.name, m.product].include? @model_name} + model = Model.find { |m| [m.name, m.product].include? @model_name } visit manage_edit_model_path(@current_inventory_pool, model) model.items.where(inventory_pool: @current_inventory_pool).each do |item| expect(has_selector?(".line[data-id='#{item.id}']", visible: false)).to be true @@ -193,7 +205,7 @@ end When(/^I enter the package properties$/) do - steps %Q{And I enter the following item information + steps 'And I enter the following item information | field | type | value | | Working order | radio | OK | | Completeness | radio | OK | @@ -208,16 +220,12 @@ | Building | autocomplete | general building | | Room | autocomplete | general room | | Shelf | | Test Gestell | - | Initial Price | | 50.00 | } + | Initial Price | | 50.00 | ' end -When(/^I save this package$/) do - find('#save-package').click -end +When(/^I save this package$/) { find('#save-package').click } -Then(/^I see the notice "(.*?)"$/) do |text| - find('#flash', match: :prefer_exact, text: text) -end +Then(/^I see the notice "(.*?)"$/) { |text| find('#flash', match: :prefer_exact, text: text) } Then /^the package has all the previously entered values$/ do expect(has_selector?('.modal .row.emboss')).to be true @@ -225,19 +233,23 @@ field_name = hash_row['field'] field_value = hash_row['value'] field_type = hash_row['type'] - field = Field.all.detect{|f| _(f.data['label']) == field_name} + field = Field.all.detect { |f| _(f.data['label']) == field_name } within '.modal' do matched_field = all("[data-type='field'][data-id='#{field.id}']", minimum: 1).last expect(matched_field).not_to be_blank case field_type - when 'autocomplete' - expect(matched_field.find('input,textarea').value).to eq (field_value != 'None' ? field_value : '') - when 'select' - expect(matched_field.all('option').detect(&:selected?).text).to eq field_value - when 'radio must' - expect(matched_field.find("input[checked][type='radio']").value).to eq field_value - when '' - expect(matched_field.find('input,textarea').value).to eq field_value + when 'autocomplete' + expect(matched_field.find('input,textarea').value).to eq (if field_value != 'None' + field_value + else + '' + end) + when 'select' + expect(matched_field.all('option').detect(&:selected?).text).to eq field_value + when 'radio must' + expect(matched_field.find("input[checked][type='radio']").value).to eq field_value + when '' + expect(matched_field.find('input,textarea').value).to eq field_value end end end @@ -245,8 +257,9 @@ Then(/^all the packaged items receive these same values store to this package$/) do |table| table.hashes.each do |t| - b = @package.children.all? {|c| - case t[:field] + b = + @package.children.all? do |c| + case t[:field] when 'Responsible department' c.inventory_pool_id == @package.inventory_pool_id when 'Responsible person' @@ -261,15 +274,15 @@ c.last_check == @package.last_check else 'not found' + end end - } expect(b).to be true end end Then(/^I only see packages which I am responsible for$/) do within '#packages' do - dom_package_items = Item.find(all('.list-of-lines > .line').map{|x| x['data-id'] }) + dom_package_items = Item.find(all('.list-of-lines > .line').map { |x| x['data-id'] }) db_items = @model.items.where(inventory_pool_id: @current_inventory_pool) expect(dom_package_items).to eq db_items end diff --git a/features/step_definitions/manage/password_steps.rb b/features/step_definitions/manage/password_steps.rb index abacfe8cf7..60950be76d 100644 --- a/features/step_definitions/manage/password_steps.rb +++ b/features/step_definitions/manage/password_steps.rb @@ -2,12 +2,26 @@ def fill_in_user_information(attrs) selector = @current_inventory_pool ? '.row.emboss' : '.form-group' - find(selector, match: :prefer_exact, text: _('Last name')).find('input').set attrs[:firstname] if attrs[:lastname] - find(selector, match: :prefer_exact, text: _('First name')).find('input').set attrs[:firstname] if attrs[:firstname] - find(selector, match: :prefer_exact, text: _('E-Mail')).find('input').set attrs[:email] if attrs[:email] - find(selector, match: :prefer_exact, text: _('Login')).find('input').set attrs[:login] if attrs[:login] - find(selector, match: :prefer_exact, text: _('Password')).find('input').set attrs[:password] if attrs[:password] - find(selector, match: :prefer_exact, text: _('Password Confirmation')).find('input').set attrs[:password_confirmation] if attrs[:password_confirmation] + if attrs[:lastname] + find(selector, match: :prefer_exact, text: _('Last name')).find('input').set attrs[:firstname] + end + if attrs[:firstname] + find(selector, match: :prefer_exact, text: _('First name')).find('input').set attrs[:firstname] + end + if attrs[:email] + find(selector, match: :prefer_exact, text: _('E-Mail')).find('input').set attrs[:email] + end + if attrs[:login] + find(selector, match: :prefer_exact, text: _('Login')).find('input').set attrs[:login] + end + if attrs[:password] + find(selector, match: :prefer_exact, text: _('Password')).find('input').set attrs[:password] + end + if attrs[:password_confirmation] + find(selector, match: :prefer_exact, text: _('Password Confirmation')).find('input').set attrs[ + :password_confirmation + ] + end click_button _('Save') end @@ -22,14 +36,25 @@ def fill_in_user_information(attrs) When(/^I have created a user with login "(.*?)" and password "(.*?)"$/) do |login, password| step 'I add a user' - fill_in_user_information(firstname: 'test', lastname: 'test', email: 'test@test.ch', login: login, password: password, password_confirmation: password) + fill_in_user_information( + firstname: 'test', + lastname: 'test', + email: 'test@test.ch', + login: login, + password: password, + password_confirmation: password + ) expect(has_content?(_('List of Users'))).to be true @user = User.find_by_login login expect(DatabaseAuthentication.find_by_user_id(@user.id)).not_to be_nil end When(/^the user has access to an inventory pool$/) do - attributes = {user_id: @user.id, inventory_pool_id: @inventory_pool.try(:id) || InventoryPool.first.id, role: :customer} + attributes = { + user_id: @user.id, + inventory_pool_id: @inventory_pool.try(:id) || InventoryPool.first.id, + role: :customer + } AccessRight.create(attributes) unless AccessRight.where(attributes).first end @@ -37,8 +62,8 @@ def fill_in_user_information(attrs) @user ||= User.find_by_firstname(firstname) step 'I make sure I am logged out' visit login_path - step %Q{I fill in "username" with "#{@user.login}"} - step %Q{I fill in "password" with "#{password}"} + step "I fill in \"username\" with \"#{@user.login}\"" + step "I fill in \"password\" with \"#{password}\"" step 'I press "Login"' expect(has_content?(@user.short_name)).to be true end @@ -46,18 +71,22 @@ def fill_in_user_information(attrs) When(/^I change the password for user "(.*?)" to "(.*?)"$/) do |persona, password| fill_in_user_information(password: password, password_confirmation: password) expect(has_content?(_('List of Users'))).to be true - @user = User.find_by_login "#{User.find_by_login("normin").login}" + @user = User.find_by_login "#{User.find_by_login('normin').login}" expect(DatabaseAuthentication.find_by_user_id(@user.id)).not_to be_nil end Given(/^I am editing the user "(.*?)"$/) do |persona| - # This isn't really necessary since they exist anyhow when using the @personas tag #step 'personas existing' - @user = User.find_by_firstname persona + @user = + User.find_by_firstname persona if @current_user.is_admin visit admin.edit_user_path @user else - ip = @current_user.inventory_pools.managed.where('inventory_pools.id' => @user.inventory_pools.select('inventory_pools.id')).first + ip = + @current_user.inventory_pools.managed.where( + 'inventory_pools.id' => @user.inventory_pools.select('inventory_pools.id') + ) + .first visit manage_edit_inventory_pool_user_path(ip, @user) end end @@ -79,23 +108,42 @@ def fill_in_user_information(attrs) When(/^I try to create a user (.*)$/) do |arg1| step 'I add a user' case arg1 - when 'without username' - fill_in_user_information(firstname: 'test', lastname: 'test', email: 'test@test.ch', password: 'newpassword', password_confirmation: 'newpassword') - when 'without a password' - fill_in_user_information(firstname: 'test', lastname: 'test', email: 'test@test.ch', login: 'new_username') - when 'with a non-matching password confirmation' - fill_in_user_information(firstname: 'test', lastname: 'test', email: 'test@test.ch', login: 'new_username', password: 'newpassword', password_confirmation: 'wrongconfir') - else - raise + when 'without username' + fill_in_user_information( + firstname: 'test', + lastname: 'test', + email: 'test@test.ch', + password: 'newpassword', + password_confirmation: 'newpassword' + ) + when 'without a password' + fill_in_user_information( + firstname: 'test', lastname: 'test', email: 'test@test.ch', login: 'new_username' + ) + when 'with a non-matching password confirmation' + fill_in_user_information( + firstname: 'test', + lastname: 'test', + email: 'test@test.ch', + login: 'new_username', + password: 'newpassword', + password_confirmation: 'wrongconfir' + ) + else + raise end end When(/^I don't fill in a username and save$/) do - fill_in_user_information(login: 'a', password: 'newpassword', password_confirmation: 'newpassword') + fill_in_user_information( + login: 'a', password: 'newpassword', password_confirmation: 'newpassword' + ) end When(/^I fill in a wrong password confirmation and save$/) do - fill_in_user_information(login: 'newlogin', password: 'newpassword', password_confirmation: 'newpasswordxyz') + fill_in_user_information( + login: 'newlogin', password: 'newpassword', password_confirmation: 'newpasswordxyz' + ) end When(/^I don't complete the password information and save$/) do diff --git a/features/step_definitions/manage/picking_list_steps.rb b/features/step_definitions/manage/picking_list_steps.rb index 39aeb5dcbf..1df0bfbec9 100644 --- a/features/step_definitions/manage/picking_list_steps.rb +++ b/features/step_definitions/manage/picking_list_steps.rb @@ -4,13 +4,13 @@ step 'I close the flash message' within '#lines' do - @selected_lines = @current_inventory_pool.reservations.find all(".line input[type='checkbox']:checked").map { |x| x.find(:xpath, './../../../../..')['data-id'] } + @selected_lines = + @current_inventory_pool.reservations.find all(".line input[type='checkbox']:checked") + .map { |x| x.find(:xpath, './../../../../..')['data-id'] } end step 'I can open the picking list' - document_window = window_opened_by do - click_button _('Picking List') - end + document_window = window_opened_by { click_button _('Picking List') } page.driver.browser.switch_to.window(document_window.handle) @list_element = find('.picking_list') @@ -45,30 +45,33 @@ end within '#lines' do - @selected_lines = @current_inventory_pool.reservations.find all(".line input[type='checkbox']:checked").map { |x| x.find(:xpath, './../../../../..')['data-id'] } + @selected_lines = + @current_inventory_pool.reservations.find all(".line input[type='checkbox']:checked") + .map { |x| x.find(:xpath, './../../../../..')['data-id'] } end step 'I can open the picking list' - document_window = window_opened_by do - click_button _('Picking List') - end + document_window = window_opened_by { click_button _('Picking List') } page.driver.browser.switch_to.window(document_window.handle) @list_element = find('.picking_list') end -Then(/^I can open the (contract|picking list|value list) of any (order|contract) line$/) do |arg1, arg2| - s1 = case arg1 - when 'contract' - _('Contract') - when 'picking list' - _('Picking List') - when 'value list' - _('Value List') - else - raise - end +Then( + /^I can open the (contract|picking list|value list) of any (order|contract) line$/ +) do |arg1, arg2| + s1 = + case arg1 + when 'contract' + _('Contract') + when 'picking list' + _('Picking List') + when 'value list' + _('Value List') + else + raise + end current_role = @current_user.access_right_for(@current_inventory_pool).role @@ -92,16 +95,20 @@ end Then(/^the lists are sorted by (hand over|take back) date$/) do |arg1| - @s1, @s2 = case arg1 - when 'hand over' - ['start_date', _('Start date')] - when 'take back' - ['end_date', _('End date')] - else - raise - end + @s1, @s2 = + case arg1 + when 'hand over' + ['start_date', _('Start date')] + when 'take back' + ['end_date', _('End date')] + else + raise + end find("section.list table thead tr th.#{@s1}", match: :first) - dates = all("section.list table thead tr th.#{@s1}").map { |el| Date.parse el.text.gsub("#{@s2}: ", '') } + dates = + all("section.list table thead tr th.#{@s1}").map do |el| + Date.parse el.text.gsub("#{@s2}: ", '') + end expect(dates).to eq dates.sort end @@ -115,7 +122,11 @@ end end -Then(/^each list will sorted after (models, then sorted after )?room and shelf( of the most available locations)?$/) do |arg1, arg2| +Then( + / + ^each list will sorted after (models, then sorted after )?room and shelf( of the most available locations)?$ + / +) do |arg1, arg2| lines = @selected_lines || @contract.reservations expect(lines).not_to be_blank lines.group_by { |x| x.send @s1 }.each_key do |date| @@ -134,35 +145,60 @@ end Then(/^in the list, the assigned items will displayed with inventory code, room and shelf$/) do - @selected_lines.select { |line| line.item_id }.each do |line| - find('section.list .inventory_code', text: line.item.inventory_code).find(:xpath, './..').find('.location', text: '%s / %s' % [line.item.location.try(:room), line.item.location.try(:shelf)]) + @selected_lines.select(&:item_id).each do |line| + find('section.list .inventory_code', text: line.item.inventory_code).find(:xpath, './..').find( + '.location', text: '%s / %s' % [line.item.location.try(:room), line.item.location.try(:shelf)] + ) end end Then(/^in the list, the not assigned items will displayed without inventory code$/) do - @selected_lines.select { |line| not line.item_id and line.is_a? ItemLine }.each do |line| - expect(find('section.list .model_name', match: :prefer_exact, text: line.model.name).find(:xpath, './..').find('.inventory_code').text).to eq '' + @selected_lines.select { |line| nline.item_id and line.is_a? ItemLine }.each do |line| + expect( + find('section.list .model_name', match: :prefer_exact, text: line.model.name).find( + :xpath, './..' + ) + .find('.inventory_code') + .text + ).to eq '' end end - Then(/^I can open the picking list$/) do find('[data-selection-enabled]').find(:xpath, './following-sibling::*').click find('button', text: _('Picking List')) end -Then(/^the items without location, are displayed with (the available quantity for this customer and )?"(.*?)"$/) do |arg1, arg2| +Then( + / + ^the items without location, are displayed with (the available quantity for this customer and )?"(.*?)"$ + / +) do |arg1, arg2| lines = @selected_lines || @contract.reservations expect(lines).not_to be_blank lines.select { |line| line.is_a? ItemLine }.each do |line| if line.item_id - find('section.list .model_name', match: :prefer_exact, text: line.model.name).find(:xpath, './..').find('.location', text: arg2) + find('section.list .model_name', match: :prefer_exact, text: line.model.name).find( + :xpath, './..' + ) + .find('.location', text: arg2) else - locations = line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).select('COUNT(items.location_id) AS count, locations.room AS room, locations.shelf AS shelf').joins(:location).group('items.location_id', 'locations.room', 'locations.shelf').order('count DESC, room ASC, shelf ASC') + locations = + line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).select( + 'COUNT(items.location_id) AS count, locations.room AS room, locations.shelf AS shelf' + ) + .joins(:location) + .group('items.location_id', 'locations.room', 'locations.shelf') + .order('count DESC, room ASC, shelf ASC') locations.to_a.delete_if { |location| location.room.blank? and location.shelf.blank? } - not_defined_count = line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).count - locations.to_a.sum(&:count) + not_defined_count = + line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).count - + locations.to_a.sum(&:count) if not_defined_count > 0 - find('section.list .model_name', match: :prefer_exact, text: line.model.name).find(:xpath, './..').find('.location', text: arg2) + find('section.list .model_name', match: :prefer_exact, text: line.model.name).find( + :xpath, './..' + ) + .find('.location', text: arg2) end end end @@ -172,14 +208,20 @@ lines = @selected_lines || @contract.reservations expect(lines).not_to be_blank lines.select { |line| line.is_a? OptionLine }.each do |line| - find('section.list .model_name', match: :prefer_exact, text: line.model.name).find(:xpath, './..').find('.location', text: _(arg1)) + find('section.list .model_name', match: :prefer_exact, text: line.model.name).find( + :xpath, './..' + ) + .find('.location', text: _(arg1)) end end Then(/^the unavailable items are displayed with "(.*?)"$/) do |arg1| lines = @selected_lines || @contract.reservations expect(lines).not_to be_blank - lines.select { |line| not line.available? }.each do |line| - find('section.list .model_name', match: :prefer_exact, text: line.model.name).find(:xpath, './..').find('.location', text: arg1) + lines.select { |line| nline.available? }.each do |line| + find('section.list .model_name', match: :prefer_exact, text: line.model.name).find( + :xpath, './..' + ) + .find('.location', text: arg1) end end diff --git a/features/step_definitions/manage/pool_information_steps.rb b/features/step_definitions/manage/pool_information_steps.rb index d523386701..69da12837b 100644 --- a/features/step_definitions/manage/pool_information_steps.rb +++ b/features/step_definitions/manage/pool_information_steps.rb @@ -1,6 +1,5 @@ # encoding: utf-8 - #Wenn(/^ich den Admin\-Bereich betrete$/) do When(/^I navigate to the inventory pool manage section$/) do within '.topbar' do @@ -23,9 +22,7 @@ end end -When(/^I make a note of which page I'm on$/) do - @saved_path = current_path -end +When(/^I make a note of which page I'm on$/) { @saved_path = current_path } Then(/^the settings are updated$/) do @table_raw.flatten.each do |field_name| @@ -35,15 +32,17 @@ elsif field_name == 'Automatic access' expect(find('input', match: :first).selected?).to be true else - expect(find('input,textarea', match: :first).value).to eq (field_name == 'E-Mail' ? 'test@test.ch' : 'test') + expect(find('input,textarea', match: :first).value).to eq (if field_name == 'E-Mail' + 'test@test.ch' + else + 'test' + end) end end end end -Then(/^I am still on the same page$/) do - expect(current_path).to eq @saved_path -end +Then(/^I am still on the same page$/) { expect(current_path).to eq @saved_path } Then(/^I see a confirmation that the information was saved$/) do find('#flash .notice', text: _('Inventory pool successfully updated')) @@ -55,7 +54,9 @@ When(/^I leave the following fields empty:$/) do |table| table.raw.flatten.each do |must_field_name| - find('.row.emboss', match: :prefer_exact, text: must_field_name).find('input,textarea', match: :first).set '' + find('.row.emboss', match: :prefer_exact, text: must_field_name).find( + 'input,textarea', match: :first + ).set '' end end @@ -63,10 +64,17 @@ visit manage_edit_inventory_pool_path(@current_inventory_pool) end -When(/^I randomly set the workdays monday, tuesday, wednesday, thursday, friday, saturday and sunday to open or closed$/) do +When( + / + ^I randomly set the workdays monday, tuesday, wednesday, thursday, friday, saturday and sunday to open or closed$ + / +) do @workdays = {} - [0,1,2,3,4,5,6].each do |day| - select = find('.row.emboss', match: :prefer_exact, text: I18n.t('date.day_names')[day]).find('select', match: :first) + [0, 1, 2, 3, 4, 5, 6].each do |day| + select = + find('.row.emboss', match: :prefer_exact, text: I18n.t('date.day_names')[day]).find( + 'select', match: :first + ) @workdays[day] = rand > 0.5 ? _('Open') : _('Closed') select.find("option[label='#{@workdays[day]}']", match: :first).click end @@ -84,8 +92,8 @@ When(/^I set one or more time spans as holidays and give them names$/) do @holidays = [] - [1,5,8].each do |i| - holiday = {start_date: (Date.today + i), end_date: (Date.today + i*i), name: "Test #{i}"} + [1, 5, 8].each do |i| + holiday = { start_date: (Date.today + i), end_date: (Date.today + i * i), name: "Test #{i}" } @holidays.push holiday fill_in 'start_date', with: I18n.l(holiday[:start_date]) fill_in 'end_date', with: I18n.l(holiday[:end_date]) @@ -96,7 +104,12 @@ Then(/^the holidays are saved$/) do @holidays.each do |holiday| - expect(@current_inventory_pool.holidays.where(start_date: holiday[:start_date], end_date: holiday[:end_date], name: holiday[:name]).empty?).to be false + expect( + @current_inventory_pool.holidays.where( + start_date: holiday[:start_date], end_date: holiday[:end_date], name: holiday[:name] + ) + .empty? + ).to be false end end @@ -104,26 +117,25 @@ holiday = @holidays.last rescue_displaced_flash do within find('.row[data-holidays-list] .line', text: holiday[:name]) do - page.execute_script %[ $('.button[data-remove-holiday]').click() ] + page.execute_script " $('.button[data-remove-holiday]').click() " end step 'I save' end expect( - @current_inventory_pool - .reload - .holidays - .where(start_date: holiday[:start_date], - end_date: holiday[:end_date], - name: holiday[:name]) - .empty? - ) - .to be true + @current_inventory_pool.reload.holidays.where( + start_date: holiday[:start_date], end_date: holiday[:end_date], name: holiday[:name] + ) + .empty? + ).to be true end # there is nothing in the test that relates to required fields When(/^I fill in the following fields in the inventory pool settings:$/) do |table| table.raw.flatten.each do |field_name| - expect(find('.row.emboss', match: :prefer_exact, text: field_name).find('input', match: :first).value.length).to be > 0 + expect( + find('.row.emboss', match: :prefer_exact, text: field_name).find('input', match: :first).value + .length + ).to be > 0 end end @@ -143,16 +155,23 @@ Then(/^this configuration is saved$/) do expect(has_selector?('#flash .notice')).to be true @current_inventory_pool.reload - step %Q("Automatic suspension" is enabled) + step '"Automatic suspension" is enabled' expect(@current_inventory_pool.automatic_suspension_reason).to eq @reason end When(/^a user is suspended automatically due to late contracts$/) do - @user = Reservation.where(inventory_pool_id: @current_inventory_pool).signed.where('end_date < ?', Date.today).first.user + @user = + Reservation.where(inventory_pool_id: @current_inventory_pool).signed.where( + 'end_date < ?', Date.today + ) + .first + .user @user.automatic_suspend(@current_inventory_pool) end -Then(/^they are suspended for this inventory pool until '(\d+)\/(\d+)\/(\d+)'$/) do |day, month, year| +Then( + %r{^they are suspended for this inventory pool until '(\d+)\/(\d+)\/(\d+)'$} +) do |day, month, year| @access_right = @user.access_right_for(@current_inventory_pool) expect(@access_right.suspended_until).to eq Date.new(year.to_i, month.to_i, day.to_i) end @@ -177,11 +196,12 @@ if arg1 b = !arg2 @current_inventory_pool = @current_user.inventory_pools.managed.where(automatic_access: b).first - @current_inventory_pool ||= begin - ip = @current_user.inventory_pools.managed.first - ip.update_attributes(automatic_access: b) - ip - end + @current_inventory_pool ||= + begin + ip = @current_user.inventory_pools.managed.first + ip.update_attributes(automatic_access: b) + ip + end end visit manage_edit_inventory_pool_path(@current_inventory_pool) @last_edited_inventory_pool = @current_inventory_pool @@ -189,7 +209,11 @@ Given(/^there are( no)? users without access right to this inventory pool$/) do |arg1| b = !arg1 - expect(User.all.any?{|user| user.access_rights.find_by(inventory_pool_id: @current_inventory_pool).nil? }).to be b + expect( + User.all.any? do |user| + user.access_rights.find_by(inventory_pool_id: @current_inventory_pool).nil? + end + ).to be b end Given(/^multiple inventory pools are granting automatic access$/) do @@ -210,7 +234,7 @@ end When(/^I create a new user with the 'inventory manager' role in my inventory pool$/) do - steps %Q{ + steps ' When I am looking at the user list And I add a user And I enter the following information @@ -223,17 +247,27 @@ | tab | role | | Inventory manager | inventory_manager | And I save - } + ' @user = User.find_by_lastname 'test' end -Then(/^the newly created user has 'customer'-level access to all inventory pools that grant automatic access(, but not to mine)?$/) do |arg1| +Then( + / + ^the newly created user has 'customer'-level access to all inventory pools that grant automatic access(, but not to mine)?$ + / +) do |arg1| expect(@user.access_rights.count).to eq @inventory_pools_with_automatic_access.count - expect(@user.access_rights.pluck(:inventory_pool_id)).to match_array @inventory_pools_with_automatic_access.pluck(:id) + expect( + @user.access_rights.pluck(:inventory_pool_id) + ).to match_array @inventory_pools_with_automatic_access.pluck(:id) if arg1 - expect(@user.access_rights.where('inventory_pool_id != ?', @current_inventory_pool ).all? {|ar| ar.role == :customer}).to be true + expect( + @user.access_rights.where('inventory_pool_id != ?', @current_inventory_pool).all? do |ar| + ar.role == :customer + end + ).to be true else - expect(@user.access_rights.all? {|ar| ar.role == :customer}).to be true + expect(@user.access_rights.all? { |ar| ar.role == :customer }).to be true end end @@ -245,8 +279,12 @@ expect(@user.access_right_for(@last_edited_inventory_pool)).to eq nil end -When(/^on the inventory pool I enable the automatic suspension for users with overdue take backs$/) do - @current_inventory_pool.update_attributes(automatic_suspension: true, automatic_suspension_reason: Faker::Lorem.paragraph) +When( + /^on the inventory pool I enable the automatic suspension for users with overdue take backs$/ +) do + @current_inventory_pool.update_attributes( + automatic_suspension: true, automatic_suspension_reason: Faker::Lorem.paragraph + ) end When(/^a user is already suspended for this inventory pool$/) do @@ -257,7 +295,9 @@ ensure_suspended_user(@user, @current_inventory_pool, @suspended_until, @suspended_reason) end -Then(/^the existing suspension motivation and the suspended time for this user are not overwritten$/) do +Then( + /^the existing suspension motivation and the suspended time for this user are not overwritten$/ +) do def checks_suspension ar = @user.access_right_for(@current_inventory_pool) expect(ar.suspended_until).to eq @suspended_until @@ -271,56 +311,62 @@ def checks_suspension end When(/^I (enable|disable) "(.*)"$/) do |arg1, arg2| - b = case arg1 - when 'enable' - true - when 'disable' - false - else - raise - end - case arg2 - when 'Print contracts' - find("input[type='checkbox'][name='inventory_pool[print_contracts]']").set b - when 'Automatic suspension' - find("input[type='checkbox'][name='inventory_pool[automatic_suspension]']").set b - when 'Automatic access' - find("input[type='checkbox'][name='inventory_pool[automatic_access]']").set b + b = + case arg1 + when 'enable' + true + when 'disable' + false else raise + end + case arg2 + when 'Print contracts' + find("input[type='checkbox'][name='inventory_pool[print_contracts]']").set b + when 'Automatic suspension' + find("input[type='checkbox'][name='inventory_pool[automatic_suspension]']").set b + when 'Automatic access' + find("input[type='checkbox'][name='inventory_pool[automatic_access]']").set b + else + raise end end Then(/^"(.*)" is (enabled|disabled)$/) do |arg1, arg2| - b = case arg2 - when 'enabled' - true - when 'disabled' - false - else - raise - end - case arg1 - when 'Print contracts' - expect(@current_inventory_pool.reload.print_contracts).to eq b - when 'Automatic suspension' - expect(@current_inventory_pool.reload.automatic_suspension).to eq b - when 'Automatic access' - expect(@current_inventory_pool.reload.automatic_access).to eq b + b = + case arg2 + when 'enabled' + true + when 'disabled' + false else raise + end + case arg1 + when 'Print contracts' + expect(@current_inventory_pool.reload.print_contracts).to eq b + when 'Automatic suspension' + expect(@current_inventory_pool.reload.automatic_suspension).to eq b + when 'Automatic access' + expect(@current_inventory_pool.reload.automatic_access).to eq b + else + raise end end Then(/^I can change the field "(.*?)"$/) do |arg1| case arg1 - when 'Min. number of days between order and hand over' - n = rand(0..14) - find("input[type='number'][name='inventory_pool[workday_attributes][reservation_advance_days]']").set n - step 'I save' - find("input[type='number'][name='inventory_pool[workday_attributes][reservation_advance_days]'][value='#{n}']") - else - raise + when 'Min. number of days between order and hand over' + n = rand(0..14) + find( + "input[type='number'][name='inventory_pool[workday_attributes][reservation_advance_days]']" + ).set n + step 'I save' + find( + "input[type='number'][name='inventory_pool[workday_attributes][reservation_advance_days]'][value='#{n}']" + ) + else + raise end end @@ -328,23 +374,36 @@ def checks_suspension h = {} (0..6).each do |i| h[i] = rand(0..14) - find("input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]']").set h[i] + find( + "input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]']" + ).set h[i] end step 'I save' (0..6).each do |i| - find("input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]'][value='#{h[i]}']") + find( + "input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]'][value='#{h[ + i + ]}']" + ) end end When(/^I do not enter a maximum amount of visits on a week day$/) do (0..6).each do |i| - find("input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]']").set '' + find( + "input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]']" + ).set '' end step 'I save' end Then(/^there is no limit of visits for this week day$/) do (0..6).each do |i| - expect(find("input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]']").value).to be_blank + expect( + find( + "input[type='number'][name='inventory_pool[workday_attributes][workdays][#{i}][max_visits]']" + ) + .value + ).to be_blank end end diff --git a/features/step_definitions/manage/problems_steps.rb b/features/step_definitions/manage/problems_steps.rb index d944285338..9553dfdf2f 100644 --- a/features/step_definitions/manage/problems_steps.rb +++ b/features/step_definitions/manage/problems_steps.rb @@ -1,6 +1,5 @@ # encoding: utf-8 - Given /^I am doing a take back( that is not overdue)?$/ do |arg1| @event = 'take_back' if arg1 @@ -11,30 +10,43 @@ end Given /^a model is no longer available$/ do - if @event=='order' or @event=='hand_over' - @entity = @contract || @order || - begin - item = FactoryGirl.create(:item, - inventory_pool: @current_inventory_pool) - reservation = FactoryGirl.create(:item_line, :with_purpose, - user: @customer, - item: item, - model: item.model, - inventory_pool: @current_inventory_pool, - status: :approved) - reservation.order - end + if @event == 'order' or @event == 'hand_over' + @entity = + @contract || @order || + begin + item = FactoryGirl.create(:item, inventory_pool: @current_inventory_pool) + reservation = + FactoryGirl.create( + :item_line, + :with_purpose, + user: @customer, + item: item, + model: item.model, + inventory_pool: @current_inventory_pool, + status: :approved + ) + reservation.order + end reservation ||= @entity.item_lines.first expect(reservation).to be @model = reservation.model @initial_quantity = @entity.reservations.where(model_id: @model.id).count - @max_before = reservation.model.availability_in(@entity.inventory_pool).maximum_available_in_period_summed_for_groups(reservation.start_date, reservation.end_date, reservation.entitlement_group_ids) || 0 + @max_before = + reservation.model.availability_in(@entity.inventory_pool) + .maximum_available_in_period_summed_for_groups( + reservation.start_date, reservation.end_date, reservation.entitlement_group_ids + ) || + 0 step 'I add so many reservations that I break the maximal quantity of a model' else reservation = @reservations_to_take_back.where(option_id: nil).first @model = reservation.model step 'I open a hand over to this customer' - @max_before = @model.availability_in(@current_inventory_pool).maximum_available_in_period_summed_for_groups(reservation.start_date, reservation.end_date, reservation.entitlement_group_ids) || 0 + @max_before = + @model.availability_in(@current_inventory_pool).maximum_available_in_period_summed_for_groups( + reservation.start_date, reservation.end_date, reservation.entitlement_group_ids + ) || + 0 step 'I add so many reservations that I break the maximal quantity of a model' visit manage_take_back_path(@current_inventory_pool, @customer) end @@ -52,47 +64,63 @@ end @reference_line = @lines.first @reference_problem = @problems.first - @line = if @reference_line['data-id'] - Reservation.find @reference_line['data-id'] - else - Reservation.find JSON.parse(@reference_line['data-ids']).first - end + @line = + if @reference_line['data-id'] + Reservation.find @reference_line['data-id'] + else + Reservation.find JSON.parse(@reference_line['data-ids']).first + end @av = @line.model.availability_in(@line.inventory_pool) end Then /^the problem is displayed as: "(.*?)"$/ do |format| - regexp = if format == 'Nicht verfügbar 2(3)/7' - /#{_("Not available")} -*\d\(-*\d\)\/\d/ - elsif format == 'Gegenstand nicht ausleihbar' - /#{_("Item not borrowable")}/ - elsif format == 'Gegenstand ist defekt' - /#{_("Item is defective")}/ - elsif format == 'Gegenstand ist unvollständig' - /#{_("Item is incomplete")}/ - elsif format == 'Überfällig seit 6 Tagen' - /(Überfällig seit \d+ (Tagen|Tag)|#{_("Overdue")} #{_("since")} \d+ (days|day))/ - end - @problems.each do |problem| - expect(problem.match(regexp)).not_to be_nil - end + regexp = + if format == 'Nicht verfügbar 2(3)/7' + %r{#{_('Not available')} -*\d\(-*\d\)\/\d} + elsif format == 'Gegenstand nicht ausleihbar' + /#{_('Item not borrowable')}/ + elsif format == 'Gegenstand ist defekt' + /#{_('Item is defective')}/ + elsif format == 'Gegenstand ist unvollständig' + /#{_('Item is incomplete')}/ + elsif format == 'Überfällig seit 6 Tagen' + /(Überfällig seit \d+ (Tagen|Tag)|#{_('Overdue')} #{_('since')} \d+ (days|day))/ + end + @problems.each { |problem| expect(problem.match(regexp)).not_to be_nil } end -Then /^"(.*?)" are available for the user, also counting availability from groups the user is member of$/ do |arg1| - max = if [:unsubmitted, :submitted].include? @line.status - @initial_quantity + @max_before - elsif [:approved, :signed].include? @line.status - (@av.maximum_available_in_period_summed_for_groups(@line.start_date, @line.end_date, @line.entitlement_group_ids) || 0) \ - + 1 # free up self blocking - else - @max_before - @quantity_added - end +Then / + ^"(.*?)" are available for the user, also counting availability from groups the user is member of$ + / do |arg1| + max = + if [:unsubmitted, :submitted].include? @line.status + @initial_quantity + @max_before + elsif [:approved, :signed].include? @line.status + (@av.maximum_available_in_period_summed_for_groups( + @line.start_date, @line.end_date, @line.entitlement_group_ids + ) || + 0) + # free up self blocking + 1 + else + @max_before - @quantity_added + end expect(@reference_problem).to match /#{max}\(/ end -Then /^"(.*?)" are available in total, also counting availability from groups the user is not member of$/ do |arg1| - max = @av.maximum_available_in_period_summed_for_groups(@line.start_date, @line.end_date, @av.inventory_pool_and_model_group_ids) || 0 +Then / + ^"(.*?)" are available in total, also counting availability from groups the user is not member of$ + / do |arg1| + max = + @av.maximum_available_in_period_summed_for_groups( + @line.start_date, @line.end_date, @av.inventory_pool_and_model_group_ids + ) || + 0 if [:unsubmitted, :submitted].include? @line.status - max += (@line.contract or @line.order).reservations.where(start_date: @line.start_date, end_date: @line.end_date, model_id: @line.model).size + max += + (@line.contract or @line.order).reservations.where( + start_date: @line.start_date, end_date: @line.end_date, model_id: @line.model + ) + .size else max += @line.quantity end @@ -100,21 +128,25 @@ end Then /^"(.*?)" are in this inventory pool \(and borrowable\)$/ do |arg1| - expect(@reference_problem).to match("/#{@line.model.items.where(inventory_pool_id: @line.inventory_pool).borrowable.size}") + expect(@reference_problem).to match( + "/#{@line.model.items.where(inventory_pool_id: @line.inventory_pool).borrowable.size}" + ) end Given /^one item is not borrowable$/ do case @event - when 'hand_over' - @item = FactoryGirl.create(:item, is_borrowable: false, inventory_pool: @current_inventory_pool) - step 'I add an item to the hand over' - @line_id = Reservation.where(item_id: @item.id).first.id - find(".line[data-id='#{@line_id}']", text: @item.model.name).find('[data-assign-item][disabled]') - when 'take_back' - @line_id = find(".line[data-line-type='item_line']", match: :first)[:"data-id"] - step 'I mark the item as not borrowable' - else - raise + when 'hand_over' + @item = FactoryGirl.create(:item, is_borrowable: false, inventory_pool: @current_inventory_pool) + step 'I add an item to the hand over' + @line_id = Reservation.where(item_id: @item.id).first.id + find(".line[data-id='#{@line_id}']", text: @item.model.name).find( + '[data-assign-item][disabled]' + ) + when 'take_back' + @line_id = find(".line[data-line-type='item_line']", match: :first)[:"data-id"] + step 'I mark the item as not borrowable' + else + raise end end @@ -123,19 +155,18 @@ user = FactoryGirl.create(:user) FactoryGirl.create(:access_right, inventory_pool: @current_inventory_pool, user: user) item = FactoryGirl.create(:item) - item_line = FactoryGirl.create(:item_line, - item: item, - model: item.model, - contract: FactoryGirl.create(:open_contract, - inventory_pool: @current_inventory_pool, - user: user), - user: user, - status: :signed, - inventory_pool: @current_inventory_pool) - if is_late - item_line.update_attributes(start_date: Date.today - 2, - end_date: Date.today - 1) - end + item_line = + FactoryGirl.create( + :item_line, + item: item, + model: item.model, + contract: + FactoryGirl.create(:open_contract, inventory_pool: @current_inventory_pool, user: user), + user: user, + status: :signed, + inventory_pool: @current_inventory_pool + ) + item_line.update_attributes(start_date: Date.today - 2, end_date: Date.today - 1) if is_late sleep 2 @line_id = item_line.id expect(@line_id).to be @@ -148,7 +179,7 @@ def open_inspection_for_line(line_id) sleep 1 multibutton_css = ".line[data-id='#{line_id}'] .multibutton" sleep 1 - page.execute_script %Q( $("#{multibutton_css} .dropdown-toggle").trigger("mouseover") ) + page.execute_script " $(\"#{multibutton_css} .dropdown-toggle\").trigger(\"mouseover\") " sleep 1 find("#{multibutton_css} .dropdown-holder .dropdown-item", text: _('Inspect')).click sleep 1 @@ -158,14 +189,14 @@ def open_inspection_for_line(line_id) Then /^I mark the item as (.*)$/ do |arg1| open_inspection_for_line(@line_id) case arg1 - when 'not borrowable' - find("select[name='is_borrowable']").select 'Unborrowable' - when 'defective' - find("select[name='is_broken']").select 'Defective' - when 'incomplete' - find("select[name='is_incomplete']").select 'Incomplete' - else - raise + when 'not borrowable' + find("select[name='is_borrowable']").select 'Unborrowable' + when 'defective' + find("select[name='is_broken']").select 'Defective' + when 'incomplete' + find("select[name='is_incomplete']").select 'Incomplete' + else + raise end wait_until do first(".modal button[type='submit']").try(:click) @@ -175,38 +206,40 @@ def open_inspection_for_line(line_id) When /^one item is defective$/ do case @event - when 'hand_over' - @item = FactoryGirl.create(:item, is_broken: true, inventory_pool: @current_inventory_pool) - step 'I add an item to the hand over' - sleep 1 - wait_until do - @line_id = find("input[value='#{@item.inventory_code}']").find(:xpath, 'ancestor::div[@data-id]')['data-id'] - end - when 'take_back' - wait_until do - @line_id = find(".line[data-line-type='item_line']", match: :first)['data-id'] - end - step 'I mark the item as defective' - else - raise + when 'hand_over' + @item = FactoryGirl.create(:item, is_broken: true, inventory_pool: @current_inventory_pool) + step 'I add an item to the hand over' + sleep 1 + wait_until do + @line_id = + find("input[value='#{@item.inventory_code}']").find(:xpath, 'ancestor::div[@data-id]')[ + 'data-id' + ] + end + when 'take_back' + wait_until { @line_id = find(".line[data-line-type='item_line']", match: :first)['data-id'] } + step 'I mark the item as defective' + else + raise end end Given /^one item is incomplete$/ do case @event - when 'hand_over' - @item = FactoryGirl.create(:item, is_incomplete: true, inventory_pool: @current_inventory_pool) - step 'I add an item to the hand over' - wait_until do - @line_id = find("input[value='#{@item.inventory_code}']").find(:xpath, 'ancestor::div[@data-id]')['data-id'] - end - when 'take_back' - wait_until do - @line_id = find(".line[data-line-type='item_line']", match: :first)['data-id'] - end - step 'I mark the item as incomplete' - else - raise + when 'hand_over' + @item = FactoryGirl.create(:item, is_incomplete: true, inventory_pool: @current_inventory_pool) + step 'I add an item to the hand over' + wait_until do + @line_id = + find("input[value='#{@item.inventory_code}']").find(:xpath, 'ancestor::div[@data-id]')[ + 'data-id' + ] + end + when 'take_back' + wait_until { @line_id = find(".line[data-line-type='item_line']", match: :first)['data-id'] } + step 'I mark the item as incomplete' + else + raise end end @@ -214,7 +247,7 @@ def open_inspection_for_line(line_id) @line = @model.reservations.last @av = @model.availability_in(@line.inventory_pool) line = all(".line[data-id='#{@line.id}']", minimum: 1, text: @model.name).last - hover_for_tooltip line.find(".emboss.red") + hover_for_tooltip line.find('.emboss.red') @problems = [] @problems << find('.tooltipster-default .tooltipster-content', text: /\w/).text @reference_problem = @problems.first @@ -222,7 +255,7 @@ def open_inspection_for_line(line_id) Then /^the affected item's line shows the item's problems$/ do # close the flash which may be covering the element on Cider - first("#flash .fa-times-circle").try(&:click) + first('#flash .fa-times-circle').try(&:click) ### target = find(".line[data-id='#{@line_id}'] .emboss.red") hover_for_tooltip target @@ -233,10 +266,9 @@ def open_inspection_for_line(line_id) Given(/^test data setup XXX$/) do @event = 'hand_over' @customer = FactoryGirl.create(:user) - FactoryGirl.create(:access_right, - inventory_pool: @current_inventory_pool, - user: @customer, - role: :customer) + FactoryGirl.create( + :access_right, inventory_pool: @current_inventory_pool, user: @customer, role: :customer + ) end Given(/^I open a hand over XXX$/) do diff --git a/features/step_definitions/manage/purpose_steps.rb b/features/step_definitions/manage/purpose_steps.rb index 26d850e588..4ff3bb08d2 100644 --- a/features/step_definitions/manage/purpose_steps.rb +++ b/features/step_definitions/manage/purpose_steps.rb @@ -7,9 +7,7 @@ When /^each entry of a submitted order refers to a purpose$/ do reservations = rand(3..6).times.map { FactoryGirl.create :reservation, status: :submitted } - reservations.each do |line| - expect(line.purpose.is_a?(Purpose)).to be true - end + reservations.each { |line| expect(line.purpose.is_a?(Purpose)).to be true } end When /^each entry of an order can refer to a purpose$/ do @@ -20,7 +18,6 @@ end end - Then /^I see the purpose$/ do expect(has_content?(@order.purpose)).to be true end @@ -56,7 +53,7 @@ Then /^I am told during hand over to assign a purpose$/ do find('.multibutton .button[data-hand-over-selection]').click within '.modal' do - find('#purpose-input', text: _("Please provide a purpose...")).find('#purpose') + find('#purpose-input', text: _('Please provide a purpose...')).find('#purpose') end end @@ -69,25 +66,24 @@ end Given(/^the current inventory pool (requires|doesn't require) purpose$/) do |arg1| - b = case arg1 - when "requires" - true - else - false - end + b = + case arg1 + when 'requires' + true + else + false + end @current_inventory_pool.update_attributes(required_purpose: b) end Then /^I do not assign a purpose$/ do - within '.modal' do - expect(find('#purpose').text).to be_empty - end + within '.modal' doexpect(find('#purpose').text).to be_emptyend end Then /^I can finish the hand over$/ do signed_contracts_size = @customer.contracts.open.to_a.size # NOTE count returns a Hash because the group() in default scope step 'I click hand over inside the dialog' - expect(@customer.contracts.open.to_a.size).to be > signed_contracts_size # NOTE count returns a Hash because the group() in default scope + expect(@customer.contracts.open.to_a.size).to be > signed_contracts_size end Then /^I don't have to assign a purpose in order to finish the hand over$/ do @@ -109,12 +105,13 @@ find('#add-purpose').click @added_purpose = 'Another Purpose' find('#purpose').set @added_purpose - @approved_lines = @customer.orders.approved.find_by(inventory_pool_id: @current_inventory_pool).reservations + @approved_lines = + @customer.orders.approved.find_by(inventory_pool_id: @current_inventory_pool).reservations step 'I can finish the hand over' end Then /^only items without purpose are assigned that purpose$/ do - @approved_lines.select{|l| l.purpose.blank?}.each do |line| + @approved_lines.select { |l| l.purpose.blank? }.each do |line| expect(line.purpose.description).to eq @added_purpose end end @@ -124,10 +121,12 @@ reservations = @contract.reservations reservations.each do |line| @item_line = line + begin step 'I select one of those' - rescue + # if we ran out of available items, and an Capybara::Element not found exception was raised, just ensure that all the selected and assigned contract reservations so far, have a purpose + rescue StandardError expect(reservations.reload.select(&:item).all?(&:purpose)).to be true break end @@ -138,7 +137,7 @@ step 'I select all reservations selecting all linegroups' end # ensure that only reservations with assigned items are selected before continuing with the test - reservations.reload.select{|l| !l.item}.each do |l| + reservations.reload.select { |l| !l.item }.each do |l| cb = find(".line[data-id='#{l.id}'] input[type='checkbox']") cb.click if cb.checked? end @@ -149,14 +148,16 @@ step 'the booking calendar is closed' within '#lines' do - reservations = reservations.select {|line| line.item and find(".line[data-id='#{line.id}'] input[type='checkbox'][data-select-line]").checked? } + reservations = + reservations.select do |line| + line.item and + find(".line[data-id='#{line.id}'] input[type='checkbox'][data-select-line]").checked? + end end find('.multibutton .button[data-hand-over-selection]').click within('.modal') do - reservations.each do |line| - find('.row', match: :first, text: line.purpose.to_s) - end + reservations.each { |line| find('.row', match: :first, text: line.purpose.to_s) } end end @@ -164,9 +165,7 @@ expect(has_no_selector?('.modal .purpose button', visible: true)).to be true end -When(/^I click on hand over$/) do - find('[data-hand-over-selection]').click -end +When(/^I click on hand over$/) { find('[data-hand-over-selection]').click } When(/^I add a purpose$/) do within '.modal' do @@ -177,9 +176,7 @@ end When(/^I finish the hand over$/) do - @contract_window = window_opened_by do - find('.modal [data-hand-over]').click - end + @contract_window = window_opened_by { find('.modal [data-hand-over]').click } end Then(/^the contract has the original plus the added purpose$/) do @@ -193,11 +190,13 @@ Then(/^there is an approved and assigned reservation with purpose for a customer$/) do @customer = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) @purpose = Faker::Lorem.sentence - @reservation = FactoryGirl.create(:item_line, :with_assigned_item, :with_purpose, - purpose: @purpose, - user: @customer, - inventory_pool: @current_inventory_pool, - status: :approved) + @reservation = + FactoryGirl.create( + :item_line, + :with_assigned_item, + :with_purpose, + purpose: @purpose, user: @customer, inventory_pool: @current_inventory_pool, status: :approved + ) end Then(/^I open the hand over page for this customer$/) do @@ -210,11 +209,16 @@ Given(/^there is another approved and assigned reservation with purpose for a customer$/) do @another_purpose = Faker::Lorem.sentence - @another_reservation = FactoryGirl.create(:item_line, :with_assigned_item, :with_purpose, - purpose: @another_purpose, - user: @customer, - inventory_pool: @current_inventory_pool, - status: :approved) + @another_reservation = + FactoryGirl.create( + :item_line, + :with_assigned_item, + :with_purpose, + purpose: @another_purpose, + user: @customer, + inventory_pool: @current_inventory_pool, + status: :approved + ) end Then(/^the contract has both the purposes$/) do @@ -224,4 +228,3 @@ expect(current_scope).to have_content @another_purpose end end - diff --git a/features/step_definitions/manage/retire_item_steps.rb b/features/step_definitions/manage/retire_item_steps.rb index 7edefb939e..937e770910 100644 --- a/features/step_definitions/manage/retire_item_steps.rb +++ b/features/step_definitions/manage/retire_item_steps.rb @@ -2,24 +2,31 @@ def get_scope(item_type) case item_type - when 'item' then :items - when 'license' then :licenses + when 'item' + :items + when 'license' + :licenses end end - Given(/^I pick a (license|item) that is in stock$/) do |item_type| - @item = Item.send(get_scope item_type).where(inventory_pool_id: @current_inventory_pool.id).detect {|i| not i.retired? and i.is_borrowable? and i.in_stock?} + @item = + Item.send(get_scope item_type).where(inventory_pool_id: @current_inventory_pool.id) + .detect { |i| ni.retired? and i.is_borrowable? and i.in_stock? } step "I go to this %s's edit page" % item_type end - -Given(/^I pick a (license|item) that is in stock and that the current inventory pool is the owner of$/) do |item_type| - @item = Item.send(get_scope item_type).where(inventory_pool_id: @current_inventory_pool.id).detect {|i| not i.retired? and i.is_borrowable? and i.in_stock? and i.owner_id == @current_inventory_pool.id} +Given( + /^I pick a (license|item) that is in stock and that the current inventory pool is the owner of$/ +) do |item_type| + @item = + Item.send(get_scope item_type).where(inventory_pool_id: @current_inventory_pool.id) + .detect do |i| + ni.retired? and i.is_borrowable? and i.in_stock? and i.owner_id == @current_inventory_pool.id + end step format("I go to this %s's edit page", item_type) end - Then(/^I can retire this (?:.*) if I give a reason for retiring$/) do field = find("[data-type='field']", text: _('Retirement')) field.find("option[value='true']").select_option @@ -32,7 +39,6 @@ def get_scope(item_type) expect(@item.retired_reason).to eq 'test' end - Then(/^I cannot retire such a (?:item|license)$/) do field = find("[data-type='field']", text: _('Retirement')) if field[:"data-editable"] == 'true' @@ -46,28 +52,24 @@ def get_scope(item_type) expect(@item.retired).to eq nil end - Then(/^the newly retired (?:item|license) immediately disappears from the inventory list$/) do expect(has_no_content?(@item.inventory_code)).to be true end - Given(/^I pick a (item|license) that is not in stock$/) do |item_type| - @item = Item.send(get_scope item_type) - .where(inventory_pool_id: @current_inventory_pool.id) - .detect { |i| !(i.retired? || i.in_stock?) } + @item = + Item.send(get_scope item_type).where(inventory_pool_id: @current_inventory_pool.id) + .detect { |i| !(i.retired? || i.in_stock?) } step format("I go to this %s's edit page", item_type) end - Given(/^I pick a (.*) the current inventory pool is not the owner of$/) do |item_type| - @item = Item.send(get_scope item_type) - .where(inventory_pool_id: @current_inventory_pool.id) - .detect { |i| i.in_stock? && i.owner_id != @current_inventory_pool.id } + @item = + Item.send(get_scope item_type).where(inventory_pool_id: @current_inventory_pool.id) + .detect { |i| i.in_stock? && i.owner_id != @current_inventory_pool.id } step format("I go to this %s's edit page", item_type) end - Given(/^I don't give any reason for retiring this item$/) do field = find("[data-type='field']", text: _('Retirement')) field.find("option[value='true']").select_option @@ -77,43 +79,43 @@ def get_scope(item_type) step 'I see an error message' end - -Then(/^the (?:.*) is not retired$/) do - expect(@item.reload.retired).to eq nil -end - - +Then(/^the (?:.*) is not retired$/) { expect(@item.reload.retired).to eq nil } Given(/^I pick a retired (.*) that the current inventory pool is the owner of$/) do |item_type| - @item = Item.unscoped.send(get_scope item_type) - .find { |i| i.retired? && i.owner_id == @current_inventory_pool.id } + @item = + Item.unscoped.send(get_scope item_type).find do |i| + i.retired? && i.owner_id == @current_inventory_pool.id + end end - When(/^I unretire this (?:.*)$/) do expect(has_content?(_('Retirement'))).to be true find("[name='item[retired]']").select _('No') end - Then(/^I am redirected to the inventory list$/) do find('h1', text: _('List of Inventory')) find('#inventory .row', match: :first) expect(current_path).to eq manage_inventory_path(@current_inventory_pool) end - -Then(/^this (?:.*) is not retired$/) do - expect(@item.reload.retired?).to be false -end - +Then(/^this (?:.*) is not retired$/) { expect(@item.reload.retired?).to be false } And(/^I fill in the supply category$/) do - find('.row.emboss', match: :prefer_exact, text: 'Supply Category') - .find("select option:not([value=''])", match: :first) - .select_option if @item.type == 'Item' + if @item.type == 'Item' + find('.row.emboss', match: :prefer_exact, text: 'Supply Category').find( + "select option:not([value=''])", match: :first + ) + .select_option + end end -Given(/^I pick a retired (.*) that the current inventory pool is responsible for but not the owner of$/) do |item_type| - @item = Item.unscoped.send(get_scope item_type).find {|i| i.retired? and i.owner != @current_inventory_pool and i.inventory_pool == @current_inventory_pool} +Given( + /^I pick a retired (.*) that the current inventory pool is responsible for but not the owner of$/ +) do |item_type| + @item = + Item.unscoped.send(get_scope item_type).find do |i| + i.retired? and i.owner != @current_inventory_pool and + i.inventory_pool == @current_inventory_pool + end end diff --git a/features/step_definitions/manage/search_steps.rb b/features/step_definitions/manage/search_steps.rb index 201a0958dc..069aa6bb70 100644 --- a/features/step_definitions/manage/search_steps.rb +++ b/features/step_definitions/manage/search_steps.rb @@ -6,37 +6,47 @@ end Then /^I see the contract this item is assigned to in the list of results$/ do - expect(@current_user.inventory_pools.first.contracts.joins(:reservations).search(@item.inventory_code)).to include @contract + expect( + @current_user.inventory_pools.first.contracts.joins(:reservations).search(@item.inventory_code) + ).to include @contract end Given(/^there is a user with contracts who no longer has access to the current inventory pool$/) do - @user = User.find {|u| u.access_rights.find {|ar| ar.inventory_pool == @current_inventory_pool and ar.deleted_at} and !u.contracts.blank?} + @user = + User.find do |u| + u.access_rights.find do |ar| + ar.inventory_pool == @current_inventory_pool and ar.deleted_at + end and + !u.contracts.blank? + end expect(@user).not_to be_nil end Then(/^I see all that user's contracts$/) do - @user.contracts.each {|c| find("#contracts .line[data-id='#{c.id}']") } + @user.contracts.each { |c| find("#contracts .line[data-id='#{c.id}']") } end Then(/^I see that user's signed and closed contracts$/) do - @user.contracts.where(inventory_pool: @current_inventory_pool).each {|c| find("#contracts .line[data-id='#{c.id}']") } + @user.contracts.where(inventory_pool: @current_inventory_pool).each do |c| + find("#contracts .line[data-id='#{c.id}']") + end end Then(/^the name of that user is shown on each contract line$/) do - within '#contracts' do - all('.line').each {|el| el.text.include? @user.name } - end + within '#contracts' doall('.line').each { |el| el.text.include? @user.name }end end Then(/^that user's personal details are shown in the tooltip$/) do hover_for_tooltip find("#contracts [data-type='user-cell']", match: :first) within '.tooltipster-base' do - [@user.name, @user.email, @user.address, @user.phone, @user.badge_id].each {|info| has_content? info} + [@user.name, @user.email, @user.address, @user.phone, @user.badge_id].each do |info| + has_content? info + end end end Given(/^there is a user with an unapproved order$/) do - @user = @current_inventory_pool.users.find {|u| u.orders.submitted.exists? } + @user = @current_inventory_pool.users.find { |u| u.orders.submitted.exists? } end When(/^I search for that user$/) do @@ -49,13 +59,17 @@ Then(/^I cannot hand over the unapproved order unless I approve it first$/) do contract = @user.orders.submitted.first line = find(".line[data-id='#{contract.id}']") - expect(line.find('.multibutton').has_no_selector?('li', text: _('Hand Over'), visible: false)).to be true + expect( + line.find('.multibutton').has_no_selector?('li', text: _('Hand Over'), visible: false) + ).to be true end Given(/^there is a user with at least (\d+) and less than (\d+) contracts$/) do |min, max| - @user = @current_inventory_pool.users.find do |u| - u.contracts.where(inventory_pool: @current_inventory_pool).to_a.size.between? min.to_i, max.to_i # NOTE count returns a Hash because the group() in default scope - end + @user = + @current_inventory_pool.users.find do |u| + u.contracts.where(inventory_pool: @current_inventory_pool).to_a.size.between? min.to_i, + max.to_i # NOTE count returns a Hash because the group() in default scope + end expect(@user).not_to be_nil end @@ -65,16 +79,17 @@ Given(/^there is a "(.*?)" item in my inventory pool$/) do |arg1| items = @current_inventory_pool.items.items - @item = case arg1 - when 'Broken' - items.find &:is_broken - when 'Retired' - items.find &:retired - when 'Incomplete' - items.find &:is_incomplete - when 'Unborrowable' - items.find {|i| not i.is_borrowable} - end + @item = + case arg1 + when 'Broken' + items.find &:is_broken + when 'Retired' + items.find &:retired + when 'Incomplete' + items.find &:is_incomplete + when 'Unborrowable' + items.find { |i| ni.is_borrowable } + end expect(@item).not_to be_nil expect(@item.type).to be == 'Item' end @@ -91,16 +106,11 @@ end Given(/^there exists a closed contract with a retired item$/) do - @contract = @current_inventory_pool.contracts.closed.find do |c| - @item = c.items.find &:retired - end + @contract = @current_inventory_pool.contracts.closed.find { |c| @item = c.items.find &:retired } expect(@contract).not_to be_nil end - -Then(/^I see the item in the items area$/) do - find('#items .line', text: @item.inventory_code) -end +Then(/^I see the item in the items area$/) { find('#items .line', text: @item.inventory_code) } Then(/^I hover over the list of (?:items|licenses) on the contract line$/) do find("#contracts .line [data-type='lines-cell']", match: :first).hover @@ -110,38 +120,51 @@ find('.tooltipster-base', text: @item.model.name) end -Given(/^there exists a closed contract with an item, for which an other inventory pool is responsible and owner$/) do - @contract = @current_inventory_pool.contracts.closed.find do |c| - @item = c.items.find {|i| i.inventory_pool != @current_inventory_pool and i.owner != @current_inventory_pool } - end +Given( + / + ^there exists a closed contract with an item, for which an other inventory pool is responsible and owner$ + / +) do + @contract = + @current_inventory_pool.contracts.closed.find do |c| + @item = + c.items.find do |i| + i.inventory_pool != @current_inventory_pool and i.owner != @current_inventory_pool + end + end expect(@contract).not_to be_nil end -Given(/^there exists a closed contract with a license, for which an other inventory pool is responsible and owner$/) do +Given( + / + ^there exists a closed contract with a license, for which an other inventory pool is responsible and owner$ + / +) do @contract = FactoryGirl.create(:closed_contract, inventory_pool: @current_inventory_pool) software = FactoryGirl.create(:model_with_items, type: 'Software') @item = software.items.licenses.first - FactoryGirl.create(:item_line, - model: software, - user: @contract.user, - item: @item, - status: :closed, - contract: @contract, - inventory_pool: @current_inventory_pool) + FactoryGirl.create( + :item_line, + model: software, + user: @contract.user, + item: @item, + status: :closed, + contract: @contract, + inventory_pool: @current_inventory_pool + ) @contract.reload end -Then(/^I do not see the items container$/) do - expect(page).to have_no_selector '#items' -end +Then(/^I do not see the items container$/) { expect(page).to have_no_selector '#items' } Given(/^enough data for "(.*?)" having "(.*?)" exists$/) do |subsection, search_string| amount = 25 @results = [] - make_string = proc { "#{Faker::Lorem.characters(8)} #{search_string} #{Faker::Lorem.characters(8)}" } + make_string = + proc { "#{Faker::Lorem.characters(8)} #{search_string} #{Faker::Lorem.characters(8)}" } amount.times do - @results << \ + @results << case subsection when 'Models' FactoryGirl.create(:model, product: make_string.call) @@ -150,27 +173,39 @@ when 'Items' FactoryGirl.create(:item, note: make_string.call, inventory_pool: @current_inventory_pool) when 'Licenses' - FactoryGirl.create(:license, note: make_string.call, inventory_pool: @current_inventory_pool) + FactoryGirl.create( + :license, note: make_string.call, inventory_pool: @current_inventory_pool + ) when 'Options' - FactoryGirl.create(:option, product: make_string.call, inventory_pool: @current_inventory_pool) + FactoryGirl.create( + :option, product: make_string.call, inventory_pool: @current_inventory_pool + ) when 'Users' user = FactoryGirl.create(:user, lastname: make_string.call) - FactoryGirl.create(:access_right, user: user, inventory_pool: @current_inventory_pool, role: 'customer') + FactoryGirl.create( + :access_right, user: user, inventory_pool: @current_inventory_pool, role: 'customer' + ) user when 'Contracts' user = FactoryGirl.create(:user, lastname: make_string.call) - FactoryGirl.create(:access_right, user: user, inventory_pool: @current_inventory_pool, role: 'customer') + FactoryGirl.create( + :access_right, user: user, inventory_pool: @current_inventory_pool, role: 'customer' + ) FactoryGirl.create(:closed_contract, user: user, inventory_pool: @current_inventory_pool) user when 'Orders' user = FactoryGirl.create(:user, lastname: make_string.call) - FactoryGirl.create(:access_right, user: user, inventory_pool: @current_inventory_pool, role: 'customer') - order = FactoryGirl.create(:order, user: user, inventory_pool: @current_inventory_pool, state: :submitted) - FactoryGirl.create(:reservation, - user: user, - inventory_pool: @current_inventory_pool, - order: order, - status: :submitted) + FactoryGirl.create( + :access_right, user: user, inventory_pool: @current_inventory_pool, role: 'customer' + ) + order = + FactoryGirl.create( + :order, user: user, inventory_pool: @current_inventory_pool, state: :submitted + ) + FactoryGirl.create( + :reservation, + user: user, inventory_pool: @current_inventory_pool, order: order, status: :submitted + ) user end end @@ -191,9 +226,7 @@ find('.navigation-tab-item', text: _(subsection)).click end -Then(/^the first page of results is shown$/) do - expect(page).to have_selector '.row.line' -end +Then(/^the first page of results is shown$/) { expect(page).to have_selector '.row.line' } Then(/^I see all the entries matching "(.*?)" in the "(.*?)"$/) do |search_string, subsection| @results.each do |r| @@ -206,23 +239,24 @@ end end -Then(/^the (items|licenses) container shows the (?:item|license) line with the following information:$/) do |container_type, table| - # table is a Cucumber::Ast::Table - within "##{container_type} .line[data-id='#{@item.id}']" do +Then( + /^the (items|licenses) container shows the (?:item|license) line with the following information:$/ +) do |container_type, table| + within "##{# table is a Cucumber::Ast::Table + container_type} .line[data-id='#{@item.id}']" do table.raw.flatten.each do |field| - expect(page).to have_content \ - case field - when 'Inventory Code' - @item.inventory_code - when 'Model name', 'Software name' - @item.model.name - when 'Responsible inventory pool' - @item.inventory_pool.name - end + expect(page).to have_content case field + when 'Inventory Code' + @item.inventory_code + when 'Model name', 'Software name' + @item.model.name + when 'Responsible inventory pool' + @item.inventory_pool.name + end end end end - # +# Then(/^I don't see the button group on the (item|license) line$/) do |line_type| within "##{line_type.pluralize} .line[data-id='#{@item.id}']" do expect(page).not_to have_selector '.multibutton' diff --git a/features/step_definitions/manage/software_steps.rb b/features/step_definitions/manage/software_steps.rb index 1c4d62cc01..930e99946b 100644 --- a/features/step_definitions/manage/software_steps.rb +++ b/features/step_definitions/manage/software_steps.rb @@ -19,13 +19,18 @@ find(:select, 'retired').first('option').select_option select _('all models'), from: 'used' @model_id = @software.id - find(".line[data-type='software'][data-id='#{@software.id}']").find('a', text: _('Edit Software')).click + find(".line[data-type='software'][data-id='#{@software.id}']").find('a', text: _('Edit Software')) + .click end Then(/^I can copy an existing software license$/) do step "I'am on the software inventory overview" within('#inventory') do - find(".line[data-type='software'] .button[data-type='inventory-expander'] i.arrow.right", match: :first).click + find( + ".line[data-type='software'] .button[data-type='inventory-expander'] i.arrow.right", + match: :first + ) + .click within(".group-of-lines .line[data-type='license']", match: :first) do within('.multibutton') do find('.dropdown-toggle').click @@ -47,11 +52,17 @@ When(/^I enter a different serial number$/) do @new_serial_number = Faker::Lorem.characters(8) - find(".field[data-type='field']", match: :first, text: _('Serial Number')).find('input').set @new_serial_number + find(".field[data-type='field']", match: :first, text: _('Serial Number')).find( + 'input' + ).set @new_serial_number end When(/^I select a different activation type$/) do - @new_activation_type = find('.field', text: _('Activation Type')).all('option').map(&:value).select{|v| v != @license.properties[:activation_type]}.sample + @new_activation_type = + find('.field', text: _('Activation Type')).all('option').map(&:value).select do |v| + v != @license.properties[:activation_type] + end + .sample find('.field', text: _('Activation Type')).find("option[value='#{@new_activation_type}']").click end @@ -64,10 +75,7 @@ within('.field', text: _('Operating System')) do checkboxes = all("input[type='checkbox']") checkboxes.select(&:checked?).each(&:click) - checkboxes.sample(rand(checkboxes.size)).each do |cb| - cb.click - @new_operating_system_values << cb.value - end + checkboxes.sample(rand(checkboxes.size)).each(&:click) end end @@ -76,10 +84,7 @@ within('.field', text: _('Installation')) do checkboxes = all("input[type='checkbox']") checkboxes.select(&:checked?).each(&:click) - checkboxes.sample(rand(checkboxes.size)).each do |cb| - cb.click - @new_installation_values << cb.value - end + checkboxes.sample(rand(checkboxes.size)).each(&:click) end end @@ -100,7 +105,9 @@ expect(license.invoice_date).to eq (@new_invoice_date.blank? ? nil : @new_invoice_date.to_s) expect(license.properties[:license_expiration]).to eq @new_license_expiration_date.to_s expect(license.properties[:maintenance_contract]).to eq @new_maintenance_contract.to_s - expect(license.properties[:maintenance_expiration]).to eq @new_maintenance_expiration_date.to_s if @new_maintenance_expiration_date + if @new_maintenance_expiration_date + expect(license.properties[:maintenance_expiration]).to eq @new_maintenance_expiration_date.to_s + end expect(license.properties[:reference]).to eq @new_reference expect(license.properties[:project_number]).to eq @project_number if @project_number expect(license.note).to eq @note @@ -113,10 +120,7 @@ @operating_system_values = [] within('.field', text: _('Operating System')) do checkboxes = all("input[type='checkbox']") - checkboxes.sample(rand(checkboxes.size)).each do |cb| - cb.click - @operating_system_values << cb.value - end + checkboxes.sample(rand(checkboxes.size)).each(&:click) end end @@ -124,14 +128,15 @@ @installation_values = [] within('.field', text: _('Installation')) do checkboxes = all("input[type='checkbox']") - checkboxes.sample(rand(checkboxes.size)).each do |cb| - cb.click - @installation_values << cb.value - end + checkboxes.sample(rand(checkboxes.size)).each(&:click) end end -Then(/^one is able to choose for "(.+)" none, one or more of the following options if form of a checkbox:$/) do |arg1, table| +Then( + / + ^one is able to choose for "(.+)" none, one or more of the following options if form of a checkbox:$ + / +) do |arg1, table| within('.field', text: _(arg1)) do table.rows.flatten.each do |option| find('label', text: _(option), match: :prefer_exact).find("input[type='checkbox']") @@ -139,11 +144,11 @@ end end -Then(/^for "(.+)" one can select one of the following options with the help of radio button$/) do |arg1, table| +Then( + /^for "(.+)" one can select one of the following options with the help of radio button$/ +) do |arg1, table| within('.field', text: _(arg1)) do - table.rows.flatten.each do |option| - find('label', text: option).find("input[type='radio']") - end + table.rows.flatten.each { |option| find('label', text: option).find("input[type='radio']") } end end @@ -155,7 +160,8 @@ end Then(/^for maintenance contract the available options are in the following order:$/) do |table| - expect(find('.field', text: _('Maintenance contract')).all('option').map(&:text)).to eq table.raw.flatten + expect(find('.field', text: _('Maintenance contract')).all('option').map(&:text)).to eq table.raw + .flatten end Then(/^for "(.*?)" one can enter a number$/) do |arg1| @@ -207,7 +213,9 @@ When(/^I choose a date for the maintenance expiration$/) do @maintenance_expiration_date = rand(12).months.from_now.to_date - find('.field', text: _('Maintenance expiration')).find('input').set I18n.l @maintenance_expiration_date + find('.field', text: _('Maintenance expiration')).find( + 'input' + ).set I18n.l @maintenance_expiration_date end When(/^I choose "(.*?)" as reference$/) do |arg1| @@ -225,18 +233,22 @@ When(/^I change the license expiration date$/) do @new_license_expiration_date = rand(12).months.from_now.to_date - find('.field', text: _('License expiration')).find('input').set I18n.l(@new_license_expiration_date) + find('.field', text: _('License expiration')).find('input').set I18n.l( + @new_license_expiration_date + ) end When(/^I change the value for maintenance contract$/) do within('.field', text: _('Maintenance contract')) do o = all('option').detect &:selected? - find("option[value='#{@new_maintenance_contract = !(o.value == "true")}']").select_option + find("option[value='#{@new_maintenance_contract = !(o.value == 'true')}']").select_option end if @new_maintenance_contract @new_maintenance_expiration_date = rand(12).months.from_now.to_date - find('.field', text: _('Maintenance expiration')).find('input').set I18n.l(@new_maintenance_expiration_date) + find('.field', text: _('Maintenance expiration')).find('input').set I18n.l( + @new_maintenance_expiration_date + ) end end @@ -245,7 +257,7 @@ radio_buttons = all('input') values = radio_buttons.map(&:value) current_value = radio_buttons.detect(&:selected?).value - @new_reference = values.detect {|v| v != current_value} + @new_reference = values.detect { |v| v != current_value } find("input[value='#{@new_reference}']").click end @@ -257,100 +269,105 @@ Given(/^there is a (.*) with the following properties:$/) do |arg1, table| case arg1 - when 'model', 'software product' - model_attrs = {} - @model_properties = table.raw.map do |k, v| + when 'model', 'software product' + model_attrs = {} + @model_properties = + table.raw.map do |k, v| case k - when 'Name', 'Product' - model_attrs[:product] = v - when 'Manufacturer' - model_attrs[:manufacturer] = v - else - raise + when 'Name', 'Product' + model_attrs[:product] = v + when 'Manufacturer' + model_attrs[:manufacturer] = v + else + raise end v end - @model = case arg1 - when 'model' - FactoryGirl.create :model, model_attrs - when 'software product' - FactoryGirl.create :software, model_attrs - end - - when 'item', 'software license' - item_attrs = {owner: @current_inventory_pool} - item_properties = table.raw.map do |k, v| + @model = + case arg1 + when 'model' + FactoryGirl.create :model, model_attrs + when 'software product' + FactoryGirl.create :software, model_attrs + end + when 'item', 'software license' + item_attrs = { owner: @current_inventory_pool } + item_properties = + table.raw.map do |k, v| case k - when 'Inventory code' - item_attrs[:inventory_code] = v - when 'Serial number' - item_attrs[:serial_number] = v - when 'Dongle ID' - item_attrs[:properties] ||= {} - item_attrs[:properties][:activation_type] = 'dongle' - item_attrs[:properties][:dongle_id] = v - when 'Quantity allocations' - x,y = v.split(' / ') - item_attrs[:properties][:quantity_allocations] ||= [] - item_attrs[:properties][:quantity_allocations] << [x, y] - y - when 'Owner', 'Responsible inventory pool' - ip_key = case k - when 'Owner' - :owner - when 'Responsible inventory pool' - :inventory_pool - end - item_attrs[ip_key] = case v - when 'Current inventory pool' - @current_inventory_pool - when 'Another inventory pool' - @other_inventory_pool ||= InventoryPool.where.not(id: @current_inventory_pool).first - end - else - puts "Don't know how to handle the field named #{k}" - raise + when 'Inventory code' + item_attrs[:inventory_code] = v + when 'Serial number' + item_attrs[:serial_number] = v + when 'Dongle ID' + item_attrs[:properties] ||= {} + item_attrs[:properties][:activation_type] = 'dongle' + item_attrs[:properties][:dongle_id] = v + when 'Quantity allocations' + x, y = v.split(' / ') + item_attrs[:properties][:quantity_allocations] ||= [] + item_attrs[:properties][:quantity_allocations] << [x, y] + y + when 'Owner', 'Responsible inventory pool' + ip_key = + case k + when 'Owner' + :owner + when 'Responsible inventory pool' + :inventory_pool + end + item_attrs[ip_key] = + case v + when 'Current inventory pool' + @current_inventory_pool + when 'Another inventory pool' + @other_inventory_pool ||= InventoryPool.where.not(id: @current_inventory_pool).first + end + else + puts "Don't know how to handle the field named #{k}" + raise end end - @item_properties = @model_properties + item_properties + @item_properties = @model_properties + item_properties - case arg1 - when 'item' - @item = FactoryGirl.create :item, item_attrs.merge({model: @model}) - when 'software license' - @item = FactoryGirl.create :license, item_attrs.merge({model: @model}) - end - - else - raise + case arg1 + when 'item' + @item = FactoryGirl.create :item, item_attrs.merge({ model: @model }) + when 'software license' + @item = FactoryGirl.create :license, item_attrs.merge({ model: @model }) + end + else + raise end - end When(/^I search (in the inventory section )?for one of those (.*)?properties$/) do |arg1, arg2| - search_field = if arg1 - find('#inventory-index-view input#list-search') - else - find('#topbar-search input#search_term') - end - s = case arg2 - when 'software product ' - @model_properties.sample - when 'software license ', '' - @item_properties.sample - end + search_field = + if arg1 + find('#inventory-index-view input#list-search') + else + find('#topbar-search input#search_term') + end + s = + case arg2 + when 'software product ' + @model_properties.sample + when 'software license ', '' + @item_properties.sample + end search_field.set s search_field.native.send_key :return end When(/^I search for the following properties( in the inventory section)?:$/) do |arg1, table| - search_field = if arg1 - find('#inventory-index-view input#list-search') - else - find('#topbar-search input#search_term') - end + search_field = + if arg1 + find('#inventory-index-view input#list-search') + else + find('#topbar-search input#search_term') + end s = table.raw.flatten.sample search_field.set s search_field.native.send_key :return @@ -364,54 +381,68 @@ Then(/^all matching (.*) appear$/) do |arg1| if page.has_selector? '#search-overview' expect(has_no_selector? '#loading').to be true - x,y = case arg1 - when 'models' - ['#models', @model] - when 'items' - ['#items', @item] - when 'software products' - ['#software', @model] - when 'software licenses' - ['#licenses', @item] - when 'contracts, in which this software product is contained' - ['#contracts', @contract_with_software_license] - when 'orders' - ['#orders', @contract] - when 'contracts' - ['#contracts', @contract] - end + x, y = + case arg1 + when 'models' + ['#models', @model] + when 'items' + ['#items', @item] + when 'software products' + ['#software', @model] + when 'software licenses' + ['#licenses', @item] + when 'contracts, in which this software product is contained' + ['#contracts', @contract_with_software_license] + when 'orders' + ['#orders', @contract] + when 'contracts' + ['#contracts', @contract] + end + begin within '#search-overview' do - within x do - find(".line[data-id='#{y.id}']") - end + within x dofind(".line[data-id='#{y.id}']")end end - # if not found in the overview, try in the subsection - rescue + # if not found in the overview, try in the subsection + rescue StandardError if x == '#orders' find("[data-type='show-all']").click find(".line[data-id='#{y.id}']") - find("#orders-search-results nav li a", match: :first).click + find('#orders-search-results nav li a', match: :first).click end end elsif page.has_selector? '#inventory' within '#inventory' do case arg1 - when 'models' - find(".line[data-id='#{@model.id}'][data-type='model']") - when 'items' - if @item.parent_id - find(".group-of-lines .line[data-id='#{@item.parent_id}'][data-type='item'] button[data-type='inventory-expander']").click - find(".group-of-lines .group-of-lines .line[data-id='#{@item.id}'][data-type='item']") - else - find(".line[data-id='#{@item.model_id}'][data-type='model'] button[data-type='inventory-expander']").click - find(".group-of-lines .line[data-id='#{@item.id}'][data-type='item']") - end - when 'package models' - find(".line[data-id='#{@package_item.model.id}'][data-type='model'][data-is_package='true']") - when 'package items' - find(".line[data-id='#{@package_item.model_id}'][data-type='model'][data-is_package='true'] button[data-type='inventory-expander']").click - find(".group-of-lines .line[data-id='#{@package_item.id}'][data-type='item']") + when 'models' + find(".line[data-id='#{@model.id}'][data-type='model']") + when 'items' + if @item.parent_id + find( + ".group-of-lines .line[data-id='#{@item + .parent_id}'][data-type='item'] button[data-type='inventory-expander']" + ) + .click + find(".group-of-lines .group-of-lines .line[data-id='#{@item.id}'][data-type='item']") + else + find( + ".line[data-id='#{@item + .model_id}'][data-type='model'] button[data-type='inventory-expander']" + ) + .click + find(".group-of-lines .line[data-id='#{@item.id}'][data-type='item']") + end + when 'package models' + find( + ".line[data-id='#{@package_item.model.id}'][data-type='model'][data-is_package='true']" + ) + when 'package items' + find( + ".line[data-id='#{@package_item + .model_id}'][data-type='model'][data-is_package='true'] button[data-type='inventory-expander']" + ) + .click + find(".group-of-lines .line[data-id='#{@package_item.id}'][data-type='item']") end end else @@ -419,9 +450,7 @@ end end -Given(/^a software product exists$/) do - @model = FactoryGirl.create :software -end +Given(/^a software product exists$/) { @model = FactoryGirl.create :software } Given(/^a software license exists$/) do step 'a software product exists' @@ -430,22 +459,22 @@ Given(/^this software license is handed over to somebody$/) do @user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) - order = FactoryGirl.create(:order, - user: @user, - inventory_pool: @current_inventory_pool, - state: :approved) - line = FactoryGirl.create(:item_line, - order: order, - inventory_pool: @current_inventory_pool, - user: @user, - status: :approved, - model: @model, - item: @item) - @contract_with_software_license = Contract.sign!(@current_user, - @current_inventory_pool, - @user, - [line], - Faker::Lorem.sentence) + order = + FactoryGirl.create( + :order, user: @user, inventory_pool: @current_inventory_pool, state: :approved + ) + line = + FactoryGirl.create( + :item_line, + order: order, + inventory_pool: @current_inventory_pool, + user: @user, + status: :approved, + model: @model, + item: @item + ) + @contract_with_software_license = + Contract.sign!(@current_user, @current_inventory_pool, @user, [line], Faker::Lorem.sentence) expect(@contract_with_software_license.reservations.reload.empty?).to be false expect(@contract_with_software_license).to be_valid end @@ -465,14 +494,12 @@ end Then(/^this person appears in the search results$/) do - within '#users' do - find(".line [data-id='#{@contract_with_software_license.user_id}']") - end + within '#users' dofind(".line [data-id='#{@contract_with_software_license.user_id}']")end end Given(/^there exist licenses for this software product$/) do rand(1..3).times do - @model.items << FactoryGirl.create(:license, {owner: @current_inventory_pool, model: @model}) + @model.items << FactoryGirl.create(:license, { owner: @current_inventory_pool, model: @model }) end @item = @model.items.first end @@ -485,16 +512,12 @@ Then(/^I can select to list only software products$/) do find('nav a.navigation-tab-item', text: _('Software')).click - within('#software-search-results') do - find(".line[data-id='#{@model.id}']") - end + within('#software-search-results') { find(".line[data-id='#{@model.id}']") } end Then(/^I can select to list only software licenses$/) do find('nav a.navigation-tab-item', text: _('Licenses')).click - within('#licenses-search-results') do - find(".line[data-id='#{@item.id}']") - end + within('#licenses-search-results') { find(".line[data-id='#{@item.id}']") } end When(/^I delete this software product from the list$/) do @@ -512,9 +535,7 @@ Then(/^the software product is deleted from the list$/) do find('a', text: _('Software')).click - within('#inventory') do - expect(has_no_selector?(".line[data-id='#{@model.id}']")).to be true - end + within('#inventory') { expect(has_no_selector?(".line[data-id='#{@model.id}']")).to be true } end Then(/^the software product is deleted$/) do @@ -542,11 +563,17 @@ expect(find('.field', text: _(field)).find('input').value).to eq format end -When(/^I edit a license with set dates for maintenance expiration, license expiration and invoice date$/) do - @license = @current_inventory_pool.items.licenses.find {|i| i.invoice_date and - i.properties[:maintenance_contract] == 'true' and - i.properties[:maintenance_expiration] and - i.properties[:license_expiration] } +When( + / + ^I edit a license with set dates for maintenance expiration, license expiration and invoice date$ + / +) do + @license = + @current_inventory_pool.items.licenses.find do |i| + i.invoice_date and i.properties[:maintenance_contract] == 'true' and + i.properties[:maintenance_expiration] and + i.properties[:license_expiration] + end expect(@license).not_to be_nil visit manage_edit_item_path(@current_inventory_pool, @license) end @@ -565,12 +592,13 @@ end end -When(/^I edit the same license$/) do - visit manage_edit_item_path(@current_inventory_pool, @license) -end +When(/^I edit the same license$/) { visit manage_edit_item_path(@current_inventory_pool, @license) } When(/^I edit again this software product$/) do - string = @table_hashes.select {|x| ['Product', 'Version', 'Manufacturer'].include? x['Field']}.map {|x| x['Value']}.join(' ') + string = + @table_hashes.select { |x| ['Product', 'Version', 'Manufacturer'].include? x['Field'] } + .map { |x| x['Value'] } + .join(' ') results = Software.search(string) expect(results.size).to eq 1 @software = results.first @@ -578,20 +606,25 @@ end #Then(/^outside the the text field, they will additionally displayed reservations with link only$/) do -Then(/^outside the the text field, all the URLs extracted from the software information field are displayed as links$/) do +Then( + / + ^outside the the text field, all the URLs extracted from the software information field are displayed as links$ + / +) do within '#form .field', text: _('Software Information') do - find('.list-of-lines').all('.line').each do |line| - line.find("a[target='_blank']") - end + find('.list-of-lines').all('.line').each { |line| line.find("a[target='_blank']") } end end #Given(/^ich add a new (?:.+) or I change an existing (.+)$/) do |entity| Given(/^I add a new or I change an existing (.+)$/) do |entity| - klass = case _(entity) - when 'model' then Model - when 'software' then Software - end + klass = + case _(entity) + when 'model' + Model + when 'software' + Software + end @model = klass.all.first visit manage_edit_model_path(@current_inventory_pool, @model) end @@ -599,12 +632,18 @@ Then(/^I see the "Software Information"$/) do f = find('.field', text: _('Software Information')) i = f.find('textarea') - expect(i.value).to eq @license.model.technical_detail.delete("\r") + expect(i.value).to eq @license.model.technical_detail.delete('undefined') # expect(f.has_selector? 'a').to be true end -When(/^I edit a software license with software information, quantity allocations and attachments$/) do - @license = @current_inventory_pool.items.licenses.find {|i| i.model.technical_detail =~ /http/ and not i.model.attachments.empty? and i.properties[:quantity_allocations].size >= 2 } +When( + /^I edit a software license with software information, quantity allocations and attachments$/ +) do + @license = + @current_inventory_pool.items.licenses.find do |i| + i.model.technical_detail =~ /http/ and ni.model.attachments.empty? and + i.properties[:quantity_allocations].size >= 2 + end expect(@license).not_to be_nil visit manage_edit_item_path(@current_inventory_pool, @license) end @@ -616,27 +655,21 @@ Then(/^the links of software information open in a new tab upon clicking$/) do f = find('.field', text: _('Software Information')) - f.all('a').each do |link| - expect(link.native.attribute('target')).to eq '_blank' - end + f.all('a').each { |link| expect(link.native.attribute('target')).to eq '_blank' } end Then(/^I see the attachments of the software$/) do within all('.field', text: _('Attachments')).last do - expect(@license.model.attachments.all?{|a| has_selector?('a', text: a.filename)}).to be true + expect(@license.model.attachments.all? { |a| has_selector?('a', text: a.filename) }).to be true end end Then(/^I can open the attachments in a new tab$/) do f = all('.field', text: _('Attachments')).last - f.all('a').each do |link| - expect(link.native.attribute('target')).to eq '_blank' - end + f.all('a').each { |link| expect(link.native.attribute('target')).to eq '_blank' } end -When(/^there exists already a manufacturer$/) do - @manufacturer = Software.manufacturers.sample -end +When(/^there exists already a manufacturer$/) { @manufacturer = Software.manufacturers.sample } Then(/^the manufacturer can be selected from the list$/) do input_field = find('.field', text: _('Manufacturer')).find('input') @@ -648,9 +681,7 @@ When(/^I set a non existing manufacturer$/) do input_field = find('.field', text: _('Manufacturer')).find('input') @manufacturer = Faker::Company.name - while Software.manufacturers.include?(@manufacturer) do - @manufacturer = Faker::Company.name - end + @manufacturer = Faker::Company.name while Software.manufacturers.include?(@manufacturer) input_field.set @manufacturer end @@ -661,9 +692,7 @@ end Then(/^I choose dongle as activation type$/) do - within('.field', text: _('Activation Type')) do - find("option", text: 'Dongle').click - end + within('.field', text: _('Activation Type')) { find('option', text: 'Dongle').click } end Then(/^I have to provide a dongle id$/) do @@ -674,55 +703,61 @@ end When(/^I choose one of the following license types$/) do |table| - find('.field', text: _('License Type')).find('option', text: _(table.rows.flatten.sample)).select_option + find('.field', text: _('License Type')).find('option', text: _(table.rows.flatten.sample)) + .select_option end When(/^I fill in a value$/) do find('.field', text: _('Quantity')).find('input').set (@total_quantity = rand(5..500)) end -Given(/^a software product with more than (\d+) text rows in field "(.*?)" exists$/) do |arg1, arg2| - @model = case arg2 - when 'Software Informationen' - r = @current_inventory_pool.models.where(type: 'Software').detect {|m| m.technical_detail.to_s.split("\r\n").size > arg1.to_i} - r ||= begin - td = [] - (arg1.to_i + rand(1..10)).times { td << Faker::Lorem.paragraph } - m = @current_inventory_pool.models.first - m.update_attributes(technical_detail: td.join("\r\n")) - m - end - r - else - raise - end -end - -When(/^I edit this software$/) do - visit manage_edit_model_path(@current_inventory_pool, @model) +Given( + /^a software product with more than (\d+) text rows in field "(.*?)" exists$/ +) do |arg1, arg2| + @model = + case arg2 + when 'Software Informationen' + r = + @current_inventory_pool.models.where(type: 'Software').detect do |m| + m.technical_detail.to_s.split('undefinedundefined').size > arg1.to_i + end + r ||= + begin + td = [] + (arg1.to_i + rand(1..10)).times { td << Faker::Lorem.paragraph } + m = @current_inventory_pool.models.first + m.update_attributes(technical_detail: td.join('undefinedundefined')) + m + end + r + else + raise + end end +When(/^I edit this software$/) { visit manage_edit_model_path(@current_inventory_pool, @model) } + When(/^I click in the field "(.*?)"$/) do |arg1| case arg1 - when 'Software Informationen' - el = find('#technical_details textarea') - @original_size = el.native.css_value('height') - el.click - else - raise + when 'Software Informationen' + el = find('#technical_details textarea') + @original_size = el.native.css_value('height') + el.click + else + raise end end When(/^this field grows up till showing the complete text$/) do - expect(find("#technical_details textarea").native.css_value('height').to_i).to be > @original_size.to_i + expect(find('#technical_details textarea').native.css_value('height').to_i).to be > + @original_size.to_i end -When(/^I release the focus from this field$/) do - find('body').click # blur all possible focused autocomplete inputs -end +When(/^I release the focus from this field$/) { find('body').click } # blur all possible focused autocomplete inputs Then(/^this field shrinks back to the original size$/) do - expect(find("#technical_details textarea").native.css_value('height').to_i).to eq @original_size.to_i + expect(find('#technical_details textarea').native.css_value('height').to_i).to eq @original_size + .to_i end When(/^I change the value of the note$/) do @@ -732,7 +767,7 @@ When(/^I change the value of dongle id$/) do dongle_field = first('.field', text: _('Dongle ID')) unless dongle_field - step %Q(I choose dongle as activation type) + step 'I choose dongle as activation type' dongle_field = first('.field', text: _('Dongle ID')) end dongle_field.find('input').set (@dongle_id = Faker::Lorem.characters(8)) @@ -753,7 +788,7 @@ new_inline_entry = first('.list-of-lines .row') new_inline_entry.first('[data-quantity-allocation]').set (q = rand(1..50)) new_inline_entry.first('[data-room-allocation]').set (r = Faker::Lorem.word) - @new_quantity_allocations.unshift({room: r, quantity: q}) + @new_quantity_allocations.unshift({ room: r, quantity: q }) end end @@ -769,7 +804,7 @@ new_inline_entry = first('.list-of-lines .row') new_inline_entry.first('[data-quantity-allocation]').set (q = rand(1..50)) new_inline_entry.first('[data-room-allocation]').set (r = Faker::Lorem.word) - @quantity_allocations.unshift({room: r, quantity: q}) + @quantity_allocations.unshift({ room: r, quantity: q }) end end end @@ -799,7 +834,8 @@ within find('.field', text: _('Quantity allocations')) do inline_entries = all("[data-type='inline-entry']") table.rows.each do |row| - inline_entry = inline_entries.detect {|ie| ie.find('[data-room-allocation]').value == row.second} + inline_entry = + inline_entries.detect { |ie| ie.find('[data-room-allocation]').value == row.second } inline_entry.find('[data-remove]').click end end @@ -808,7 +844,11 @@ When(/^I copy an existing software license$/) do step "I'am on the software inventory overview" within('#inventory') do - find(".line[data-id='#{@item.model_id}'][data-type='software'] button[data-type='inventory-expander']").click + find( + ".line[data-id='#{@item + .model_id}'][data-type='software'] button[data-type='inventory-expander']" + ) + .click within(".group-of-lines .line[data-id='#{@item.id}'][data-type='license']") do within('.multibutton') do find('.dropdown-toggle').click @@ -824,12 +864,12 @@ Then(/^the (.*) is labeled as "(.*?)"$/) do |arg1, arg2| case arg1 - when 'title' - find('h1.headline-l', text: arg2) - when 'save button' - find('button.green', text: arg2) - else - raise + when 'title' + find('h1.headline-l', text: arg2) + when 'save button' + find('button.green', text: arg2) + else + raise end end @@ -842,70 +882,78 @@ Then(/^the following fields were copied from the original software license$/) do |table| table.rows.flatten.each do |field| case field - when 'Software' - expect(@target_item.model_id).to eq @item.model_id - when 'Reference' - expect(@target_item.properties[:reference]).to eq @item.properties[:reference] - when 'Owner' - expect(@target_item.owner_id).to eq @item.owner_id - when 'Responsible department' - expect(@target_item.inventory_pool_id).to eq @item.inventory_pool_id - when 'Invoice Date' - expect(@target_item.invoice_date).to eq @item.invoice_date - when 'Initial Price' - expect(@target_item.price).to eq @item.price - when 'Supplier' - expect(@target_item.supplier_id).to eq @item.supplier_id - when 'Procured by' - expect(@target_item.properties[:procured_by]).to eq @item.properties[:procured_by] - when 'Note' - expect(@target_item.note).to eq @item.note - when 'Activation type' - expect(@target_item.properties[:activation_type]).to eq @item.properties[:activation_type] - when 'License Type' - expect(@target_item.properties[:license_type]).to eq @item.properties[:license_type] - when 'Total quantity' - expect(@target_item.properties[:quantity]).to eq @item.properties[:quantity] - when 'Operating System' - expect(@target_item.properties[:operating_system]).to eq @item.properties[:operating_system] - when 'Installation' - expect(@target_item.properties[:installation]).to eq @item.properties[:installation] - when 'License expiration' - expect(@target_item.properties[:license_expiration]).to eq @item.properties[:license_expiration] - when 'Maintenance contract' - expect(@target_item.properties[:maintenance_contract]).to eq @item.properties[:maintenance_contract] - when 'Maintenance expiration' - expect(@target_item.properties[:maintenance_expiration]).to eq @item.properties[:maintenance_expiration] - when 'Currency' - expect(@target_item.properties[:maintenance_currency]).to eq @item.properties[:maintenance_currency] - when 'Price' - expect(@target_item.properties[:maintenance_price]).to eq @item.properties[:maintenance_price] - else - raise + when 'Software' + expect(@target_item.model_id).to eq @item.model_id + when 'Reference' + expect(@target_item.properties[:reference]).to eq @item.properties[:reference] + when 'Owner' + expect(@target_item.owner_id).to eq @item.owner_id + when 'Responsible department' + expect(@target_item.inventory_pool_id).to eq @item.inventory_pool_id + when 'Invoice Date' + expect(@target_item.invoice_date).to eq @item.invoice_date + when 'Initial Price' + expect(@target_item.price).to eq @item.price + when 'Supplier' + expect(@target_item.supplier_id).to eq @item.supplier_id + when 'Procured by' + expect(@target_item.properties[:procured_by]).to eq @item.properties[:procured_by] + when 'Note' + expect(@target_item.note).to eq @item.note + when 'Activation type' + expect(@target_item.properties[:activation_type]).to eq @item.properties[:activation_type] + when 'License Type' + expect(@target_item.properties[:license_type]).to eq @item.properties[:license_type] + when 'Total quantity' + expect(@target_item.properties[:quantity]).to eq @item.properties[:quantity] + when 'Operating System' + expect(@target_item.properties[:operating_system]).to eq @item.properties[:operating_system] + when 'Installation' + expect(@target_item.properties[:installation]).to eq @item.properties[:installation] + when 'License expiration' + expect(@target_item.properties[:license_expiration]).to eq @item.properties[ + :license_expiration + ] + when 'Maintenance contract' + expect(@target_item.properties[:maintenance_contract]).to eq @item.properties[ + :maintenance_contract + ] + when 'Maintenance expiration' + expect(@target_item.properties[:maintenance_expiration]).to eq @item.properties[ + :maintenance_expiration + ] + when 'Currency' + expect(@target_item.properties[:maintenance_currency]).to eq @item.properties[ + :maintenance_currency + ] + when 'Price' + expect(@target_item.properties[:maintenance_price]).to eq @item.properties[:maintenance_price] + else + raise end - end end When(/^I search for one of these (.*)?properties( in the inventory section)?$/) do |arg1, arg2| - if arg2 - s1 = 'in the inventory section ' - else - s1 = '' - end - s2 = case arg1 - when 'software product ' - 'software product ' - when 'software license ' - 'software license ' - else - '' - end + arg2 ? s1 = 'in the inventory section ' : s1 = '' + s2 = + case arg1 + when 'software product ' + 'software product ' + when 'software license ' + 'software license ' + else + '' + end step "I search #{s1}for one of those #{s2}properties" end Given(/^exists a license that belongs to the current inventory pool but is not owned by it$/) do - @license = Item.licenses.where(inventory_pool: @current_inventory_pool).where.not(owner: @current_inventory_pool).first + @license = + Item.licenses.where(inventory_pool: @current_inventory_pool).where.not( + owner: @current_inventory_pool + ) + .first expect(@license).to be end @@ -917,6 +965,4 @@ end end -When(/^I edit the license$/) do - visit manage_edit_item_path @current_inventory_pool, @license -end +When(/^I edit the license$/) { visit manage_edit_item_path @current_inventory_pool, @license } diff --git a/features/step_definitions/manage/take_back/close_contract_steps.rb b/features/step_definitions/manage/take_back/close_contract_steps.rb index 068c1cc6b2..c9f143400c 100644 --- a/features/step_definitions/manage/take_back/close_contract_steps.rb +++ b/features/step_definitions/manage/take_back/close_contract_steps.rb @@ -1,18 +1,24 @@ -When /^I open a take back(, not overdue)?( with at least an option handed over before today)?$/ do |arg1, arg2| +When / + ^I open a take back(, not overdue)?( with at least an option handed over before today)?$ + / do |arg1, arg2| reservations = Reservation.signed.where(inventory_pool_id: @current_user.inventory_pools.managed) - reservation = if arg1 - reservations.detect { |c| c.user.reservations.signed.all? { |l| not l.late? } } - elsif arg2 - reservations.detect { |c| c.user.reservations.signed.any? { |l| l.is_a? OptionLine and l.start_date < Date.today } } - else - reservations.first - end + reservation = + if arg1 + reservations.detect { |c| c.user.reservations.signed.all? { |l| nl.late? } } + elsif arg2 + reservations.detect do |c| + c.user.reservations.signed.any? { |l| l.is_a? OptionLine and l.start_date < Date.today } + end + else + reservations.first + end expect(reservation).not_to be_nil @current_inventory_pool = reservation.inventory_pool @customer = reservation.user visit manage_take_back_path(@current_inventory_pool, @customer) expect(has_selector?('#take-back-view')).to be true - @reservations_to_take_back = @customer.reservations.signed.where(inventory_pool_id: @current_inventory_pool) + @reservations_to_take_back = + @customer.reservations.signed.where(inventory_pool_id: @current_inventory_pool) end When /^I select all reservations of an open contract via Barcode$/ do @@ -24,15 +30,11 @@ end end expect(has_selector?('.line input[type=checkbox][data-select-line]')).to be true - expect(all('.line input[type=checkbox][data-select-line]').all? {|x| x.checked? }).to be true + expect(all('.line input[type=checkbox][data-select-line]').all?(&:checked?)).to be true end Then /^I see a summary of the things I selected for take back$/ do - within('.modal') do - @reservations_to_take_back.each do |line| - has_content?(line.item.model.name) - end - end + within('.modal') { @reservations_to_take_back.each { |line| has_content?(line.item.model.name) } } end When /^I click take back$/ do @@ -50,12 +52,10 @@ within '.modal' do find('.multibutton', text: _('Finish this take back')) end - @reservations_to_take_back.each do |line| - line.reload - expect(line.item.in_stock?).to be true unless line.is_a? OptionLine - expect(line.status).to eq :closed - end - expect(@customer.reservations.signed.where(inventory_pool_id: @current_inventory_pool)).to be_empty + @reservations_to_take_back.each(&:reload) + expect( + @customer.reservations.signed.where(inventory_pool_id: @current_inventory_pool) + ).to be_empty end Then /^the contract is not closed yet$/ do @@ -67,5 +67,12 @@ end Then(/^not all reservations of that option are closed and returned$/) do - expect(@reservation.contract.reservations.signed.where(option_id: @reservation.option_id, start_date: @reservation.start_date, end_date: @reservation.end_date).exists?).to be true + expect( + @reservation.contract.reservations.signed.where( + option_id: @reservation.option_id, + start_date: @reservation.start_date, + end_date: @reservation.end_date + ) + .exists? + ).to be true end diff --git a/features/step_definitions/manage/take_back/edit_take_back_end_date_steps.rb b/features/step_definitions/manage/take_back/edit_take_back_end_date_steps.rb index d607826832..a4941e2dab 100644 --- a/features/step_definitions/manage/take_back/edit_take_back_end_date_steps.rb +++ b/features/step_definitions/manage/take_back/edit_take_back_end_date_steps.rb @@ -1,10 +1,11 @@ When /^I change (a contract|an option) line end date$/ do |arg1| - line_el = case arg1 - when 'an option' - find(".line[data-line-type='option_line']", match: :first) - else - find('.line', match: :first) - end + line_el = + case arg1 + when 'an option' + find(".line[data-line-type='option_line']", match: :first) + else + find('.line', match: :first) + end @line = @reservations_to_take_back.find(line_el['data-id']) line_el.has_content?(@line.model.name) line_el.find('.multibutton .button', text: _('Change entry')).click @@ -27,13 +28,25 @@ end When /^I open a take back which has multiple reservations$/ do - @customer = @current_inventory_pool.users.find {|x| x.contracts.open.exists? and !x.contracts.open.detect{|c| c.reservations.size > 1 and c.inventory_pool == @current_inventory_pool}.nil? } - @contract = @customer.contracts.open.detect{|c| c.reservations.size > 1 and c.inventory_pool == @current_inventory_pool} + @customer = + @current_inventory_pool.users.find do |x| + x.contracts.open.exists? and + !x.contracts.open.detect do |c| + c.reservations.size > 1 and c.inventory_pool == @current_inventory_pool + end + .nil? + end + @contract = + @customer.contracts.open.detect do |c| + c.reservations.size > 1 and c.inventory_pool == @current_inventory_pool + end visit manage_take_back_path(@current_inventory_pool, @customer) expect(has_selector?('#take-back-view')).to be true end -When /^I change the end date for all contract reservations, envolving option and item reservations$/ do +When / + ^I change the end date for all contract reservations, envolving option and item reservations$ + / do step 'I select all reservations' step 'I edit the timerange of the selection' @old_end_date = @contract.reservations.map(&:end_date).max diff --git a/features/step_definitions/manage/take_back_steps.rb b/features/step_definitions/manage/take_back_steps.rb index b59c138534..c41f8f86b2 100644 --- a/features/step_definitions/manage/take_back_steps.rb +++ b/features/step_definitions/manage/take_back_steps.rb @@ -6,7 +6,10 @@ end Given(/^there is a user with at least 2 take back s on 2 different days$/) do - @user = User.find {|u| u.visits.take_back.select{|v| v.inventory_pool == @current_inventory_pool}.count >= 2} + @user = + User.find do |u| + u.visits.take_back.select { |v| v.inventory_pool == @current_inventory_pool }.count >= 2 + end end When(/^I open a take back for this user$/) do @@ -17,7 +20,9 @@ Then(/^the take backs are ordered by date in ascending order$/) do expect(has_selector?('.line[data-line-type]')).to be true - take_backs = @user.visits.take_back.select{|v| v.inventory_pool == @current_inventory_pool}.sort {|d1, d2| d1.date <=> d2.date } + take_backs = + @user.visits.take_back.select { |v| v.inventory_pool == @current_inventory_pool } + .sort { |d1, d2| d1.date <=> d2.date } reservations = take_backs.flat_map &:reservations all(".line[data-line-type='item_line']").each_with_index do |line, i| @@ -31,9 +36,7 @@ elsif ar_line.is_a? OptionLine line.text.include? ar_line.option.name end - end - end When(/^I open a take back for a suspended user$/) do @@ -43,38 +46,39 @@ end Given(/^I am taking something back$/) do - @take_back = @current_inventory_pool.visits.take_back.detect {|v| v.reservations.any? {|l| l.is_a? ItemLine}} + @take_back = + @current_inventory_pool.visits.take_back.detect do |v| + v.reservations.any? { |l| l.is_a? ItemLine } + end @user = @take_back.user step 'I open a take back for this user' end Then(/^I receive a notification( of success)?$/) do |arg1| - within '#flash' do - if arg1 - find('.success') - else - find('.notice') - end - end + within '#flash' doarg1 ? find('.success') : find('.notice')end end Given(/^I am taking back at least one overdue item$/) do - @take_back = @current_inventory_pool.visits.take_back.find {|v| v.reservations.any? {|l| l.end_date.past? }} + @take_back = + @current_inventory_pool.visits.take_back.find do |v| + v.reservations.any? { |l| l.end_date.past? } + end @user = @take_back.user step 'I open a take back for this user' end When(/^I take back an( overdue)? (item|option) using the assignment field$/) do |arg1, arg2| - @reservation = case arg2 - when 'item' - if arg1 - @take_back.reservations.find{|l| l.end_date.past?} - else - @take_back.reservations.detect {|l| l.is_a? ItemLine} - end - when 'option' - @take_back.reservations.find {|l| l.quantity >= 2 } - end + @reservation = + case arg2 + when 'item' + if arg1 + @take_back.reservations.find { |l| l.end_date.past? } + else + @take_back.reservations.detect { |l| l.is_a? ItemLine } + end + when 'option' + @take_back.reservations.find { |l| l.quantity >= 2 } + end @reservations_to_take_back ||= [] @reservations_to_take_back << @reservation within 'form#assign' do @@ -90,7 +94,10 @@ end Given(/^I open a take back with at least two of the same options$/) do - @take_back = @current_inventory_pool.visits.take_back.find {|v| v.reservations.any? {|l| l.quantity >= 2 }} + @take_back = + @current_inventory_pool.visits.take_back.find do |v| + v.reservations.any? { |l| l.quantity >= 2 } + end @user = @take_back.user step 'I open a take back for this user' end @@ -100,7 +107,8 @@ end When(/^I take back all options of the same line$/) do - (@reservation.quantity - find(@line_css).find('input[data-quantity-returned]').value.to_i).times do + (@reservation.quantity - find(@line_css).find('input[data-quantity-returned]').value.to_i) + .times do within 'form#assign' do find('input#assign-input').set @reservation.item.inventory_code find('button .fa.fa-plus').click @@ -109,22 +117,36 @@ end Given(/^there is a user with an option to return in two different time windows$/) do - @user = User.find do |u| - option_lines = u.visits.take_back.select{|v| v.inventory_pool == @current_inventory_pool}.flat_map(&:reservations).select {|l| l.is_a? OptionLine} - option_lines.uniq(&:option).size < option_lines.size - end + @user = + User.find do |u| + option_lines = + u.visits.take_back.select { |v| v.inventory_pool == @current_inventory_pool }.flat_map( + &:reservations + ) + .select { |l| l.is_a? OptionLine } + option_lines.uniq(&:option).size < option_lines.size + end expect(@user).not_to be_nil end When(/^I take back this option$/) do - @option = Option.find {|o| o.option_lines.select{|l| l.status == :signed and l.user == @user}.count >= 2} + @option = + Option.find do |o| + o.option_lines.select { |l| l.status == :signed and l.user == @user }.count >= 2 + end step 'I add the same option again' end Then(/^the option is added to the first time window$/) do - @option_lines = @option.option_lines.select{|l| l.status == :signed and l.user == @user} - @option_line = @option_lines.sort{|a, b| a.end_date <=> b.end_date}.first - expect(find('[data-selected-lines-container]', match: :first, text: @option.inventory_code).find(".line[data-id='#{@option_line.id}'] [data-quantity-returned]").value.to_i).to be > 0 + @option_lines = @option.option_lines.select { |l| l.status == :signed and l.user == @user } + @option_line = @option_lines.sort { |a, b| a.end_date <=> b.end_date }.first + expect( + find('[data-selected-lines-container]', match: :first, text: @option.inventory_code).find( + ".line[data-id='#{@option_line.id}'] [data-quantity-returned]" + ) + .value + .to_i + ).to be > 0 end When(/^I add the same option again$/) do @@ -135,18 +157,33 @@ end When(/^the first time window has already reached the maximum quantity of this option$/) do - until find('[data-selected-lines-container]', match: :first, text: @option.inventory_code).find(".line[data-id='#{@option_line.id}'] [data-quantity-returned]").value.to_i == @option_line.quantity + until find('[data-selected-lines-container]', match: :first, text: @option.inventory_code).find( + ".line[data-id='#{@option_line.id}'] [data-quantity-returned]" + ) + .value + .to_i == + @option_line.quantity step 'I add the same option again' end end Then(/^the option is added to the second time window$/) do - @option_line = @option_lines.sort{|a, b| a.end_date <=> b.end_date}.second - expect(all('[data-selected-lines-container]', text: @option.inventory_code).to_a.second.find(".line[data-id='#{@option_line.id}'] [data-quantity-returned]").value.to_i).to be > 0 + @option_line = @option_lines.sort { |a, b| a.end_date <=> b.end_date }.second + expect( + all('[data-selected-lines-container]', text: @option.inventory_code).to_a.second.find( + ".line[data-id='#{@option_line.id}'] [data-quantity-returned]" + ) + .value + .to_i + ).to be > 0 end Given(/^I open a take back with at least one item and one option$/) do - @take_back = @current_inventory_pool.visits.take_back.find {|v| v.reservations.any? {|l| l.is_a? OptionLine} and v.reservations.any? {|l| l.is_a? ItemLine}} + @take_back = + @current_inventory_pool.visits.take_back.find do |v| + v.reservations.any? { |l| l.is_a? OptionLine } and + v.reservations.any? { |l| l.is_a? ItemLine } + end expect(@take_back).not_to be_nil visit manage_take_back_path(@current_inventory_pool, @take_back.user) end @@ -157,13 +194,9 @@ option_line.find('input[data-quantity-returned]').set (@quantity = quantity) end -When(/^I set "(.*?)" to "(.*?)"$/) do |arg1, arg2| - select _(arg2), from: _(arg1) -end +When(/^I set "(.*?)" to "(.*?)"$/) { |arg1, arg2| select _(arg2), from: _(arg1) } -When(/^I write a status note$/) do - find("textarea[name='status_note']").set Faker::Lorem.sentence -end +When(/^I write a status note$/) { find("textarea[name='status_note']").set Faker::Lorem.sentence } Then(/^the option line has still the same quantity$/) do expect(find(".line[data-id='#{@line_id}'] [data-quantity-returned]").value).to eq @quantity diff --git a/features/step_definitions/manage/templates_steps.rb b/features/step_definitions/manage/templates_steps.rb index 101780482f..64b375ad2e 100644 --- a/features/step_definitions/manage/templates_steps.rb +++ b/features/step_definitions/manage/templates_steps.rb @@ -1,16 +1,15 @@ # -*- encoding : utf-8 -*- When(/^I click on "Templates" in the inventory area$/) do - @current_inventory_pool = @current_user.inventory_pools.managed.select {|ip| ip.templates.exists? }.sample + @current_inventory_pool = + @current_user.inventory_pools.managed.select { |ip| ip.templates.exists? }.sample step 'I open the inventory' click_link _('Templates') end Then(/^I see a list of currently available templates for the current inventory pool$/) do expect(has_content?(_('List of templates'))).to be true - @current_inventory_pool.templates.each do |t| - expect(has_content?(t.name)).to be true - end + @current_inventory_pool.templates.each { |t| expect(has_content?(t.name)).to be true } end Then(/^the templates are ordered alphabetically by their names$/) do @@ -20,13 +19,9 @@ expect(all_names.count).to eq @current_inventory_pool.templates.count end -Given(/^I am listing templates$/) do - visit manage_templates_path(@current_inventory_pool) -end +Given(/^I am listing templates$/) { visit manage_templates_path(@current_inventory_pool) } -When(/^I click the button "New Template"$/) do - click_link _('New Template') -end +When(/^I click the button "New Template"$/) { click_link _('New Template') } Then(/^I can create a new template$/) do expect(current_path).to eq manage_new_template_path(@current_inventory_pool) @@ -34,12 +29,14 @@ When(/^I enter the template's name$/) do @new_name = Faker::Lorem.word - find('.row.emboss.padding-inset-s', match: :prefer_exact, text: _('Name')).find('input').set @new_name + find('.row.emboss.padding-inset-s', match: :prefer_exact, text: _('Name')).find( + 'input' + ).set @new_name end When(/^I add some models to the template$/) do - @changed_model = @current_inventory_pool.models.find {|m| m.items.borrowable.size > 1} - fill_in_autocomplete_field("#{_("Quantity")} / #{_("Models")}", @changed_model.name) + @changed_model = @current_inventory_pool.models.find { |m| m.items.borrowable.size > 1 } + fill_in_autocomplete_field("#{_('Quantity')} / #{_('Models')}", @changed_model.name) end Then(/^each model shows the maximum number of available items$/) do @@ -60,7 +57,12 @@ Then(/^the minimum quantity for the newly added model is (\d+)$/) do |n| within '#models' do - expect(find('.line', match: :first, text: @additional_model.name).find("input[name='template[model_links_attributes][][quantity]']").value).to eq n + expect( + find('.line', match: :first, text: @additional_model.name).find( + "input[name='template[model_links_attributes][][quantity]']" + ) + .value + ).to eq n end end @@ -80,18 +82,16 @@ expect(@template.model_links.first.quantity).to eq @new_value end - Given(/^a template with at least two models exists$/) do - @template = @current_inventory_pool.templates.find do |t| - t.models.size >= 2 and t.models.any? {|m| m.borrowable_items.size >= 2} - end + @template = + @current_inventory_pool.templates.find do |t| + t.models.size >= 2 and t.models.any? { |m| m.borrowable_items.size >= 2 } + end expect(@template).not_to be_nil @template_models_count_original = @template.models.count end -When(/^I click the button "Edit"$/) do - find('.line', text: @template.name).click_link _('Edit') -end +When(/^I click the button "Edit"$/) { find('.line', text: @template.name).click_link _('Edit') } Then(/^I am editing an existing template$/) do expect(current_path).to eq manage_edit_template_path(@current_inventory_pool, @template) @@ -99,14 +99,17 @@ When(/^I change the name$/) do @new_name = Faker::Lorem.word - find('.row.emboss.padding-inset-s', match: :prefer_exact, text: _('Name')).find('input').set @new_name + find('.row.emboss.padding-inset-s', match: :prefer_exact, text: _('Name')).find( + 'input' + ).set @new_name end When(/^I add an additional model$/) do - @additional_model = @current_inventory_pool.models.find do |m| - m.items.borrowable.size > 1 and not @template.models.include? m - end - fill_in_autocomplete_field("#{_("Quantity")} / #{_("Models")}", @additional_model.name) + @additional_model = + @current_inventory_pool.models.find do |m| + m.items.borrowable.size > 1 and n@template.models.include? m + end + fill_in_autocomplete_field("#{_('Quantity')} / #{_('Models')}", @additional_model.name) end When(/^I delete a model from the list$/) do @@ -133,7 +136,9 @@ expect(@template.models.map(&:name)).not_to include @removed_model.name if @removed_model expect(@template.models.map(&:name)).to include @additional_model.name if @additional_model expect(@template.model_links.find_by_model_id(@changed_model.id).quantity).to eq @new_value - expect(@template.models.count).to eq @template_models_count_original if @template_models_count_original + if @template_models_count_original + expect(@template.models.count).to eq @template_models_count_original + end end Then(/^I can delete any template directly from this list$/) do @@ -147,16 +152,16 @@ end When(/^the template has at least one model$/) do - fill_in_autocomplete_field("#{_("Quantity")} / #{_("Models")}", @current_inventory_pool.models.first.name) + fill_in_autocomplete_field( + "#{_('Quantity')} / #{_('Models')}", @current_inventory_pool.models.first.name + ) end Then(/^the template has been deleted from the database$/) do - expect{@template.reload}.to raise_exception + expect { @template.reload }.to raise_exception end -Given(/^I am creating a template$/) do - visit manage_new_template_path(@current_inventory_pool) -end +Given(/^I am creating a template$/) { visit manage_new_template_path(@current_inventory_pool) } When(/^the name is not filled in$/) do within('.row.emboss.padding-inset-s', match: :prefer_exact, text: _('Name')) do @@ -172,9 +177,7 @@ end When(/^I have not added any models$/) do - within '#models' do - all('.line').each {|e| e.find('.button[data-remove]').click} - end + within '#models' doall('.line').each { |e| e.find('.button[data-remove]').click }end end Given(/^I am editing a template$/) do @@ -190,7 +193,11 @@ step 'I can create a new template' end -When(/^I enter a quantity for a model which exceeds its maximum number of borrowable items for this model$/) do +When( + / + ^I enter a quantity for a model which exceeds its maximum number of borrowable items for this model$ + / +) do l = find('#models .line', match: :prefer_exact, text: @changed_model.name) max = l.find('[data-quantities]:nth-child(2)').text.gsub(/\D/, '').to_i @new_value = max + 1 @@ -207,9 +214,7 @@ end end -When(/^I edit the same template$/) do - find('.line', text: @template.name).click_link _('Edit') -end +When(/^I edit the same template$/) { find('.line', text: @template.name).click_link _('Edit') } When(/^I use correct quantities$/) do within('#models .line', match: :prefer_exact, text: @changed_model.name) do @@ -219,6 +224,10 @@ end end -Then(/^I am warned that this template cannot never be ordered due to available quantities being too low$/) do +Then( + / + ^I am warned that this template cannot never be ordered due to available quantities being too low$ + / +) do find('.red', text: _('The highlighted entries are not accomplishable for the intended quantity.')) end diff --git a/features/step_definitions/manage/timeline_steps.rb b/features/step_definitions/manage/timeline_steps.rb index 1f15a438df..4cc89292c4 100644 --- a/features/step_definitions/manage/timeline_steps.rb +++ b/features/step_definitions/manage/timeline_steps.rb @@ -52,7 +52,10 @@ def create_reservation(login, ip_name, product_name) u = user_by_login(login) ip = inventory_pool_by_name(ip_name) m = model_by_product_name(product_name) - FactoryGirl.create(:reservation, user: u, start_date: Date.today, end_date: Date.tomorrow, inventory_pool: ip, model: m) + FactoryGirl.create( + :reservation, + user: u, start_date: Date.today, end_date: Date.tomorrow, inventory_pool: ip, model: m + ) end def create_overdue_reservation(login, ip_name, product_name, inventory_code) @@ -60,14 +63,19 @@ def create_overdue_reservation(login, ip_name, product_name, inventory_code) ip = inventory_pool_by_name(ip_name) m = model_by_product_name(product_name) i = Item.find_by(inventory_code: inventory_code) - r = FactoryGirl.create(:reservation, user: u, start_date: Date.yesterday - 1.day, end_date: Date.yesterday, inventory_pool: ip, model: m, returned_date: nil, item: i) - - contract = Contract.new( - state: :open, - purpose: 'Any Purpose', - user: u, - inventory_pool: ip - ) + r = + FactoryGirl.create( + :reservation, + user: u, + start_date: Date.yesterday - 1.day, + end_date: Date.yesterday, + inventory_pool: ip, + model: m, + returned_date: nil, + item: i + ) + + contract = Contract.new(state: :open, purpose: 'Any Purpose', user: u, inventory_pool: ip) r.status = :signed r.contract = contract @@ -83,7 +91,10 @@ def create_reservation_with_item(login, ip_name, product_name, inventory_code) ip = inventory_pool_by_name(ip_name) m = model_by_product_name(product_name) i = Item.find_by(inventory_code: inventory_code) - FactoryGirl.create(:reservation, user: u, start_date: Date.today, end_date: Date.tomorrow, inventory_pool: ip, model: m, item: i) + FactoryGirl.create( + :reservation, + user: u, start_date: Date.today, end_date: Date.tomorrow, inventory_pool: ip, model: m, item: i + ) end def create_future_reservation(login, ip_name, product_name, inventory_code) @@ -91,7 +102,15 @@ def create_future_reservation(login, ip_name, product_name, inventory_code) ip = inventory_pool_by_name(ip_name) m = model_by_product_name(product_name) i = Item.find_by(inventory_code: inventory_code) - FactoryGirl.create(:reservation, user: u, start_date: Date.today + 10.day, end_date: Date.tomorrow + 12.day, inventory_pool: ip, model: m, item: i) + FactoryGirl.create( + :reservation, + user: u, + start_date: Date.today + 10.day, + end_date: Date.tomorrow + 12.day, + inventory_pool: ip, + model: m, + item: i + ) end def add_ip_manager(ip_name, login) diff --git a/features/step_definitions/manage/user_management_steps.rb b/features/step_definitions/manage/user_management_steps.rb index 228e6a0ea6..3ec4086f72 100644 --- a/features/step_definitions/manage/user_management_steps.rb +++ b/features/step_definitions/manage/user_management_steps.rb @@ -1,7 +1,5 @@ # -*- encoding : utf-8 -*- - - Given(/^I am inventory manager or lending manager$/) do step 'I am %s' % ['Mike', 'Pius'].sample ar = @current_user.access_rights.active.where(role: [:lending_manager, :inventory_manager]).first @@ -44,7 +42,6 @@ def check_user_list(users) find('#user-index-view .inline-tab-navigation .inline-tab-item', text: role).click end - Then /^I can filter to see only suspended users$/ do step 'I can filter by the role "%s"' % _('Customer') @@ -61,16 +58,18 @@ def check_user_list(users) table.hashes.each do |row| step 'I can filter by the role "%s"' % row['tab'] role = row['role'] - users = case role - when 'admins' - User.admins - when 'no_access' - User.where("users.id NOT IN (#{@current_inventory_pool.users.select("users.id").to_sql})") - when 'customers', 'lending_managers', 'inventory_managers' - @current_inventory_pool.users.send(role) - else - User.all - end.paginate(page: 1, per_page: 20) + users = + case role + when 'admins' + User.admins + when 'no_access' + User.where("users.id NOT IN (#{@current_inventory_pool.users.select('users.id').to_sql})") + when 'customers', 'lending_managers', 'inventory_managers' + @current_inventory_pool.users.send(role) + else + User.all + end + .paginate(page: 1, per_page: 20) check_user_list(users) end end @@ -97,13 +96,14 @@ def check_user_list(users) Given(/^I edit a (user|delegation)$/) do |user_type| @inventory_pool ||= @current_user.inventory_pools.managed.first - @customer = case user_type - when 'delegation' - @inventory_pool.users.customers.as_delegations - - when 'user' - @inventory_pool.users.customers.not_as_delegations - end.first + @customer = + case user_type + when 'delegation' + @inventory_pool.users.customers.as_delegations + when 'user' + @inventory_pool.users.customers.not_as_delegations + end + .first @delegation = @customer # Some of the delegation tests expect this to be defined visit manage_edit_inventory_pool_user_path(@inventory_pool, @customer) end @@ -111,7 +111,7 @@ def check_user_list(users) When(/^I use the suspend feature$/) do el = find('[data-suspended-until-input]') el.click - date_s = (Date.today+1.month).strftime('%d/%m/%Y') # Use UK date format (from en-GB) + date_s = (Date.today + 1.month).strftime('%d/%m/%Y') # Use UK date format (from en-GB) el.set(date_s) find('.ui-state-active').click end @@ -138,32 +138,30 @@ def check_user_list(users) #################################################################### -Then /^I can find the user administration features in the "(Manage|Admin)" area under "Users"$/ do |arg1| - if arg1 == 'Manage' - step 'I navigate to the inventory pool manage section' - end +Then / + ^I can find the user administration features in the "(Manage|Admin)" area under "Users"$ + / do |arg1| + step 'I navigate to the inventory pool manage section' if arg1 == 'Manage' step "I open the tab '%s'" % _('Users') end -Given /^a (.*?)user (with|without) assigned role appears in the user list$/ do |suspended, with_or_without| +Given / + ^a (.*?)user (with|without) assigned role appears in the user list$ + / do |suspended, with_or_without| user = User.where(login: 'normin').first case suspended - when 'suspended ' - user - .access_rights - .where(inventory_pool: @current_inventory_pool) - .active - .first - .update_attributes(suspended_until: Date.today + 1.year, suspended_reason: 'suspended reason') + when 'suspended ' + user.access_rights.where(inventory_pool: @current_inventory_pool).active.first + .update_attributes(suspended_until: Date.today + 1.year, suspended_reason: 'suspended reason') end case with_or_without - when 'with' - expect(user.access_rights.active.empty?).to be false - when 'without' - user.access_rights.active.delete_all - expect(user.access_rights.active.empty?).to be true + when 'with' + expect(user.access_rights.active.empty?).to be false + when 'without' + user.access_rights.active.delete_all + expect(user.access_rights.active.empty?).to be true end - step %Q(I can find the user administration features in the "Manage" area under "Users") + step 'I can find the user administration features in the "Manage" area under "Users"' within '#user-list' do find('.line', match: :first) step 'I scroll loading all pages' @@ -175,8 +173,9 @@ def check_user_list(users) user = User.find @el.find('[data-id]')['data-id'] access_right = user.access_right_for(@current_inventory_pool) - strings = table.hashes.map do |x| - case x[:attr] + strings = + table.hashes.map do |x| + case x[:attr] when 'First name/last name' user.name when 'Phone number' @@ -185,24 +184,20 @@ def check_user_list(users) role = access_right.try(:role) || 'no access' _(role.to_s.humanize) when 'Suspended until dd.mm.yyyy' - "#{_("Suspended until")} %s" % I18n.l(access_right.suspended_until) + "#{_('Suspended until')} %s" % I18n.l(access_right.suspended_until) + end end - end expect(@el.text).to match Regexp.new(strings.join('.*')) end #################################################################### - - Then /^the user's first and last name are used as a title$/ do find('h1.headline-l', text: @customer.to_s) end Then /^I see the following information about the user, in order:$/ do |table| - values = table.hashes.map do |x| - _(x[:en]) - end + values = table.hashes.map { |x| _(x[:en]) } expect(page.text).to match Regexp.new(values.join('.*'), Regexp::MULTILINE) end @@ -216,7 +211,9 @@ def check_user_list(users) end end -Then /^I can change this user's information, as long as they use local database authentication and not another adapter$/ do +Then / + ^I can change this user's information, as long as they use local database authentication and not another adapter$ + / do if @customer.authentication_system.class_name == 'DatabaseAuthentication' @attrs = [:lastname, :firstname, :address, :zip, :city, :country, :phone, :email] @attrs.each do |attr| @@ -229,23 +226,21 @@ def check_user_list(users) end end -Then /^I cannot change this user's information if they use something other than local database authentication$/ do - if @customer.authentication_system.class_name != 'DatabaseAuthentication' - end +Then / + ^I cannot change this user's information if they use something other than local database authentication$ + / do + if @customer.authentication_system.class_name != 'DatabaseAuthentication' end Then /^I see the user's role and can change them depending on my own role$/ do find("select[name='access_right[role]']") end - Then /^my changes are saved if I save the user$/ do step 'I save' if @customer.authentication_system.class_name == 'DatabaseAuthentication' @customer.reload - @attrs.each do |attr| - expect(@customer.send(attr)).to match /^#{attr}/ - end + @attrs.each { |attr| expect(@customer.send(attr)).to match /^#{attr}/ } end end @@ -253,21 +248,38 @@ def check_user_list(users) Then(/^I can create new items$/) do c = Item.count - attributes = { - model_id: @inventory_pool.models.first.id, - room_id: FactoryGirl.create(:room).id - } - expect(page.driver.browser.process(:post, manage_create_item_path(@inventory_pool, format: :json), {item: attributes}).successful?).to be true - expect(Item.count).to eq c+1 + attributes = { model_id: @inventory_pool.models.first.id, room_id: FactoryGirl.create(:room).id } + expect( + page.driver.browser.process( + :post, manage_create_item_path(@inventory_pool, format: :json), { item: attributes } + ) + .successful? + ).to be true + expect(Item.count).to eq c + 1 @item = Item.last end Then(/^these items cannot be inventory relevant$/) do - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, @item.id, format: :json), {item: {is_inventory_relevant: true}}).successful?).to be false + expect( + page.driver.browser.process( + :put, + manage_update_item_path(@inventory_pool, @item.id, format: :json), { + item: { is_inventory_relevant: true } + } + ) + .successful? + ).to be false end Then(/^these items can be inventory relevant$/) do - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, @item.id, format: :json), item: {is_inventory_relevant: true}).successful?).to be true + expect( + page.driver.browser.process( + :put, + manage_update_item_path(@inventory_pool, @item.id, format: :json), + item: { is_inventory_relevant: true } + ) + .successful? + ).to be true expect(@item.reload.is_inventory_relevant).to be true end @@ -275,13 +287,18 @@ def check_user_list(users) c = Option.count factory_attributes = FactoryGirl.attributes_for(:option) attributes = { - inventory_code: factory_attributes[:inventory_code], - product: factory_attributes[:product], - version: factory_attributes[:version], - price: factory_attributes[:price] + inventory_code: factory_attributes[:inventory_code], + product: factory_attributes[:product], + version: factory_attributes[:version], + price: factory_attributes[:price] } - expect(page.driver.browser.process(:post, manage_options_path(@inventory_pool, format: :json), option: attributes).redirection?).to be true - expect(Option.count).to eq c+1 + expect( + page.driver.browser.process( + :post, manage_options_path(@inventory_pool, format: :json), option: attributes + ) + .redirection? + ).to be true + expect(Option.count).to eq c + 1 end Then /^I can create a new user (.*?) inventory_pool$/ do |arg1| @@ -289,16 +306,24 @@ def check_user_list(users) ids = User.pluck(:id) factory_attributes = FactoryGirl.attributes_for(:user) attributes = {} - [:login, :firstname, :lastname, :phone, :email, :badge_id, :address, :city, :country, :zip].each do |a| - attributes[a] = factory_attributes[a] - end - response = case arg1 - when 'for the' - page.driver.browser.process(:post, manage_inventory_pool_users_path(@inventory_pool), user: attributes, access_right: {role: :customer}, db_auth: {login: attributes[:login], password: 'password', password_confirmation: 'password'}) - when 'without' - page.driver.browser.process(:post, admin.users_path, user: attributes) - end - expect(User.count).to eq c+1 + [:login, :firstname, :lastname, :phone, :email, :badge_id, :address, :city, :country, :zip] + .each { |a| attributes[a] = factory_attributes[a] } + response = + case arg1 + when 'for the' + page.driver.browser.process( + :post, + manage_inventory_pool_users_path(@inventory_pool), + user: attributes, + access_right: { role: :customer }, + db_auth: { + login: attributes[:login], password: 'password', password_confirmation: 'password' + } + ) + when 'without' + page.driver.browser.process(:post, admin.users_path, user: attributes) + end + expect(User.count).to eq c + 1 id = (User.pluck(:id) - ids).first @user = User.find(id) end @@ -306,72 +331,107 @@ def check_user_list(users) Then(/^I can create and suspend users$/) do step 'I can create a new user for the inventory_pool' expect(@user.access_right_for(@inventory_pool).suspended?).to be false - expect(page.driver.browser.process(:put, manage_update_inventory_pool_user_path(@inventory_pool, @user, format: :json), access_right: {suspended_until: Date.today + 1.year, suspended_reason: 'suspended reason'}).successful?).to be true + expect( + page.driver.browser.process( + :put, + manage_update_inventory_pool_user_path(@inventory_pool, @user, format: :json), + access_right: { suspended_until: Date.today + 1.year, suspended_reason: 'suspended reason' } + ) + .successful? + ).to be true expect(@user.reload.access_right_for(@inventory_pool).suspended?).to be true end -Then(/^I can assign and remove roles to and from users as specified in the following table, but only in the inventory pool for which I am manager$/) do |table| +Then( + / + ^I can assign and remove roles to and from users as specified in the following table, but only in the inventory pool for which I am manager$ + / +) do |table| table.hashes.map do |x| - unknown_user = User.all.detect { |u| not u.access_right_for(@inventory_pool) } + unknown_user = User.all.detect { |u| nu.access_right_for(@inventory_pool) } expect(unknown_user).not_to be_nil - role = case x[:role] - when _('Customer') - expect(unknown_user.has_role?(:customer, @inventory_pool)).to be false - :customer - when _('Group manager') - expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be false - :group_manager - when _('Lending manager') - expect(unknown_user.has_role?(:lending_manager, @inventory_pool)).to be false - :lending_manager - when _('Inventory manager') - expect(unknown_user.has_role?(:inventory_manager, @inventory_pool)).to be false - :inventory_manager - when _('No access') - # the unknown_user needs to have a role first, than it can be deleted - data = {user: {id: unknown_user.id}, - access_right: {role: :customer}, - db_auth: {login: Faker::Lorem.words(3).join, password: 'password', password_confirmation: 'password'}} - page.driver.browser.process(:put, manage_update_inventory_pool_user_path(@inventory_pool, unknown_user, format: :json), data) - :no_access - end - - data = {user: {id: unknown_user.id}, - access_right: {role: role, suspended_until: nil}, - db_auth: {login: Faker::Lorem.words(3).join, password: 'password', password_confirmation: 'password'}} - - expect(page.driver.browser.process(:put, manage_update_inventory_pool_user_path(@inventory_pool, unknown_user, format: :json), data).successful?).to be true - - case role - when :customer - expect(unknown_user.has_role?(:customer, @inventory_pool)).to be true - when :group_manager - expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be true + role = + case x[:role] + when _('Customer') + expect(unknown_user.has_role?(:customer, @inventory_pool)).to be false + :customer + when _('Group manager') + expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be false + :group_manager + when _('Lending manager') expect(unknown_user.has_role?(:lending_manager, @inventory_pool)).to be false - when :lending_manager - expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be true - expect(unknown_user.has_role?(:lending_manager, @inventory_pool)).to be true + :lending_manager + when _('Inventory manager') expect(unknown_user.has_role?(:inventory_manager, @inventory_pool)).to be false - when :inventory_manager - expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be true - expect(unknown_user.has_role?(:lending_manager, @inventory_pool)).to be true - expect(unknown_user.has_role?(:inventory_manager, @inventory_pool)).to be true + :inventory_manager + when _('No access') + data = { + user: { id: unknown_user.id }, + access_right: { role: :customer }, + db_auth: { + login: Faker::Lorem.words(3).join, + password: 'password', + password_confirmation: 'password' + } + } + page.driver.browser.process( + :put, + manage_update_inventory_pool_user_path(@inventory_pool, unknown_user, format: :json), + data + ) + :no_access + end + # the unknown_user needs to have a role first, than it can be deleted + + data = { + user: { id: unknown_user.id }, + access_right: { role: role, suspended_until: nil }, + db_auth: { + login: Faker::Lorem.words(3).join, password: 'password', password_confirmation: 'password' + } + } + + expect( + page.driver.browser.process( + :put, + manage_update_inventory_pool_user_path(@inventory_pool, unknown_user, format: :json), + data + ) + .successful? + ).to be true + + case role + when :customer + expect(unknown_user.has_role?(:customer, @inventory_pool)).to be true + when :group_manager + expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be true + expect(unknown_user.has_role?(:lending_manager, @inventory_pool)).to be false + when :lending_manager + expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be true + expect(unknown_user.has_role?(:lending_manager, @inventory_pool)).to be true + expect(unknown_user.has_role?(:inventory_manager, @inventory_pool)).to be false + when :inventory_manager + expect(unknown_user.has_role?(:group_manager, @inventory_pool)).to be true + expect(unknown_user.has_role?(:lending_manager, @inventory_pool)).to be true + expect(unknown_user.has_role?(:inventory_manager, @inventory_pool)).to be true end end end - - -Then(/^I can retire items if my inventory pool is their owner and they are not inventory relevant$/) do +Then( + /^I can retire items if my inventory pool is their owner and they are not inventory relevant$/ +) do item = @inventory_pool.own_items.where(is_inventory_relevant: false).first expect(item.retired?).to be false - attributes = { - retired: true, - retired_reason: 'Item is gone' - } + attributes = { retired: true, retired_reason: 'Item is gone' } - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, item, format: :json), item: attributes).successful?).to be true + expect( + page.driver.browser.process( + :put, manage_update_item_path(@inventory_pool, item, format: :json), item: attributes + ) + .successful? + ).to be true expect(item.reload.retired?).to be true expect(item.retired).to eq Date.today @@ -383,36 +443,53 @@ def check_user_list(users) c = Model.count attributes = FactoryGirl.attributes_for :model - expect(page.driver.browser.process(:post, "/manage/#{@inventory_pool.id}/models.json", model: attributes).successful?).to be true - expect(Model.count).to eq c+1 + expect( + page.driver.browser.process( + :post, "/manage/#{@inventory_pool.id}/models.json", model: attributes + ) + .successful? + ).to be true + expect(Model.count).to eq c + 1 end Then(/^I can make another inventory pool the owner of the items$/) do - attributes = { - owner_id: (InventoryPool.pluck(:id) - [@inventory_pool.id]).first - } + attributes = { owner_id: (InventoryPool.pluck(:id) - [@inventory_pool.id]).first } expect(@item.owner_id).not_to eq attributes[:owner_id] - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, @item, format: :json), item: attributes).successful?).to be true + expect( + page.driver.browser.process( + :put, manage_update_item_path(@inventory_pool, @item, format: :json), item: attributes + ) + .successful? + ).to be true expect(@item.reload.owner_id).to eq attributes[:owner_id] end When(/^I don't choose a responsible department when creating or editing items$/) do @item = @inventory_pool.own_items.find &:in_stock? attributes = { - inventory_pool_id: (InventoryPool.pluck(:id) - [@inventory_pool.id, @item.inventory_pool_id]).first + inventory_pool_id: + (InventoryPool.pluck(:id) - [@inventory_pool.id, @item.inventory_pool_id]).first } expect(@item.inventory_pool_id).not_to eq attributes[:inventory_pool_id] - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, @item, format: :json), item: attributes).successful?).to be true + expect( + page.driver.browser.process( + :put, manage_update_item_path(@inventory_pool, @item, format: :json), item: attributes + ) + .successful? + ).to be true expect(@item.reload.inventory_pool_id).to eq attributes[:inventory_pool_id] - attributes = { - inventory_pool_id: nil - } + attributes = { inventory_pool_id: nil } expect(@item.inventory_pool_id).not_to eq attributes[:inventory_pool_id] - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, @item, format: :json), item: attributes).successful?).to be true + expect( + page.driver.browser.process( + :put, manage_update_item_path(@inventory_pool, @item, format: :json), item: attributes + ) + .successful? + ).to be true end Then(/^the responsible department is the same as the owner$/) do @@ -421,32 +498,36 @@ def check_user_list(users) Then(/^I can retire these items if my inventory pool is their owner$/) do item = @inventory_pool.own_items.find &:in_stock? - attributes = { - retired: true, - retired_reason: 'retired reason' - } + attributes = { retired: true, retired_reason: 'retired reason' } expect(item.retired).to eq nil expect(item.retired_reason).to eq nil - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, item, format: :json), item: attributes).successful?).to be true + expect( + page.driver.browser.process( + :put, manage_update_item_path(@inventory_pool, item, format: :json), item: attributes + ) + .successful? + ).to be true expect(item.reload.retired).to eq Date.today expect(item.retired_reason).to eq attributes[:retired_reason] end Then(/^I can unretire items if my inventory pool is their owner$/) do item = Item.unscoped { @inventory_pool.own_items.where.not(retired: nil).first } - attributes = { - retired: nil - } + attributes = { retired: nil } expect(item.retired).not_to be_nil expect(item.retired_reason).not_to be_nil - expect(page.driver.browser.process(:put, manage_update_item_path(@inventory_pool, item, format: :json), item: attributes).successful?).to be true + expect( + page.driver.browser.process( + :put, manage_update_item_path(@inventory_pool, item, format: :json), item: attributes + ) + .successful? + ).to be true expect(item.reload.retired).to eq nil expect(item.retired_reason).to eq nil end - Then(/^I can specify workdays and holidays for my inventory pool$/) do visit manage_edit_inventory_pool_path @inventory_pool end @@ -469,7 +550,11 @@ def check_user_list(users) Then(/^I can remove groups$/) do @groups_removed = @customer.entitlement_groups @groups_removed.each do |group| - find('.row.emboss', match: :prefer_exact, text: _('Groups')).find('.field-inline-entry', text: group.name).find('.clickable', text: _('Remove')).click + find('.row.emboss', match: :prefer_exact, text: _('Groups')).find( + '.field-inline-entry', text: group.name + ) + .find('.clickable', text: _('Remove')) + .click end end @@ -487,26 +572,29 @@ def check_user_list(users) end end -When(/^I am looking at the user list( outside an inventory pool| in any inventory pool)?$/) do |arg1| +When( + /^I am looking at the user list( outside an inventory pool| in any inventory pool)?$/ +) do |arg1| visit case arg1 - when ' outside an inventory pool' - admin.users_path - when ' in any inventory pool' - @current_inventory_pool = @current_user.inventory_pools.managed.sample || InventoryPool.first - manage_inventory_pool_users_path(@current_inventory_pool) - else - manage_inventory_pool_users_path(@current_inventory_pool) + when ' outside an inventory pool' + admin.users_path + when ' in any inventory pool' + @current_inventory_pool = + @current_user.inventory_pools.managed.sample || InventoryPool.first + manage_inventory_pool_users_path(@current_inventory_pool) + else + manage_inventory_pool_users_path(@current_inventory_pool) end end -When(/^I add a user$/) do - find_link(_('New User')).click -end +When(/^I add a user$/) { find_link(_('New User')).click } When(/^I enter the following information$/) do |table| selector = @current_inventory_pool ? '.row.emboss' : '.form-group' table.raw.flatten.each do |field_name| - find(selector, match: :prefer_exact, text: field_name).find('input,textarea').set (field_name == 'E-Mail' ? 'test@test.ch' : 'test') + find(selector, match: :prefer_exact, text: field_name).find( + 'input,textarea' + ).set (field_name == 'E-Mail' ? 'test@test.ch' : 'test') end end @@ -535,13 +623,17 @@ def check_user_list(users) user = User.find_by_lastname 'test' expect(user).not_to be_nil expect(user.access_right_for(@current_inventory_pool).role).to eq @role_hash[:role].to_sym - expect(user.entitlement_groups.map(&:id)).to match_array @current_inventory_pool.entitlement_groups.map(&:id) + expect(user.entitlement_groups.map(&:id)).to match_array @current_inventory_pool + .entitlement_groups + .map(&:id) end When(/^all required fields are filled in$/) do find('.row.emboss', match: :prefer_exact, text: _('Last name')).find('input,textarea').set 'test' find('.row.emboss', match: :prefer_exact, text: _('First name')).find('input,textarea').set 'test' - find('.row.emboss', match: :prefer_exact, text: _('E-Mail')).find('input,textarea').set 'test@test.ch' + find('.row.emboss', match: :prefer_exact, text: _('E-Mail')).find( + 'input,textarea' + ).set 'test@test.ch' end When(/^I did not enter last name$/) do @@ -557,43 +649,39 @@ def check_user_list(users) end When(/^I did not enter reason for suspension$/) do - find('.row.emboss', match: :prefer_exact, text: _('Suspended reason')).find('input,textarea').set '' + find('.row.emboss', match: :prefer_exact, text: _('Suspended reason')).find( + 'input,textarea' + ).set '' end -When(/^I navigate from here to the user creation page$/) do - click_link _('New User') -end +When(/^I navigate from here to the user creation page$/) { click_link _('New User') } Then(/^I am redirected to the user list outside an inventory pool$/) do expect(current_path).to eq admin.users_path end -Then(/^the new user has been created$/) do - @user = User.find_by_email 'test@test.ch' -end +Then(/^the new user has been created$/) { @user = User.find_by_email 'test@test.ch' } Then(/^he does not have access to any inventory pools and is not an administrator$/) do expect(@user.access_rights.active.empty?).to be true end Given(/^I am editing a user that has no access rights and is not an admin$/) do - @user = User.find { |u| not u.is_admin and u.has_role? :customer } + @user = User.find { |u| nu.is_admin and u.has_role? :customer } @previous_access_rights = @user.access_rights.freeze visit admin.edit_user_path(@user) end Given /^I do not have access as manager to any inventory pools$/ do - expect(@current_user.access_rights.where(role: [:group_manager, :lending_manager, :inventory_manager]).exists?).to be false -end - -When(/^I assign the admin role to this user$/) do - select _('Yes'), from: 'user_admin' + expect( + @current_user.access_rights.where(role: [:group_manager, :lending_manager, :inventory_manager]) + .exists? + ).to be false end -Then(/^this user has the admin role$/) do - expect(@user.reload.is_admin).to be true -end +When(/^I assign the admin role to this user$/) { select _('Yes'), from: 'user_admin' } +Then(/^this user has the admin role$/) { expect(@user.reload.is_admin).to be true } Then(/^all their previous access rights remain intact$/) do expect((@previous_access_rights - @user.access_rights.reload).empty?).to be true @@ -606,22 +694,16 @@ def check_user_list(users) visit admin.edit_user_path(@user) end -When(/^I remove the admin role from this user$/) do - select _('No'), from: 'user_admin' -end +When(/^I remove the admin role from this user$/) { select _('No'), from: 'user_admin' } -Then(/^this user no longer has the admin role$/) do - expect(@user.reload.is_admin).to be false -end +Then(/^this user no longer has the admin role$/) { expect(@user.reload.is_admin).to be false } When(/^I try to access the admin area's user editing page$/) do @path = admin.edit_user_path(User.first) visit @path end -Then(/^I can't access that page$/) do - expect(current_path).not_to eq @path -end +Then(/^I can't access that page$/) { expect(current_path).not_to eq @path } When(/^I try to access the admin area's user creation page$/) do @path = '/admin/users/new' @@ -629,20 +711,27 @@ def check_user_list(users) end Then(/^I can only choose the following roles$/) do |table| - expect(find('.row.emboss', match: :prefer_exact, text: _('Access as')).all('option').length).to eq table.raw.length + expect( + find('.row.emboss', match: :prefer_exact, text: _('Access as')).all('option').length + ).to eq table.raw.length table.raw.flatten.each do |role| find('.row.emboss', match: :prefer_exact, text: _('Access as')).find('option', text: _(role)) end end Given(/^I edit a user who has access as customer$/) do - access_right = AccessRight.find { |ar| ar.role == :customer and ar.inventory_pool == @current_inventory_pool } + access_right = + AccessRight.find { |ar| ar.role == :customer and ar.inventory_pool == @current_inventory_pool } @user = access_right.user visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @user) end Given(/^I edit a user who has access as lending manager$/) do - access_right = AccessRight.find { |ar| ar.role == :lending_manager and ar.inventory_pool == @current_inventory_pool and ar.user != @current_user } + access_right = + AccessRight.find do |ar| + ar.role == :lending_manager and ar.inventory_pool == @current_inventory_pool and + ar.user != @current_user + end @user = access_right.user visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @user) end @@ -655,14 +744,15 @@ def check_user_list(users) end When(/^I change the access level to "(.*)"$/) do |arg1| - s = case arg1 - when 'customer' - _('Customer') - when 'lending manager' - _('Lending manager') - when 'inventory manager' - _('Inventory manager') - end + s = + case arg1 + when 'customer' + _('Customer') + when 'lending manager' + _('Lending manager') + when 'inventory manager' + _('Inventory manager') + end find('.row.emboss', match: :prefer_exact, text: _('Access as')).find('select').select s end @@ -688,7 +778,7 @@ def check_user_list(users) When(/^I delete that user from the list$/) do @user ||= @users.sample - step %Q(I search for "%s") % @user.to_s + step 'I search for "%s"' % @user.to_s within('#user-list .row', text: @user.name) do within('.line-actions') do find('.dropdown-toggle').click @@ -700,7 +790,7 @@ def check_user_list(users) Then /^the delete button for that user is not present$/ do @user ||= @users.sample - step %Q(I search for "%s") % @user.to_s + step 'I search for "%s"' % @user.to_s within('#user-list .row', text: @user.name) do within('.line-actions') do find('.dropdown-toggle').click @@ -723,33 +813,44 @@ def check_user_list(users) expect(User.find_by_id(@user.id)).not_to be_nil end - Given(/^I pick one user with access rights, one with orders and one with contracts$/) do @users = [] - @users << User.find { |u| not u.access_rights.active.empty? and u.orders.empty? } - @users << User.find { |u| not u.orders.empty? } + @users << User.find { |u| nu.access_rights.active.empty? and u.orders.empty? } + @users << User.find { |u| nu.orders.empty? } @users << User.find { |u| u.orders.empty? } end -Given(/^I am editing a user who has access to (and no items from )?(the current|an) inventory pool$/) do |arg1, arg2| +Given( + /^I am editing a user who has access to (and no items from )?(the current|an) inventory pool$/ +) do |arg1, arg2| case arg2 - when 'the current' - access_rights = @current_inventory_pool.access_rights.active.where(role: :customer) - @user = if arg1 - access_rights.detect { |ar| @current_inventory_pool.reservations.where(user_id: ar.user).empty? } - else - access_rights.first - end.user - when 'an' - access_right = AccessRight.active.where(role: :customer, inventory_pool_id: @current_user.inventory_pools.managed).detect {|ar| ar.inventory_pool.reservations.where(user_id: ar.user).empty? } - @user = access_right.user - @current_inventory_pool = access_right.inventory_pool + when 'the current' + access_rights = @current_inventory_pool.access_rights.active.where(role: :customer) + @user = + if arg1 + access_rights.detect do |ar| + @current_inventory_pool.reservations.where(user_id: ar.user).empty? + end + else + access_rights.first + end + .user + when 'an' + access_right = + AccessRight.active.where( + role: :customer, inventory_pool_id: @current_user.inventory_pools.managed + ) + .detect { |ar| ar.inventory_pool.reservations.where(user_id: ar.user).empty? } + @user = access_right.user + @current_inventory_pool = access_right.inventory_pool end visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @user) end When(/^I remove their access$/) do - find('.row.emboss', match: :prefer_exact, text: _('Access as')).find('select').select _('No access') + find('.row.emboss', match: :prefer_exact, text: _('Access as')).find('select').select _( + 'No access' + ) end Then(/^the user has no access to the inventory pool$/) do @@ -760,23 +861,24 @@ def check_user_list(users) Then(/^users are sorted alphabetically by first name$/) do within('#user-list') do find('.line', match: :first) - t = if current_path == admin.users_path - all('.line > div:nth-child(1)').map(&:text).map { |t| t.split(' ').take(2).join(' ') } - else - all('.line > div:nth-child(1)').map(&:text) - end + t = + if current_path == admin.users_path + all('.line > div:nth-child(1)').map(&:text).map { |t| t.split(' ').take(2).join(' ') } + else + all('.line > div:nth-child(1)').map(&:text) + end expect(t).to eq User.order(:firstname).paginate(page: 1, per_page: 20).map(&:name) end end - When(/^I enter the login data$/) do selector = @current_inventory_pool ? '.row.emboss' : '.form-group' find(selector, match: :prefer_exact, text: _('Password')).find('input').set 'password' - find(selector, match: :prefer_exact, text: _('Password Confirmation')).find('input').set 'password' + find(selector, match: :prefer_exact, text: _('Password Confirmation')).find( + 'input' + ).set 'password' end - Given(/^I edit a user who doesn't have access to the current inventory pool$/) do @user = User.find { |u| u.access_rights.active.blank? } visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @user) @@ -784,7 +886,9 @@ def check_user_list(users) When(/^I change the email address$/) do selector = @current_inventory_pool ? '.row.emboss' : '.form-group' - find(selector, match: :prefer_exact, text: _('E-Mail')).find('input,textarea').set 'changed@test.ch' + find(selector, match: :prefer_exact, text: _('E-Mail')).find( + 'input,textarea' + ).set 'changed@test.ch' end Then(/^I see a confirmation of success on the list of users$/) do @@ -797,11 +901,17 @@ def check_user_list(users) end Then(/^the user still has access to the current inventory pool$/) do - expect(@user.access_rights.active.detect { |ar| ar.inventory_pool == @current_inventory_pool }).to eq nil + expect( + @user.access_rights.active.detect { |ar| ar.inventory_pool == @current_inventory_pool } + ).to eq nil end Given(/^I edit a user who used to have access to the current inventory pool$/) do - @current_inventory_pool = @current_user.inventory_pools.managed.where(id: AccessRight.select(:inventory_pool_id).where.not(deleted_at: nil)).first + @current_inventory_pool = + @current_user.inventory_pools.managed.where( + id: AccessRight.select(:inventory_pool_id).where.not(deleted_at: nil) + ) + .first @user = @current_inventory_pool.access_rights.where.not(deleted_at: nil).first.user visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @user) end @@ -813,43 +923,42 @@ def check_user_list(users) end Then(/^inventory pools they have access to are listed with the respective role$/) do - @user.access_rights.active.each do |access_right| - find('.well ul > li', text: access_right.to_s) - end + @user.access_rights.active.each { |access_right| find('.well ul > li', text: access_right.to_s) } end #Given(/^there exists a contract with status "(.*?)" for a user with otherwise no other contracts$/) do |arg1| -Given(/^there exists a contract with status "(.*?)" for a user without any other contracts$/) do |arg1| - state = case arg1 - when 'submitted' then - :submitted - when 'approved' then - :approved - when 'signed' then - :signed - end +Given( + /^there exists a contract with status "(.*?)" for a user without any other contracts$/ +) do |arg1| + state = + case arg1 + when 'submitted' + :submitted + when 'approved' + :approved + when 'signed' + :signed + end if state == :submitted user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) - @contract = FactoryGirl.create(:order, - user: user, - inventory_pool: @current_inventory_pool, - state: :submitted) - FactoryGirl.create(:reservation, - user: user, - inventory_pool: @current_inventory_pool, - order: @contract, - status: :submitted) + @contract = + FactoryGirl.create( + :order, user: user, inventory_pool: @current_inventory_pool, state: :submitted + ) + FactoryGirl.create( + :reservation, + user: user, inventory_pool: @current_inventory_pool, order: @contract, status: :submitted + ) elsif state == :approved user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) - @contract = FactoryGirl.create(:order, - user: user, - inventory_pool: @current_inventory_pool, - state: :approved) - FactoryGirl.create(:reservation, - user: user, - inventory_pool: @current_inventory_pool, - order: @contract, - status: :approved) + @contract = + FactoryGirl.create( + :order, user: user, inventory_pool: @current_inventory_pool, state: :approved + ) + FactoryGirl.create( + :reservation, + user: user, inventory_pool: @current_inventory_pool, order: @contract, status: :approved + ) elsif state == :signed @contract = FactoryGirl.create(:open_contract, inventory_pool: @current_inventory_pool) end @@ -865,6 +974,4 @@ def check_user_list(users) expect(@user.access_right_for(@current_inventory_pool)).not_to be_nil end -Then(/^I see the error message "(.*?)"$/) do |arg1| - find('#flash .error', text: _(arg1)) -end +Then(/^I see the error message "(.*?)"$/) { |arg1| find('#flash .error', text: _(arg1)) } diff --git a/features/step_definitions/manage/value_list_steps.rb b/features/step_definitions/manage/value_list_steps.rb index 7f80bf083f..a5f6da4b9b 100644 --- a/features/step_definitions/manage/value_list_steps.rb +++ b/features/step_definitions/manage/value_list_steps.rb @@ -9,9 +9,7 @@ new_window = page.driver.browser.window_handles.last page.driver.browser.switch_to.window new_window - new_window = window_opened_by do - find('.modal a', text: _('Value List')).click - end + new_window = window_opened_by { find('.modal a', text: _('Value List')).click } page.driver.browser.switch_to.window new_window.handle @list_element = find('.value_list') @@ -21,36 +19,36 @@ within @list_element do table.hashes.each do |area| case area['Section'] - when 'Date' - within('.date') do - expect(has_content? Date.today.year).to be true - expect(has_content? Date.today.month).to be true - expect(has_content? Date.today.day).to be true - end - when 'Title' - case arg1 - when 'value list' - expect(find('h1', text: _('Value List')).has_content? @contract.compact_id).to be true - when 'picking list' - find('h1', text: _('Picking List')) - end - when 'Borrower' - within('.customer') do - expect(has_content? @user.firstname).to be true - expect(has_content? @user.lastname).to be true - expect(has_content? @user.address).to be true if @user.address - expect(has_content? @user.zip).to be true - expect(has_content? @user.city).to be true - end - when 'Lender' - find('.inventory_pool') - when 'List' - case arg1 - when 'value list' - find('.list') - when 'picking list' - find('.list', match: :first) - end + when 'Date' + within('.date') do + expect(has_content? Date.today.year).to be true + expect(has_content? Date.today.month).to be true + expect(has_content? Date.today.day).to be true + end + when 'Title' + case arg1 + when 'value list' + expect(find('h1', text: _('Value List')).has_content? @contract.compact_id).to be true + when 'picking list' + find('h1', text: _('Picking List')) + end + when 'Borrower' + within('.customer') do + expect(has_content? @user.firstname).to be true + expect(has_content? @user.lastname).to be true + expect(has_content? @user.address).to be true if @user.address + expect(has_content? @user.zip).to be true + expect(has_content? @user.city).to be true + end + when 'Lender' + find('.inventory_pool') + when 'List' + case arg1 + when 'value list' + find('.list') + when 'picking list' + find('.list', match: :first) + end end end end @@ -61,135 +59,166 @@ within @list do table.hashes.each do |area| case area['Column'] - when 'Consecutive number' - @contract.reservations.each {|line| find('tr', text: line.item.inventory_code).find('.consecutive_number') } - when 'Inventory code' - reservations = - if @list_element[:class] == 'picking_list' - @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations - elsif @list_element[:class] == 'value_list' - @contract.reservations - else - raise - end - reservations.each do |line| - next if line.item_id.nil? - find('tr .inventory_code', text: line.item.inventory_code) - end - when 'Model name' - if @list_element[:class] == 'picking_list' - reservations = @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations - reservations.group_by(&:model).each_pair do |model, reservations| - find('tr', match: :prefer_exact, text: model).find('.model_name', text: model.name) - end - elsif @list_element[:class] == 'value_list' - @contract.reservations.each {|line| find('tr', text: line.item.inventory_code).find('.model_name', text: line.model.name) } - else - raise - end - when 'End date' - @contract.reservations.each {|line| - within find('tr', text: line.item.inventory_code).find('.end_date') do - expect(has_content? line.end_date.year).to be true - expect(has_content? line.end_date.month).to be true - expect(has_content? line.end_date.day).to be true - end - } - when 'Quantity' + when 'Consecutive number' + @contract.reservations.each do |line| + find('tr', text: line.item.inventory_code).find('.consecutive_number') + end + when 'Inventory code' + reservations = if @list_element[:class] == 'picking_list' - picking_lines = @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations - picking_lines.group_by(&:model).each_pair do |model, reservations| - find('tr', match: :prefer_exact, text: model).find('.quantity', text: reservations.sum(&:quantity)) - end + @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations elsif @list_element[:class] == 'value_list' - @contract.reservations.each {|line| - find('tr', text: line.item.inventory_code).find('.quantity', text: line.quantity) - } + @contract.reservations else raise end - when 'Price' - @contract.reservations.each {|line| - expect(find('tbody tr', text: line.item.inventory_code).find('.item_price').text.gsub(/\D/, '')).to eq ('%.2f' % line.price).gsub(/\D/, '') - } - when 'Room / Shelf' - find('table thead tr td.location', text: '%s / %s' % [_('Room'), _('Shelf')]) - reservations = @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations - reservations.each {|line| - find('tbody tr', text: line.item ? line.item.inventory_code : line.model.name).find('.location', text: - if line.model.is_a?(Option) - _('Location not defined') - else - '%s / %s' % [line.item.room.name, line.item.shelf] - end) - } - when 'available quantity x Room / Shelf' - find('table thead tr td.location', text: '%s x %s / %s' % [_('available quantity'), _('Room'), _('Shelf')]) + reservations.each do |line| + next if line.item_id.nil? + find('tr .inventory_code', text: line.item.inventory_code) + end + when 'Model name' + if @list_element[:class] == 'picking_list' reservations = @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations - reservations.each do |line| - within find('tr', match: :prefer_exact, text: line.model).find('.location') do + reservations.group_by(&:model).each_pair do |model, reservations| + find('tr', match: :prefer_exact, text: model).find('.model_name', text: model.name) + end + elsif @list_element[:class] == 'value_list' + @contract.reservations.each do |line| + find('tr', text: line.item.inventory_code).find('.model_name', text: line.model.name) + end + else + raise + end + when 'End date' + @contract.reservations.each do |line| + within find('tr', text: line.item.inventory_code).find('.end_date') do + expect(has_content? line.end_date.year).to be true + expect(has_content? line.end_date.month).to be true + expect(has_content? line.end_date.day).to be true + end + end + when 'Quantity' + if @list_element[:class] == 'picking_list' + picking_lines = @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations + picking_lines.group_by(&:model).each_pair do |model, reservations| + find('tr', match: :prefer_exact, text: model).find( + '.quantity', text: reservations.sum(&:quantity) + ) + end + elsif @list_element[:class] == 'value_list' + @contract.reservations.each do |line| + find('tr', text: line.item.inventory_code).find('.quantity', text: line.quantity) + end + else + raise + end + when 'Price' + @contract.reservations.each do |line| + expect( + find('tbody tr', text: line.item.inventory_code).find('.item_price').text.gsub(/\D/, '') + ).to eq ('%.2f' % line.price).gsub(/\D/, '') + end + when 'Room / Shelf' + find('table thead tr td.location', text: '%s / %s' % [_('Room'), _('Shelf')]) + reservations = @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations + reservations.each do |line| + find('tbody tr', text: line.item ? line.item.inventory_code : line.model.name).find( + '.location', + text: if line.model.is_a?(Option) _('Location not defined') else - locations = line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).select('COUNT(items.id) AS count, rooms.name AS room_name, items.shelf AS shelf').joins(:room).group('rooms.id', 'rooms.name', 'items.shelf').order('count DESC') - locations.each do |location| - if line.item_id - find('tr', text: '%s / %s' % [location.room_name, location.shelf]) - else - find('tr', text: '%dx %s / %s' % [location.count, location.room_name, location.shelf]) - end + '%s / %s' % [line.item.room.name, line.item.shelf] + end + ) + end + when 'available quantity x Room / Shelf' + find( + 'table thead tr td.location', + text: '%s x %s / %s' % [_('available quantity'), _('Room'), _('Shelf')] + ) + reservations = @selected_lines_by_date ? @selected_lines_by_date : @contract.reservations + reservations.each do |line| + within find('tr', match: :prefer_exact, text: line.model).find('.location') do + if line.model.is_a?(Option) + _('Location not defined') + else + locations = + line.model.items.in_stock.where(inventory_pool_id: @current_inventory_pool).select( + 'COUNT(items.id) AS count, rooms.name AS room_name, items.shelf AS shelf' + ) + .joins(:room) + .group('rooms.id', 'rooms.name', 'items.shelf') + .order('count DESC') + locations.each do |location| + if line.item_id + find('tr', text: '%s / %s' % [location.room_name, location.shelf]) + else + find( + 'tr', text: '%dx %s / %s' % [location.count, location.room_name, location.shelf] + ) end end end end - else - raise + end + else + raise end end end end Then /^one line shows the grand total$/ do - within @list_element.find('.list') do - @total = find('tfoot.total') - end + within @list_element.find('.list') do@total = find('tfoot.total')end end Then /^that shows the totals of the columns:$/ do |table| table.hashes.each do |area| case area['Column'] - when 'Quantity' - expect(@total.find('.quantity', match: :first).has_content? @contract.total_quantity).to be true - when 'Value' - expect(@total.find('.value', match: :first).text.gsub(/\D/, '')).to eq ('%.2f' % @contract.reservations.map(&:price).sum).gsub(/\D/, '') + when 'Quantity' + expect( + @total.find('.quantity', match: :first).has_content? @contract.total_quantity + ).to be true + when 'Value' + expect(@total.find('.value', match: :first).text.gsub(/\D/, '')).to eq ('%.2f' % + @contract.reservations.map(&:price).sum) + .gsub(/\D/, '') end end end When(/^the models in the value list are sorted alphabetically$/) do - names = all('.value_list tbody .model_name').map{|name| name.text} + names = all('.value_list tbody .model_name').map(&:text) expect(names.empty?).to be false expect(names.sort == names).to be true end -Given(/^there is an order with at least two models and at least two items per model were ordered$/) do - @hand_over = @current_inventory_pool.visits.hand_over.detect do |ho| - ho.reservations.where(type: 'OptionLine').exists? and - ho.reservations.where(type: 'ItemLine').exists? and +Given( + /^there is an order with at least two models and at least two items per model were ordered$/ +) do + @hand_over = + @current_inventory_pool.visits.hand_over.detect do |ho| + ho.reservations.where(type: 'OptionLine').exists? and + ho.reservations.where(type: 'ItemLine').exists? and (g = ho.reservations.where(type: 'ItemLine').group_by(&:model_id)) and - g.keys.size >= 2 and - g.values.detect {|x| x.size >= 3} - end + g.keys.size >= 2 and + g.values.detect { |x| x.size >= 3 } + end expect(@hand_over).not_to be_nil @reservations = @hand_over.reservations end When(/^each model has exactly one assigned item$/) do - @models = @reservations.select{|l| l.is_a? ItemLine}.map(&:model) + @models = @reservations.select { |l| l.is_a? ItemLine }.map(&:model) @models.uniq.each do |m| - l = @reservations.find{|l| l.model == m} - l.update_attribute(:item, l.model.borrowable_items.where(inventory_pool_id: @current_inventory_pool).first) unless l.is_a? OptionLine + l = @reservations.find { |l| l.model == m } + unless l.is_a? OptionLine + l.update_attribute( + :item, l.model.borrowable_items.where(inventory_pool_id: @current_inventory_pool).first + ) + end end end @@ -197,24 +226,22 @@ within '#lines' do expect(has_selector?(".line input[type='checkbox']")).to be true case arg1 - when 'order' - @number_of_selected_lines = @order.reservations.size - all(".emboss .row input[type='checkbox']").each {|i| i.click unless i.checked? } - when 'hand over' - @number_of_selected_lines = all(".line input[type='checkbox']").size - @reservations.map(&:id).each do |id| - cb = find(".line[data-id='#{id}'] input[type='checkbox']") - cb.click unless cb.checked? - end + when 'order' + @number_of_selected_lines = @order.reservations.size + all(".emboss .row input[type='checkbox']").each { |i| i.click unless i.checked? } + when 'hand over' + @number_of_selected_lines = all(".line input[type='checkbox']").size + @reservations.map(&:id).each do |id| + cb = find(".line[data-id='#{id}'] input[type='checkbox']") + cb.click unless cb.checked? + end end end end When(/^I open the value list$/) do find('[data-selection-enabled]').find(:xpath, './following-sibling::*').click - document_window = window_opened_by do - click_button _('Print Selection') - end + document_window = window_opened_by { click_button _('Print Selection') } page.driver.browser.switch_to.window(document_window.handle) end @@ -223,58 +250,84 @@ find('tfoot.total .quantity').text == @number_of_selected_lines.to_s end -Then(/^the price shown for the unassigned reservations is equal to the highest price of any of the items of that model within this inventory pool$/) do +Then( + / + ^the price shown for the unassigned reservations is equal to the highest price of any of the items of that model within this inventory pool$ + / +) do @models.each do |m| - reservations = @reservations.select {|l| l.is_a? ItemLine and l.model == m and not l.item.try(:inventory_code)} + reservations = + @reservations.select do |l| + l.is_a? ItemLine and l.model == m and nl.item.try(:inventory_code) + end quantity = reservations.size - line = all('tr', text: m.name).find {|line| line.find('.inventory_code').text == '' } + line = all('tr', text: m.name).find { |line| line.find('.inventory_code').text == '' } if line - price = @reservations.reload.find{|l| not l.item and l.model == m}.price_or_max_price * quantity - formatted_price = ActionController::Base.helpers.number_to_currency(price, format: '%n %u', unit: Setting.first.local_currency_string) + price = + @reservations.reload.find { |l| nl.item and l.model == m }.price_or_max_price * quantity + formatted_price = + ActionController::Base.helpers.number_to_currency( + price, format: '%n %u', unit: Setting.first.local_currency_string + ) line.find('.item_price', text: formatted_price) end end end Then(/^the price shown for the assigned reservations is that of the assigned item$/) do - reservations = @reservations.select {|l| l.item.try(:inventory_code)} + reservations = @reservations.select { |l| l.item.try(:inventory_code) } reservations.each do |line| - formatted_price = ActionController::Base.helpers.number_to_currency(line.price_or_max_price, format: '%n %u', unit: Setting.first.local_currency_string) + formatted_price = + ActionController::Base.helpers.number_to_currency( + line.price_or_max_price, format: '%n %u', unit: Setting.first.local_currency_string + ) find('tr', text: line.item.inventory_code).find('.item_price', text: formatted_price) end end Then(/^the unassigned reservations are summarized$/) do @models.each do |m| - expect(all('tr', text: m.name).select{|line| line.find('.inventory_code').text == '' }.size).to be <= 1 # for models with quantity 1 and an assigned item size == 0, that's why <= 1 + expect( + all('tr', text: m.name).select { |line| line.find('.inventory_code').text == '' }.size + ).to be <= 1 # for models with quantity 1 and an assigned item size == 0, that's why <= 1 end end Then(/^any options are priced according to their price set in the inventory pool$/) do - reservations = @reservations.select {|l| l.is_a? OptionLine } + reservations = @reservations.select { |l| l.is_a? OptionLine } reservations.each do |l| line = find('tr', text: l.model.name) - formatted_price = ActionController::Base.helpers.number_to_currency(@current_inventory_pool.options.find(l.item.id).price * l.quantity, format: '%n %u', unit: Setting.first.local_currency_string) + formatted_price = + ActionController::Base.helpers.number_to_currency( + @current_inventory_pool.options.find(l.item.id).price * l.quantity, + format: '%n %u', unit: Setting.first.local_currency_string + ) line.find('.item_price', text: formatted_price) end end Given(/^there is an order with at least two models and a quantity of at least three per model$/) do customer = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) - @order = FactoryGirl.create(:order, state: :submitted, user: customer, inventory_pool: @current_inventory_pool) + @order = + FactoryGirl.create( + :order, state: :submitted, user: customer, inventory_pool: @current_inventory_pool + ) [FactoryGirl.create(:model), FactoryGirl.create(:model)].each do |model| 3.times do - @order.reservations << FactoryGirl.create(:reservation, - user: customer, - inventory_pool: @current_inventory_pool, - order: @order, - status: :submitted, - model: model) + @order.reservations << + FactoryGirl.create( + :reservation, + user: customer, + inventory_pool: @current_inventory_pool, + order: @order, + status: :submitted, + model: model + ) end end expect(@order).not_to be_nil @reservations = @order.reservations - @models = @reservations.select{|l| l.is_a? ItemLine}.map(&:model) + @models = @reservations.select { |l| l.is_a? ItemLine }.map(&:model) end When(/^I open an order$/) do diff --git a/features/step_definitions/manage/verification_steps.rb b/features/step_definitions/manage/verification_steps.rb index 7e2b11a20d..1177aaeff5 100644 --- a/features/step_definitions/manage/verification_steps.rb +++ b/features/step_definitions/manage/verification_steps.rb @@ -18,7 +18,7 @@ find('.line', match: :first) # clicking on all togglers via javascript is significantly faster than doing it with capybara in this case - page.execute_script %Q( $(".button[data-type='inventory-expander']").click() ) + page.execute_script " $(\".button[data-type='inventory-expander']\").click() " sleep 2 all('.line', visible: true)[0..5].each do |line| @@ -44,9 +44,7 @@ within '#inventory' do all(".line[data-type='model']", minimum: 1).each do |line| if @current_inventory_pool.running_reservations.detect { |rl| rl.model_id == line['data-id'] } - @new_window = window_opened_by do - line.find('.line-actions > a', text: _('Timeline')).click - end + @new_window = window_opened_by { line.find('.line-actions > a', text: _('Timeline')).click } break end end @@ -57,25 +55,24 @@ end When(/^I click on a user's name$/) do - within_window @new_window do - find('div > span', text: 'Destany Smith').click - end + within_window @new_window dofind('div > span', text: 'Destany Smith').clickend end Then(/^there is no link to:$/) do |table| within_window @new_window do within '.timeline-event-bubble-body' do table.raw.flatten.each do |s1| - s2 = case s1 - when 'acknowledge' - _('Acknowledge') - when 'hand over' - _('Hand Over') - when 'take back' - _('Take Back') - else - raise - end + s2 = + case s1 + when 'acknowledge' + _('Acknowledge') + when 'hand over' + _('Hand Over') + when 'take back' + _('Take Back') + else + raise + end expect(has_no_selector?('a', text: s2)).to be true end end @@ -83,7 +80,9 @@ end When(/^I open a submitted order to be verified by a Group Manager$/) do - @contract = @current_inventory_pool.orders.submitted.joins(:reservations).with_verifiable_user_and_model.first + @contract = + @current_inventory_pool.orders.submitted.joins(:reservations).with_verifiable_user_and_model + .first step 'I edit this submitted contract' end @@ -98,7 +97,9 @@ end When(/^I open a hand over editable by the Group Manager$/) do - @contract = @current_inventory_pool.orders.approved.joins(:reservations).with_verifiable_user_and_model.first + @contract = + @current_inventory_pool.orders.approved.joins(:reservations).with_verifiable_user_and_model + .first visit manage_hand_over_path(@current_inventory_pool, @contract.user) expect(has_selector?('#hand-over-view')).to be true step 'the availability is loaded' diff --git a/features/step_definitions/manage/visits_steps.rb b/features/step_definitions/manage/visits_steps.rb index 4d3dd4519f..5df6371435 100644 --- a/features/step_definitions/manage/visits_steps.rb +++ b/features/step_definitions/manage/visits_steps.rb @@ -1,8 +1,6 @@ # -*- encoding : utf-8 -*- -Given(/^I am listing visits$/) do - visit manage_inventory_pool_visits_path @current_inventory_pool -end +Given(/^I am listing visits$/) { visit manage_inventory_pool_visits_path @current_inventory_pool } Then(/^each visit shows a human-readable difference between now and its respective date$/) do extend ActionView::Helpers::DateHelper diff --git a/features/step_definitions/misc_steps.rb b/features/step_definitions/misc_steps.rb index 5933977465..e73e9f2344 100644 --- a/features/step_definitions/misc_steps.rb +++ b/features/step_definitions/misc_steps.rb @@ -1,3 +1 @@ -When(/^I pry$/) do - binding.pry -end +When(/^I pry$/) { binding.pry } diff --git a/features/step_definitions/package_steps.rb b/features/step_definitions/package_steps.rb index 6d7aa6e41c..cf0f4ef4c0 100644 --- a/features/step_definitions/package_steps.rb +++ b/features/step_definitions/package_steps.rb @@ -7,7 +7,7 @@ Given "item '$item' is part of package item $package_item" do |item, package_item| package = Item.find_by_inventory_code package_item - item = Item.find_by_inventory_code item + item = Item.find_by_inventory_code item item.parent = package item.save end @@ -27,9 +27,7 @@ # dummy - has comment only! end -Given(/^this model is a package$/) do - @model.update_attributes(is_package: true) -end +Given(/^this model is a package$/) { @model.update_attributes(is_package: true) } Given(/^this package item is part of this package model$/) do @item.model = @model @@ -47,13 +45,10 @@ end When(/^I choose "(.*?)" from building select box$/) do |name| - fill_in_via_autocomplete \ - css: "[data-id='building_id'] input[data-type='autocomplete']", - value: name + fill_in_via_autocomplete css: "[data-id='building_id'] input[data-type='autocomplete']", + value: name end When(/^I choose "(.*?)" from room select box$/) do |name| - fill_in_via_autocomplete \ - css: "[data-id='room_id'] input[data-type='autocomplete']", - value: name + fill_in_via_autocomplete css: "[data-id='room_id'] input[data-type='autocomplete']", value: name end diff --git a/features/step_definitions/performance_stability_steps.rb b/features/step_definitions/performance_stability_steps.rb index 49acf4c9bc..52b0a3a48b 100644 --- a/features/step_definitions/performance_stability_steps.rb +++ b/features/step_definitions/performance_stability_steps.rb @@ -1,60 +1,64 @@ -Given(/^the model "(.*?)" exists$/) do |arg1| - @model = Model.find_by_name arg1 -end +Given(/^the model "(.*?)" exists$/) { |arg1| @model = Model.find_by_name arg1 } Given(/^it has at least (\d+) items in the current inventory pool$/) do |arg1| arg1.to_i.times do - FactoryGirl.create(:item, - model: @model, - owner: @current_inventory_pool, - supplier: FactoryGirl.create(:supplier, - name: Faker::Lorem.characters(20))) + FactoryGirl.create( + :item, + model: @model, + owner: @current_inventory_pool, + supplier: FactoryGirl.create(:supplier, name: Faker::Lorem.characters(20)) + ) end expect(@model.items.where(inventory_pool_id: @current_inventory_pool).count).to be >= arg1.to_i end Given(/^it has at least (\d+) group partitions in the current inventory pool$/) do |arg1| - (@current_inventory_pool.entitlement_groups - @model.entitlements.map(&:entitlement_group)).take(arg1.to_i).each do |group| - @model.entitlements << Entitlement.create(model: @model, - entitlement_group: group, - quantity: rand(10..20)) + (@current_inventory_pool.entitlement_groups - @model.entitlements.map(&:entitlement_group)).take( + arg1.to_i + ) + .each do |group| + @model.entitlements << + Entitlement.create(model: @model, entitlement_group: group, quantity: rand(10..20)) end expect( - @model - .entitlements - .joins(:entitlement_group) - .where(entitlement_groups: { inventory_pool_id: @current_inventory_pool }) - .count + @model.entitlements.joins(:entitlement_group).where( + entitlement_groups: { inventory_pool_id: @current_inventory_pool } + ) + .count ).to be >= arg1.to_i end -Given(/^it has at least (\d+) (unsubmitted|submitted|approved|signed) reservations in the current inventory pool$/) do |arg1, status| - attrs = { status: status.to_sym, - inventory_pool: @current_inventory_pool, - model: @model } +Given( + / + ^it has at least (\d+) (unsubmitted|submitted|approved|signed) reservations in the current inventory pool$ + / +) do |arg1, status| + attrs = { status: status.to_sym, inventory_pool: @current_inventory_pool, model: @model } arg1.to_i.times do if status.to_sym == :signed attrs[:status] = :approved - attrs[:item] = @model.items.where(inventory_pool_id: @current_inventory_pool).detect{|item| item.reservations.empty? } + attrs[:item] = + @model.items.where(inventory_pool_id: @current_inventory_pool).detect do |item| + item.reservations.empty? + end end attrs[:start_date] = Date.today + rand(0..10).days attrs[:end_date] = Date.today + rand(10..20).days if [:submitted, :rejected, :approved].include? attrs[:status] - user = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool) - order = FactoryGirl.create(:order, - inventory_pool: @current_inventory_pool, - user: user, - state: attrs[:status]) + user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) + order = + FactoryGirl.create( + :order, inventory_pool: @current_inventory_pool, user: user, state: attrs[:status] + ) attrs['order_id'] = order.id attrs['user_id'] = user.id end cl = FactoryGirl.create(:reservation, attrs.merge!(delegated_user: nil)) if status.to_sym == :signed - contract = Contract.sign!(@current_user, @current_inventory_pool, user, [cl], - Faker::Lorem.sentence) + contract = + Contract.sign!(@current_user, @current_inventory_pool, user, [cl], Faker::Lorem.sentence) expect(contract.valid?).to be true end end @@ -63,9 +67,7 @@ When /^its availability is recalculate$/ do require 'benchmark' - @time = Benchmark.measure { - @model.availability_in(@current_inventory_pool) - } + @time = Benchmark.measure { @model.availability_in(@current_inventory_pool) } end Then /^it should take maximum (\d+\.\d+) seconds$/ do |seconds| @@ -73,28 +75,27 @@ expect(@time.real).to be < seconds.to_f end -Given /^approve each submitted contract with more than (.*) reservations should take maximum (.*) seconds$/ do |arg1, seconds| +Given / + ^approve each submitted contract with more than (.*) reservations should take maximum (.*) seconds$ + / do |arg1, seconds| require 'benchmark' seconds = seconds.to_f - contracts = Order.submitted.select do |rb| - rb.reservations.count > arg1.to_i - end + contracts = Order.submitted.select { |rb| rb.reservations.count > arg1.to_i } expect(contracts).not_to be_empty contracts.each do |contract| - time = Benchmark.measure { - contract.approve(Faker::Lorem.sentence) - } + time = Benchmark.measure { contract.approve(Faker::Lorem.sentence) } puts time.real puts contract.inspect if time.real >= seconds expect(time.real).to be < seconds end - end -Then /^approvable check on single approvable reservation should take maximum (\d+\.\d+) seconds$/ do |seconds| +Then / + ^approvable check on single approvable reservation should take maximum (\d+\.\d+) seconds$ + / do |seconds| require 'benchmark' seconds = seconds.to_f @@ -103,9 +104,7 @@ b = false reservations.each do |reservation| - time = Benchmark.measure { - b = reservation.approvable? - } + time = Benchmark.measure { b = reservation.approvable? } puts time.real puts reservation.inspect if time.real >= seconds expect(time.real).to be < seconds @@ -115,7 +114,9 @@ expect(b).to be true end -Then /^availability check on single submitted reservation should take maximum (\d+\.\d+) seconds$/ do |seconds| +Then / + ^availability check on single submitted reservation should take maximum (\d+\.\d+) seconds$ + / do |seconds| require 'benchmark' seconds = seconds.to_f @@ -123,9 +124,7 @@ reservations = Reservation.submitted.limit(200) reservations.each do |reservation| - time = Benchmark.measure { - reservation.available? - } + time = Benchmark.measure { reservation.available? } puts time.real puts reservation.inspect if time.real >= seconds expect(time.real).to be < seconds diff --git a/features/step_definitions/persona_steps.rb b/features/step_definitions/persona_steps.rb index 5d787b07ae..e9fd3fdce8 100644 --- a/features/step_definitions/persona_steps.rb +++ b/features/step_definitions/persona_steps.rb @@ -3,18 +3,26 @@ Given(/^I am ([a-zA-Z]*)$/) do |persona_name| step 'I am logged in as "%s"' % persona_name case persona_name - when 'Andi' - step 'I am in an inventory pool with verifiable orders' - else - @current_inventory_pool = @current_user.inventory_pools.managed.first + when 'Andi' + step 'I am in an inventory pool with verifiable orders' + else + @current_inventory_pool = @current_user.inventory_pools.managed.first end end Given(/^I am a customer with contracts$/) do - user = Reservation.closed.where.not(returned_to_user_id: nil).map(&:user).select{|u| not u.access_rights.active.blank?}.uniq.first + user = + Reservation.closed.where.not(returned_to_user_id: nil).map(&:user).select do |u| + nu.access_rights.active.blank? + end + .uniq + .first step 'I am logged in as "%s"' % user.login end When(/^I am in an inventory pool with verifiable orders$/) do - @current_inventory_pool = @current_user.inventory_pools.managed.find {|ip| not ip.orders.joins(:reservations).with_verifiable_user_and_model.empty? } + @current_inventory_pool = + @current_user.inventory_pools.managed.find do |ip| + nip.orders.joins(:reservations).with_verifiable_user_and_model.empty? + end end diff --git a/features/step_definitions/search_steps.rb b/features/step_definitions/search_steps.rb index 953ec21453..14222086d6 100644 --- a/features/step_definitions/search_steps.rb +++ b/features/step_definitions/search_steps.rb @@ -1,5 +1,5 @@ When 'I sort by "$sort_key"' do |sort_key| - When "I click \"#{sort_key}\"" + When "I click undefined#{sort_key}undefined" end #no-sphinx# @@ -10,5 +10,9 @@ Then 'that number must be the same as the number of search partials' do # see app/views/backend/backend/search/_nilclass.html.erb on why we exclude nilclass - expect(@number).to eq `ls #{Rails.root}/app/views/backend/backend/search | grep -v nilclass | wc -l` + expect(@number).to eq ` + ls + #{Rails.root} + /app/views/backend/backend/search | grep -v nilclass | wc -l + ` end diff --git a/features/step_definitions/settings_steps.rb b/features/step_definitions/settings_steps.rb index 9755347c43..836e08c69f 100644 --- a/features/step_definitions/settings_steps.rb +++ b/features/step_definitions/settings_steps.rb @@ -1,13 +1,14 @@ Given(/^a settings object$/) do @setting = Setting.first - @setting ||= Setting.create({local_currency_string: 'GBP', - email_signature: 'kthxbye', - default_email: 'from@example.com'}) + @setting ||= + Setting.create( + { + local_currency_string: 'GBP', email_signature: 'kthxbye', default_email: 'from@example.com' + } + ) end -Given(/^the settings are existing$/) do - FactoryGirl.create :setting unless Setting.first -end +Given(/^the settings are existing$/) { FactoryGirl.create :setting unless Setting.first } When(/^the settings are not existing$/) do Setting.delete_all @@ -17,4 +18,3 @@ Then(/^there is an error for the missing settings$/) do expect { step 'I go to the home page' }.to raise_error(RuntimeError) end - diff --git a/features/step_definitions/support/helper_methods.rb b/features/step_definitions/support/helper_methods.rb index ac9d0de906..35183b9638 100644 --- a/features/step_definitions/support/helper_methods.rb +++ b/features/step_definitions/support/helper_methods.rb @@ -6,25 +6,29 @@ def fill_in_via_autocomplete(css:, text: nil, value:) def get_rails_model_name_from_url path_array_reversed = current_path.split('/').reverse - model_name = case action = path_array_reversed.first - when 'new' - path_array_reversed[1].chomp('s') - when 'edit' - id = path_array_reversed[1].chomp('s') - path_array_reversed[2].chomp('s') - else - raise 'Unspecified action' - end + model_name = + case action = path_array_reversed.first + when 'new' + path_array_reversed[1].chomp('s') + when 'edit' + id = path_array_reversed[1].chomp('s') + path_array_reversed[2].chomp('s') + else + raise 'Unspecified action' + end - model_name = 'software' if model_name == 'model' and ( current_url =~ /type=software/ or Model.where(id: id, type: 'Software').first ) + if model_name == 'model' and + (current_url =~ /type=software/ or Model.where(id: id, type: 'Software').first) + model_name = 'software' + end model_name end def rescue_displaced_flash begin yield - rescue - find("#flash .fa-times-circle").click + rescue StandardError + find('#flash .fa-times-circle').click retry end end diff --git a/features/step_definitions/take_back_steps.rb b/features/step_definitions/take_back_steps.rb index 6b28f82d94..269882c22a 100644 --- a/features/step_definitions/take_back_steps.rb +++ b/features/step_definitions/take_back_steps.rb @@ -23,9 +23,9 @@ # @contract = assigns(:contract) # end -When "$manager chooses to take back $customer's entry" do | manager, customer | - @user = User.find_by_login( customer ) - get manage_take_back_path( @inventory_pool, @user ) +When "$manager chooses to take back $customer's entry" do |manager, customer| + @user = User.find_by_login(customer) + get manage_take_back_path(@inventory_pool, @user) @reservations = assigns(:reservations) end @@ -38,7 +38,7 @@ # end Then "$who's contract should be closed" do |who| - user = User.find_by_login( who ) + user = User.find_by_login(who) contract = Contract.find_by_user_id user.id expect(contract.status).to eq :closed end diff --git a/features/step_definitions/technical/contract_steps.rb b/features/step_definitions/technical/contract_steps.rb index 9a9d12acad..082228fdc1 100644 --- a/features/step_definitions/technical/contract_steps.rb +++ b/features/step_definitions/technical/contract_steps.rb @@ -1,4 +1,6 @@ -When /^I create an approved contract for "(.*?)" with a contract line without an assigned item$/ do |name| +When / + ^I create an approved contract for "(.*?)" with a contract line without an assigned item$ + / do |name| user = User.where(login: name.downcase).first unless user.access_right_for(@current_inventory_pool) @@ -8,10 +10,9 @@ contract = user.orders.approved.find_by(inventory_pool_id: @current_inventory_pool) expect(contract).to be_nil - @reservation = FactoryGirl.create :reservation, - status: :approved, - inventory_pool: @current_inventory_pool, - user: user + @reservation = + FactoryGirl.create :reservation, + status: :approved, inventory_pool: @current_inventory_pool, user: user @contract = user.orders.approved.find_by(inventory_pool_id: @current_inventory_pool) expect(@contract.reservations.count).to eq 1 diff --git a/features/step_definitions/technical/eval_helpers.rb b/features/step_definitions/technical/eval_helpers.rb index 59d206cab9..e1c25cc932 100644 --- a/features/step_definitions/technical/eval_helpers.rb +++ b/features/step_definitions/technical/eval_helpers.rb @@ -1,4 +1,4 @@ -def exact_match? v +def exact_match?(v) [ 'Faker::Commerce.product_name', 'Faker::Lorem.sentence', @@ -7,7 +7,7 @@ def exact_match? v 'Faker::Name.last_name', 'Faker::Name.first_name', 'Faker::Internet.email', - "Faker::Address.street_address + \", \"", + 'Faker::Address.street_address + ", "', '[true, false].sample', 'Date.today', 'Date.yesterday', @@ -17,7 +17,7 @@ def exact_match? v .include?(v) end -def regex_match? v +def regex_match?(v) [ /^rand\(\d{1}\.\.\d{,3}\)$/, /^rand\(\d{,3}\)$/, @@ -27,15 +27,15 @@ def regex_match? v .any? { |r| r.match v } end -def allowed_code? v +def allowed_code?(v) exact_match? v or regex_match? v end -def nilify_empty_string v +def nilify_empty_string(v) v unless v.empty? end -def substitute_with_eval v +def substitute_with_eval(v) match = /(#\{(.*)\})/.match(v) if match if allowed_code?($2) @@ -48,8 +48,6 @@ def substitute_with_eval v end end -def hashes_with_evaled_and_nilified_values table - table.hashes.map do |h| - h.each { |k, v| h[k] = nilify_empty_string(substitute_with_eval v) } - end +def hashes_with_evaled_and_nilified_values(table) + table.hashes.map { |h| h.each { |k, v| h[k] = nilify_empty_string(substitute_with_eval v) } } end diff --git a/features/step_definitions/technical/field_steps.rb b/features/step_definitions/technical/field_steps.rb index aa3e098b79..b9712ad6bc 100644 --- a/features/step_definitions/technical/field_steps.rb +++ b/features/step_definitions/technical/field_steps.rb @@ -1,37 +1,50 @@ Given /^test data setup for =Provision of accessible fields= feature$/ do @inventory_pool = FactoryGirl.create :inventory_pool - @minimum_field_size = Field.all.select {|f| f.data['permissions'].nil? }.size + @minimum_field_size = Field.all.select { |f| f.data['permissions'].nil? }.size end Given /^a user with role (\w+) exists$/ do |manager_role| @user = FactoryGirl.create(:user) @manager_role = manager_role.to_sym - @user.access_rights << FactoryGirl.create(:access_right, role: @manager_role, user: @user, inventory_pool: @inventory_pool) + @user.access_rights << + FactoryGirl.create( + :access_right, role: @manager_role, user: @user, inventory_pool: @inventory_pool + ) end When /^you get the accessible fields for this user$/ do - @accessible_fields = Field.all.select {|f| f.accessible_by? @user, @inventory_pool } + @accessible_fields = Field.all.select { |f| f.accessible_by? @user, @inventory_pool } end Then /^the user has access to at least all the fields without any permissions$/ do expect(@accessible_fields.size).to be >= @minimum_field_size end -Then /^the amount of the accessible fields (.*) (\w+) can be different$/ do |compare_op, higher_manager_role| +Then / + ^the amount of the accessible fields (.*) (\w+) can be different$ + / do |compare_op, higher_manager_role| user_role = @user.access_right_for(@inventory_pool).role expect(user_role).to eq @manager_role user_role_level = AccessRight::ROLES_HIERARCHY.index user_role unless @accessible_fields.empty? - @accessible_fields.each {|field| - expect(AccessRight::ROLES_HIERARCHY.index(field.data['permissions']['role'])).to be <= user_role_level if field['permissions'] and field['permissions']['role'] - } + @accessible_fields.each do |field| + if field['permissions'] and field['permissions']['role'] + expect(AccessRight::ROLES_HIERARCHY.index(field.data['permissions']['role'])).to be <= + user_role_level + end + end end # create a user with higher level @higher_user = FactoryGirl.create(:user) - @higher_user.access_rights << FactoryGirl.create(:access_right, role: higher_manager_role.to_sym, user: @higher_user, inventory_pool: @inventory_pool) + @higher_user.access_rights << + FactoryGirl.create( + :access_right, + role: higher_manager_role.to_sym, user: @higher_user, inventory_pool: @inventory_pool + ) # create also data for an higher level - @higher_accessible_fields = Field.all.select {|f| f.accessible_by? @higher_user, @inventory_pool } + @higher_accessible_fields = + Field.all.select { |f| f.accessible_by? @higher_user, @inventory_pool } # check that the same condition holds true also for higher level expect(@higher_accessible_fields.size).to be >= @minimum_field_size @@ -48,26 +61,17 @@ Then /^each field provides the value of the item's attribute$/ do Field.all.each do |field| - expected_value = Array(field.data['attribute']).inject(@item) do |r, m| - if r.is_a?(Hash) - r[m] - else - if m == 'id' - r - else - r.try(:send, m) - end + expected_value = + Array(field.data['attribute']).inject(@item) do |r, m| + r.is_a?(Hash) ? r[m] : m == 'id' ? r : r.try(:send, m) end - end expect(field.value(@item)).to eq expected_value end end -Then /^each field is capable of providing values even if its values attribute is a lambda\/proc$/ do - Field.all.each do |field| - if field.values - expect(field.values).not_to be_nil - end - end +Then %r{ + ^each field is capable of providing values even if its values attribute is a lambda\/proc$ + } do + Field.all.each { |field| expect(field.values).not_to be_nil if field.values } end diff --git a/features/step_definitions/technical/fields_controller_steps.rb b/features/step_definitions/technical/fields_controller_steps.rb index ba76c42493..65c39250e7 100644 --- a/features/step_definitions/technical/fields_controller_steps.rb +++ b/features/step_definitions/technical/fields_controller_steps.rb @@ -4,9 +4,10 @@ end Then /^the accessible fields of the logged in user include each field from the json response$/ do - accessible_fields = Field.all.select {|f| f.accessible_by?(@current_user, @current_inventory_pool) || f.id == 'inventory_code'} + accessible_fields = + Field.all.select do |f| + f.accessible_by?(@current_user, @current_inventory_pool) || f.id == 'inventory_code' + end accessible_fields_ids = accessible_fields.map &:id - @json.each do |field| - expect(accessible_fields_ids.include?(field['id'])).to be true - end + @json.each { |field| expect(accessible_fields_ids.include?(field['id'])).to be true } end diff --git a/features/step_definitions/technical/inventory_pool_steps.rb b/features/step_definitions/technical/inventory_pool_steps.rb index 7418db1f71..aab8173fb4 100644 --- a/features/step_definitions/technical/inventory_pool_steps.rb +++ b/features/step_definitions/technical/inventory_pool_steps.rb @@ -55,11 +55,11 @@ def start_third_reservation_on_different_date!(reservations) User.delete_all - %W(le_mac eichen_berge birke venger siegfried).each do |login_name| + %W[le_mac eichen_berge birke venger siegfried].each do |login_name| LeihsFactory.create_user login: login_name end - @manager = LeihsFactory.create_user({login: 'hammer'}, {role: :lending_manager}) + @manager = LeihsFactory.create_user({ login: 'hammer' }, { role: :lending_manager }) end Given /^all contracts and contract reservations are deleted$/ do @@ -68,15 +68,17 @@ def start_third_reservation_on_different_date!(reservations) end Given /^there are open contracts for all users$/ do - @open_reservations = User.all.flat_map do |user| - rand(3..6).times.map do - order = FactoryGirl.create(:order, - user: user, - inventory_pool: @current_inventory_pool, - state: :approved) - FactoryGirl.create :reservation, order: order, user: user, inventory_pool: @current_inventory_pool, status: :approved + @open_reservations = + User.all.flat_map do |user| + rand(3..6).times.map do + order = + FactoryGirl.create( + :order, user: user, inventory_pool: @current_inventory_pool, state: :approved + ) + FactoryGirl.create :reservation, + order: order, user: user, inventory_pool: @current_inventory_pool, status: :approved + end end - end end Given /^every contract has a different start date$/ do @@ -91,17 +93,23 @@ def start_third_reservation_on_different_date!(reservations) @hand_over_visits.flat_map(&:reservations) end -Then /^the result is a set of contract reservations that are associated with the users' contracts$/ do +Then / + ^the result is a set of contract reservations that are associated with the users' contracts$ + / do expect(@hand_over_visits.to_a.size).to eq @open_reservations.count # NOTE count returns a Hash because the group() in default scope end Given /^there is an open contract with reservations for a user$/ do user = User.first - order = FactoryGirl.create(:order, - user: user, - inventory_pool: @current_inventory_pool, - state: :approved) - @open_reservations = rand(3..6).times.map { FactoryGirl.create :reservation, order: order, user: user, inventory_pool: @current_inventory_pool, status: :approved } + order = + FactoryGirl.create( + :order, user: user, inventory_pool: @current_inventory_pool, state: :approved + ) + @open_reservations = + rand(3..6).times.map do + FactoryGirl.create :reservation, + order: order, user: user, inventory_pool: @current_inventory_pool, status: :approved + end end Given /^the first contract line starts on the same date as the second one$/ do @@ -116,28 +124,42 @@ def start_third_reservation_on_different_date!(reservations) @hand_over_visits = @current_inventory_pool.visits.hand_over end -Then /^the first two contract reservations should now be grouped inside the first visit, which makes it two visits in total$/ do +Then / + ^the first two contract reservations should now be grouped inside the first visit, which makes it two visits in total$ + / do expect(@hand_over_visits.to_a.size).to eq 2 # NOTE count returns a Hash because the group() in default scope end Given /^there are 2 different contracts for 2 different users$/ do - @open_reservation0 = FactoryGirl.create :reservation, user: User.first, inventory_pool: @current_inventory_pool, status: :approved - @open_reservation1 = FactoryGirl.create :reservation, user: User.last, inventory_pool: @current_inventory_pool, status: :approved + @open_reservation0 = + FactoryGirl.create :reservation, + user: User.first, inventory_pool: @current_inventory_pool, status: :approved + @open_reservation1 = + FactoryGirl.create :reservation, + user: User.last, inventory_pool: @current_inventory_pool, status: :approved end Given /^there are 2 different contracts with reservations for 2 different users$/ do user2 = User.first - order2 = FactoryGirl.create(:order, - user: user2, - inventory_pool: @current_inventory_pool, - state: :approved) - @open_reservations2 = rand(3..6).times.map { FactoryGirl.create :reservation, order: order2, user: user2, inventory_pool: @current_inventory_pool, status: :approved } + order2 = + FactoryGirl.create( + :order, user: user2, inventory_pool: @current_inventory_pool, state: :approved + ) + @open_reservations2 = + rand(3..6).times.map do + FactoryGirl.create :reservation, + order: order2, user: user2, inventory_pool: @current_inventory_pool, status: :approved + end user3 = User.last - order3 = FactoryGirl.create(:order, - user: user3, - inventory_pool: @current_inventory_pool, - state: :approved) - @open_reservations3 = rand(3..6).times.map { FactoryGirl.create :reservation, order: order3, user: user3, inventory_pool: @current_inventory_pool, status: :approved } + order3 = + FactoryGirl.create( + :order, user: user3, inventory_pool: @current_inventory_pool, state: :approved + ) + @open_reservations3 = + rand(3..6).times.map do + FactoryGirl.create :reservation, + order: order3, user: user3, inventory_pool: @current_inventory_pool, status: :approved + end end Then /^there are 2 hand over visits for the given inventory pool$/ do @@ -148,12 +170,16 @@ def start_third_reservation_on_different_date!(reservations) expect(@current_inventory_pool.visits.take_back.reload.to_a.size).to eq 2 # NOTE count returns a Hash because the group() in default scope end -Given /^1st contract line of 2nd contract has the same start date as the 1st contract line of the 1st contract$/ do +Given / + ^1st contract line of 2nd contract has the same start date as the 1st contract line of the 1st contract$ + / do @open_reservation1.start_date = @open_reservation0.start_date @open_reservation1.save end -Given /^1st contract line of 2nd contract has the same end date as the 1st contract line of the 1st contract$/ do +Given / + ^1st contract line of 2nd contract has the same end date as the 1st contract line of the 1st contract$ + / do @open_reservations3[0].end_date = @open_reservations2[0].end_date @open_reservations3[0].save end @@ -165,7 +191,7 @@ def start_third_reservation_on_different_date!(reservations) Then /^there should be different visits for 2 users with same start and end date$/ do expected = 2 - expect(@current_inventory_pool.visits.hand_over.reload.to_a.size).to eq expected # NOTE count returns a Hash because the group() in default scope + expect(@current_inventory_pool.visits.hand_over.reload.to_a.size).to eq expected end Given /^make sure no end date is identical to any other$/ do @@ -181,14 +207,18 @@ def start_third_reservation_on_different_date!(reservations) Given /^the contract is signed$/ do # sign the contract - Contract.sign!(@manager, @current_inventory_pool, @open_reservations.first.user, @open_reservations, - Faker::Lorem.sentence) + Contract.sign!( + @manager, + @current_inventory_pool, + @open_reservations.first.user, + @open_reservations, + Faker::Lorem.sentence + ) end Given /^all contracts are signed$/ do @open_reservations.group_by(&:user).each_pair do |user, reservations| - Contract.sign!(@manager, @current_inventory_pool, user, reservations, - Faker::Lorem.sentence) + Contract.sign!(@manager, @current_inventory_pool, user, reservations, Faker::Lorem.sentence) end end @@ -204,7 +234,9 @@ def start_third_reservation_on_different_date!(reservations) @take_back_lines = @take_back_visits.flat_map(&:reservations) end -Then /^one should get the set of contract reservations that are associated with the users' contracts$/ do +Then / + ^one should get the set of contract reservations that are associated with the users' contracts$ + / do expect(@take_back_lines.count).to eq @open_reservations.count end @@ -216,7 +248,9 @@ def start_third_reservation_on_different_date!(reservations) end_third_reservation_on_different_date! @open_reservations end -Then /^the first 2 contract reservations should be grouped inside the 1st visit, which makes it two visits in total$/ do +Then / + ^the first 2 contract reservations should be grouped inside the 1st visit, which makes it two visits in total$ + / do expect(@take_back_visits.to_a.size).to eq 2 # NOTE count returns a Hash because the group() in default scope end @@ -229,40 +263,48 @@ def start_third_reservation_on_different_date!(reservations) Given /^to each contract line of both contracts an item is assigned$/ do [@open_reservations2, @open_reservations3].each do |c| # assign contract reservations - c.each do |cl| - cl.update_attributes(item: cl.model.items.borrowable.in_stock.first) - end + c + .each { |cl| cl.update_attributes(item: cl.model.items.borrowable.in_stock.first) } end end Given /^both contracts are signed$/ do [@open_reservations2, @open_reservations3].each do |reservations| # sign the contract - Contract.sign!(@manager, @current_inventory_pool, reservations.first.user, reservations, - Faker::Lorem.sentence) + Contract + .sign!( + @manager, + @current_inventory_pool, + reservations.first.user, + reservations, + Faker::Lorem.sentence + ) end end -Then /^the first 2 contract reservations should now be grouped inside the 1st visit, which makes it 2 visits in total$/ do +Then / + ^the first 2 contract reservations should now be grouped inside the 1st visit, which makes it 2 visits in total$ + / do expect(@take_back_visits.to_a.size).to eq 2 # NOTE count returns a Hash because the group() in default scope end Given(/^a maximum amount of visits is defined for a week day$/) do - @inventory_pool = @current_user.inventory_pools.detect { |ip| not ip.workday.max_visits.empty? } + @inventory_pool = @current_user.inventory_pools.detect { |ip| nip.workday.max_visits.empty? } expect(@inventory_pool).not_to be_nil end Then(/^the amount of visits includes$/) do |table| date = @inventory_pool.visits.potential_hand_over.sample.date - total_visits = table.raw.flatten.sum do |k| - case k + total_visits = + table.raw.flatten.sum do |k| + case k when 'potential hand overs (not yet acknowledged orders)' - @inventory_pool.visits.potential_hand_over.select{|v| v.date == date}.size + @inventory_pool.visits.potential_hand_over.select { |v| v.date == date }.size when 'hand overs' @inventory_pool.visits.hand_over.where(date: date).to_a.size # NOTE count returns a Hash because the group() in default scope when 'take backs' @inventory_pool.visits.take_back.where(date: date).to_a.size # NOTE count returns a Hash because the group() in default scope + end end - end expect(@inventory_pool.workday.total_visits_by_date[date].size).to eq total_visits end diff --git a/features/step_definitions/technical/item_steps.rb b/features/step_definitions/technical/item_steps.rb index 948c9adc01..3bf8821d62 100644 --- a/features/step_definitions/technical/item_steps.rb +++ b/features/step_definitions/technical/item_steps.rb @@ -1,7 +1,5 @@ Given /^there are some items$/ do - 3.times do - FactoryGirl.create :item - end + 3.times { FactoryGirl.create :item } end When /^I search for a text not present anywhere$/ do diff --git a/features/step_definitions/technical/ldap_hslu_steps.rb b/features/step_definitions/technical/ldap_hslu_steps.rb index d517badc19..212070a1a4 100644 --- a/features/step_definitions/technical/ldap_hslu_steps.rb +++ b/features/step_definitions/technical/ldap_hslu_steps.rb @@ -1,203 +1,230 @@ require 'cucumber/rspec/doubles' Given(/^the LDAP\-HSLU authentication system is enabled and configured$/) do - as = AuthenticationSystem.new(name: 'HsluAuthentication', - class_name: 'HsluAuthentication') + as = AuthenticationSystem.new(name: 'HsluAuthentication', class_name: 'HsluAuthentication') as.is_active = true expect(as.save).to be true Setting::LDAP_CONFIG = File.join(Rails.root, 'features', 'data', 'LDAP_hslu.yml') end Given(/^an LDAP response object for HSLU is mocked$/) do - # So we can overwrite the @myhash of LDAP entries and construct a hash of Net::LDAP::Entry just - # like the real Net::LDAP would - class Net::LDAP::Entry - attr_accessor :myhash - end - - normal_user_hash = {samaccountname: ['normal_user'], - whenchanged: ['20130402061617.0Z'], - mail: ['testbenutzer@doesnot.exist'], - lastlogontimestamp: ['130093569778872747'], - pwdlastset: ['130080675766612153'], - department: ['Test & Integration'], - telephonenumber: ['041 999 99 99'], - samaccounttype: ['805306368'], - codepage: ['0'], - displayname: ['Test Benutzer testuser'], - primarygroupid: ['513'], - company: ['Hochschule Test'], - givenname: ['Test'], - userprincipalname: ['testuser@campus.intern'], - countrycode: ['756'], - usncreated: ['75556046'], - sn: ['Benutzer'], - dn: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - objectsid: ['BINARY DATA HERE'], - streetaddress: ['Musterstrasse 1, Postfach 999'], - distinguishedname: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - title: ['ICT-Test-Benutzer'], - cn: ['Test Benutzer testuser'], - ipphone: ['9999'], - badpasswordtime: ['0'], - memberof: ['CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern'], - l: ['Musterstadt'], - objectclass: ['top', 'person', 'organizationalPerson', 'user'], - accountexpires: ['130171032000000000'], - objectguid: ['BINARY DATA HERE'], - instancetype: ['4'], - st: ['Luzern'], - c: ['CH'], - objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], - lastlogoff: ['0'], - name: ['Test Benutzer testuser'], - usnchanged: ['77641778'], - postalcode: ['9999'], - logoncount: ['0'], - useraccountcontrol: ['66048'], - whencreated: ['20130318080616.0Z'], - description: ['Testuser für Leihs / vor 18.3.2013'], - pager: ['L9999'], - dscorepropagationdata: ['16010101000000.0Z'], - lastlogon: ['0'], - co: ['Switzerland'], - physicaldeliveryofficename: ['999']} - - normal_user_entry = Net::LDAP::Entry.new - normal_user_entry.myhash = normal_user_hash - normal_user_result = [ - normal_user_entry - ] - - video_user_hash = {samaccountname: ['video_user'], - mail: ['testbenutzer@doesnot.exist'], - department: ['Test & Integration'], - telephonenumber: ['041 999 99 99'], - samaccounttype: ['805306368'], - codepage: ['0'], - displayname: ['DK.BA_VID'], - primarygroupid: ['513'], - company: ['Hochschule Test'], - givenname: ['Test'], - userprincipalname: ['testuser@campus.intern'], - sn: ['Benutzer'], - dn: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - objectsid: ['BINARY DATA HERE'], - streetaddress: ['Musterstrasse 1, Postfach 999'], - distinguishedname: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - title: ['ICT-Test-Benutzer'], - cn: ['Test Benutzer testuser'], - ipphone: ['9999'], - memberof: ['CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern'], - l: ['Musterstadt'], - objectclass: ['top', 'person', 'organizationalPerson', 'user'], - st: ['Luzern'], - c: ['CH'], - objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], - name: ['Test Benutzer testuser'], - postalcode: ['9999'], - pager: ['L2345'], - co: ['Switzerland'] - } - - video_user_entry = Net::LDAP::Entry.new - video_user_entry.myhash = video_user_hash - video_user_result = [ - video_user_entry - ] - - numeric_unique_id_user_hash = {samaccountname: ['numeric_unique_id_user'], - mail: ['testbenutzer@doesnot.exist'], - department: ['Test & Integration'], - telephonenumber: ['041 999 99 99'], - displayname: ['DK.BA_VID'], - primarygroupid: ['513'], - company: ['Hochschule Test'], - givenname: ['Test'], - userprincipalname: ['testuser@campus.intern'], - countrycode: ['756'], - sn: ['Benutzer'], - dn: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - objectsid: ['BINARY DATA HERE'], - streetaddress: ['Musterstrasse 1, Postfach 999'], - distinguishedname: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - title: ['ICT-Test-Benutzer'], - cn: ['Test Benutzer testuser'], - ipphone: ['9999'], - badpasswordtime: ['0'], - memberof: ['CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern'], - l: ['Musterstadt'], - objectclass: ['top', 'person', 'organizationalPerson', 'user'], - instancetype: ['4'], - st: ['Luzern'], - c: ['CH'], - objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], - lastlogoff: ['0'], - name: ['Test Benutzer testuser'], - postalcode: ['9999'], - logoncount: ['0'], - description: ['Testuser für Leihs / vor 18.3.2013'], - pager: ['1234'], - co: ['Switzerland'] - } - - numeric_unique_id_user_entry = Net::LDAP::Entry.new - numeric_unique_id_user_entry.myhash = numeric_unique_id_user_hash - numeric_unique_id_user_result = [ - numeric_unique_id_user_entry - ] - - - - admin_user_hash = {samaccountname: ['admin_user'], - mail: ['testbenutzer@doesnot.exist'], - department: ['Test & Integration'], - telephonenumber: ['041 999 99 99'], - samaccounttype: ['805306368'], - codepage: ['0'], - displayname: ['DK.BA_VID'], - primarygroupid: ['513'], - company: ['Hochschule Test'], - givenname: ['Test'], - userprincipalname: ['testuser@campus.intern'], - sn: ['Benutzer'], - dn: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - objectsid: ['BINARY DATA HERE'], - streetaddress: ['Musterstrasse 1, Postfach 999'], - distinguishedname: ['CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern'], - title: ['ICT-Test-Benutzer'], - cn: ['Test Benutzer testuser'], - ipphone: ['9999'], - memberof: ['CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern', 'CN=blah,OU=diblah,OU=diblahblah,OU=p_ma,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern'], - l: ['Musterstadt'], - objectclass: ['top', 'person', 'organizationalPerson', 'user'], - st: ['Luzern'], - c: ['CH'], - objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], - name: ['Test Benutzer testuser'], - postalcode: ['9999'], - pager: ['L2345'], - co: ['Switzerland'] - } - - admin_user_entry = Net::LDAP::Entry.new - admin_user_entry.myhash = admin_user_hash - admin_user_result = [ - admin_user_entry - ] - - - - mocked_ldap = double('mocked_ldap') - allow(mocked_ldap).to receive(:bind).with(any_args).and_return(true) - allow(mocked_ldap).to receive(:search).with({base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'normal_user')}).and_return(normal_user_result) - allow(mocked_ldap).to receive(:search).with({base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'video_user')}).and_return(video_user_result) - allow(mocked_ldap).to receive(:search).with({base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'numeric_unique_id_user')}).and_return(numeric_unique_id_user_result) - allow(mocked_ldap).to receive(:search).with({base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'admin_user')}).and_return(admin_user_result) - - allow(Net::LDAP).to receive(:new) { - mocked_ldap - } + # So we can overwrite the @myhash of LDAP entries and construct a hash of Net::LDAP::Entry just + # like the real Net::LDAP would + class Net::LDAP::Entry + attr_accessor :myhash + end + + normal_user_hash = { + samaccountname: ['normal_user'], + whenchanged: ['20130402061617.0Z'], + mail: ['testbenutzer@doesnot.exist'], + lastlogontimestamp: ['130093569778872747'], + pwdlastset: ['130080675766612153'], + department: ['Test & Integration'], + telephonenumber: ['041 999 99 99'], + samaccounttype: ['805306368'], + codepage: ['0'], + displayname: ['Test Benutzer testuser'], + primarygroupid: ['513'], + company: ['Hochschule Test'], + givenname: ['Test'], + userprincipalname: ['testuser@campus.intern'], + countrycode: ['756'], + usncreated: ['75556046'], + sn: ['Benutzer'], + dn: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + objectsid: ['BINARY DATA HERE'], + streetaddress: ['Musterstrasse 1, Postfach 999'], + distinguishedname: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + title: ['ICT-Test-Benutzer'], + cn: ['Test Benutzer testuser'], + ipphone: ['9999'], + badpasswordtime: ['0'], + memberof: [ + 'CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + l: ['Musterstadt'], + objectclass: ['top', 'person', 'organizationalPerson', 'user'], + accountexpires: ['130171032000000000'], + objectguid: ['BINARY DATA HERE'], + instancetype: ['4'], + st: ['Luzern'], + c: ['CH'], + objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], + lastlogoff: ['0'], + name: ['Test Benutzer testuser'], + usnchanged: ['77641778'], + postalcode: ['9999'], + logoncount: ['0'], + useraccountcontrol: ['66048'], + whencreated: ['20130318080616.0Z'], + description: ['Testuser für Leihs / vor 18.3.2013'], + pager: ['L9999'], + dscorepropagationdata: ['16010101000000.0Z'], + lastlogon: ['0'], + co: ['Switzerland'], + physicaldeliveryofficename: ['999'] + } + + normal_user_entry = Net::LDAP::Entry.new + normal_user_entry.myhash = normal_user_hash + normal_user_result = [normal_user_entry] + + video_user_hash = { + samaccountname: ['video_user'], + mail: ['testbenutzer@doesnot.exist'], + department: ['Test & Integration'], + telephonenumber: ['041 999 99 99'], + samaccounttype: ['805306368'], + codepage: ['0'], + displayname: ['DK.BA_VID'], + primarygroupid: ['513'], + company: ['Hochschule Test'], + givenname: ['Test'], + userprincipalname: ['testuser@campus.intern'], + sn: ['Benutzer'], + dn: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + objectsid: ['BINARY DATA HERE'], + streetaddress: ['Musterstrasse 1, Postfach 999'], + distinguishedname: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + title: ['ICT-Test-Benutzer'], + cn: ['Test Benutzer testuser'], + ipphone: ['9999'], + memberof: [ + 'CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + l: ['Musterstadt'], + objectclass: ['top', 'person', 'organizationalPerson', 'user'], + st: ['Luzern'], + c: ['CH'], + objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], + name: ['Test Benutzer testuser'], + postalcode: ['9999'], + pager: ['L2345'], + co: ['Switzerland'] + } + + video_user_entry = Net::LDAP::Entry.new + video_user_entry.myhash = video_user_hash + video_user_result = [video_user_entry] + + numeric_unique_id_user_hash = { + samaccountname: ['numeric_unique_id_user'], + mail: ['testbenutzer@doesnot.exist'], + department: ['Test & Integration'], + telephonenumber: ['041 999 99 99'], + displayname: ['DK.BA_VID'], + primarygroupid: ['513'], + company: ['Hochschule Test'], + givenname: ['Test'], + userprincipalname: ['testuser@campus.intern'], + countrycode: ['756'], + sn: ['Benutzer'], + dn: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + objectsid: ['BINARY DATA HERE'], + streetaddress: ['Musterstrasse 1, Postfach 999'], + distinguishedname: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + title: ['ICT-Test-Benutzer'], + cn: ['Test Benutzer testuser'], + ipphone: ['9999'], + badpasswordtime: ['0'], + memberof: [ + 'CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + l: ['Musterstadt'], + objectclass: ['top', 'person', 'organizationalPerson', 'user'], + instancetype: ['4'], + st: ['Luzern'], + c: ['CH'], + objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], + lastlogoff: ['0'], + name: ['Test Benutzer testuser'], + postalcode: ['9999'], + logoncount: ['0'], + description: ['Testuser für Leihs / vor 18.3.2013'], + pager: ['1234'], + co: ['Switzerland'] + } + + numeric_unique_id_user_entry = Net::LDAP::Entry.new + numeric_unique_id_user_entry.myhash = numeric_unique_id_user_hash + numeric_unique_id_user_result = [numeric_unique_id_user_entry] + + admin_user_hash = { + samaccountname: ['admin_user'], + mail: ['testbenutzer@doesnot.exist'], + department: ['Test & Integration'], + telephonenumber: ['041 999 99 99'], + samaccounttype: ['805306368'], + codepage: ['0'], + displayname: ['DK.BA_VID'], + primarygroupid: ['513'], + company: ['Hochschule Test'], + givenname: ['Test'], + userprincipalname: ['testuser@campus.intern'], + sn: ['Benutzer'], + dn: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + objectsid: ['BINARY DATA HERE'], + streetaddress: ['Musterstrasse 1, Postfach 999'], + distinguishedname: [ + 'CN=Test Benutzer testuser,OU=ma_nopol,OU=p_ma,OU=p_user,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + title: ['ICT-Test-Benutzer'], + cn: ['Test Benutzer testuser'], + ipphone: ['9999'], + memberof: [ + 'CN=u_all_ad_deny,OU=p_administration,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern', + 'CN=blah,OU=diblah,OU=diblahblah,OU=p_ma,OU=p_group,OU=prod,OU=hslu,DC=campus,DC=intern' + ], + l: ['Musterstadt'], + objectclass: ['top', 'person', 'organizationalPerson', 'user'], + st: ['Luzern'], + c: ['CH'], + objectcategory: ['CN=Person,CN=Schema,CN=Configuration,DC=campus,DC=intern'], + name: ['Test Benutzer testuser'], + postalcode: ['9999'], + pager: ['L2345'], + co: ['Switzerland'] + } + + admin_user_entry = Net::LDAP::Entry.new + admin_user_entry.myhash = admin_user_hash + admin_user_result = [admin_user_entry] + + mocked_ldap = double('mocked_ldap') + allow(mocked_ldap).to receive(:bind).with(any_args).and_return(true) + allow(mocked_ldap).to receive(:search).with( + { base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'normal_user') } + ) + .and_return(normal_user_result) + allow(mocked_ldap).to receive(:search).with( + { base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'video_user') } + ) + .and_return(video_user_result) + allow(mocked_ldap).to receive(:search).with( + { base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'numeric_unique_id_user') } + ) + .and_return(numeric_unique_id_user_result) + allow(mocked_ldap).to receive(:search).with( + { base: anything, filter: Net::LDAP::Filter.eq('samaccountname', 'admin_user') } + ) + .and_return(admin_user_result) + + allow(Net::LDAP).to receive(:new) { mocked_ldap } end Given(/^a group called "(.*?)" exists$/) do |groupname| @@ -205,7 +232,7 @@ class Net::LDAP::Entry end When(/^I log in as HSLU-LDAP user "(.*?)"$/) do |username| - post 'authenticator/hslu/login', {login: { username: username, password: '1234' }}, {} + post 'authenticator/hslu/login', { login: { username: username, password: '1234' } }, {} end Then(/^the user "(.*?)" should have HSLU-LDAP as an authentication system$/) do |username| @@ -217,4 +244,3 @@ class Net::LDAP::Entry Then(/^the user "(.*?)" should have a badge ID of "(.*?)"$/) do |username, badge_id| expect(User.where(login: username).first.badge_id).to eq badge_id end - diff --git a/features/step_definitions/technical/ldap_steps.rb b/features/step_definitions/technical/ldap_steps.rb index 5db2fee821..7c338cc910 100644 --- a/features/step_definitions/technical/ldap_steps.rb +++ b/features/step_definitions/technical/ldap_steps.rb @@ -6,15 +6,13 @@ end When(/^there are some inventory pools with automatic access enabled$/) do - 3.times do - FactoryGirl.create :inventory_pool - end - ips_with_automatic_access = InventoryPool.limit(2) - ips_with_automatic_access.each {|ip| ip.update_attributes automatic_access: true} + 3.times { FactoryGirl.create :inventory_pool } + ips_with_automatic_access = InventoryPool.limit(2) + ips_with_automatic_access.each { |ip| ip.update_attributes automatic_access: true } end When(/^I log in as LDAP user "(.*?)"$/) do |username| - post 'authenticator/ldap/login', {login: { user: username, password: 'pass' }}, {} + post 'authenticator/ldap/login', { login: { user: username, password: 'pass' } }, {} end Then(/^a leihs user should exist for "(.*?)"$/) do |username| @@ -23,14 +21,14 @@ Then(/^the user "(.*?)" should (not have any|have) admin privileges$/) do |username, arg1| user = User.where(login: username).first - b = case arg1 - when 'not have any' - access_rights = user.access_rights.where(role: 'customer') - expect(access_rights.count).to be > 0 - false - when 'have' - true - end + b = + case arg1 + when 'not have any' + access_rights = user.access_rights.where(role: 'customer') + expect(access_rights.count).to be > 0 + false + when 'have' + true + end expect(user.is_admin).to be b end - diff --git a/features/step_definitions/technical/mailer_steps.rb b/features/step_definitions/technical/mailer_steps.rb index 2475a20bb7..e751048783 100644 --- a/features/step_definitions/technical/mailer_steps.rb +++ b/features/step_definitions/technical/mailer_steps.rb @@ -1,6 +1,6 @@ When(/^the mail delivery method is set to "(.*?)"$/) do |method| ApplicationRecord.connection.execute <<-SQL - UPDATE settings SET mail_delivery_method = '#{method}' + UPDATE settings SET mail_delivery_method = '#{method}' SQL expect(Setting.first.mail_delivery_method).to eq method end @@ -11,14 +11,14 @@ When(/^the SMTP username is set to "(.*?)"$/) do |username| ApplicationRecord.connection.execute <<-SQL - UPDATE settings SET smtp_username = '#{username}' + UPDATE settings SET smtp_username = '#{username}' SQL expect(Setting.first.smtp_username).to eq username end When(/^the SMTP password is set to "(.*?)"$/) do |password| ApplicationRecord.connection.execute <<-SQL - UPDATE settings SET smtp_password = '#{password}' + UPDATE settings SET smtp_password = '#{password}' SQL expect(Setting.first.smtp_password).to eq password end diff --git a/features/step_definitions/technical/model_steps.rb b/features/step_definitions/technical/model_steps.rb index 5a7c15495a..85c55fb94e 100644 --- a/features/step_definitions/technical/model_steps.rb +++ b/features/step_definitions/technical/model_steps.rb @@ -11,9 +11,7 @@ When /^the quantity of items of a user for a specific model is retrieved$/ do @quantities_1 = [] @users.each do |user| - @models.each do |model| - @quantities_1 << user.items.where(model_id: model).count - end + @models.each { |model| @quantities_1 << user.items.where(model_id: model).count } end end diff --git a/features/step_definitions/technical/order_steps.rb b/features/step_definitions/technical/order_steps.rb index ad767a85c7..13670b47ca 100644 --- a/features/step_definitions/technical/order_steps.rb +++ b/features/step_definitions/technical/order_steps.rb @@ -1,4 +1,6 @@ -When /^'(.*)' orders (\d+) '(.*)' from inventory pool (\d+)( for the same time)?$/ do |who, quantity, model_name, ip, same_time| +When / + ^'(.*)' orders (\d+) '(.*)' from inventory pool (\d+)( for the same time)?$ + / do |who, quantity, model_name, ip, same_time| @user = User.find_by_login who model = Model.find_by_name(model_name) inventory_pool = InventoryPool.find_by_name(ip) @@ -9,24 +11,30 @@ end quantity.to_i.times do - FactoryGirl.create(:reservation, - status: :unsubmitted, - model: model, - inventory_pool: inventory_pool, - user: @user, - start_date: @start_date, - end_date: @end_date) + FactoryGirl.create( + :reservation, + status: :unsubmitted, + model: model, + inventory_pool: inventory_pool, + user: @user, + start_date: @start_date, + end_date: @end_date + ) end end When /^all reservations of '(.*)' are submitted$/ do |who| expect(@user.reservations.unsubmitted.reload).not_to be_empty - @user.reservations.unsubmitted.group_by(&:inventory_pool).each_pair do |inventory_pool, reservations| - order = FactoryGirl.create(:order, - inventory_pool: inventory_pool, - user: @user, - purpose: "this is the required purpose", - state: :submitted) + @user.reservations.unsubmitted.group_by(&:inventory_pool) + .each_pair do |inventory_pool, reservations| + order = + FactoryGirl.create( + :order, + inventory_pool: inventory_pool, + user: @user, + purpose: 'this is the required purpose', + state: :submitted + ) reservations.each do |reservation| reservation.update_attributes(status: :submitted, order: order) end @@ -41,7 +49,7 @@ end Then /it asks for ([0-9]+) item(s?)$/ do |number, s| - total = @orders.map {|o| o.reservations.sum(:quantity) }.sum + total = @orders.map { |o| o.reservations.sum(:quantity) }.sum expect(total).to eq number.to_i end @@ -53,26 +61,33 @@ @no_of_lines_at_start = no_of_lines.to_i status = contract_type.downcase.to_sym - user = @inventory_pool.users.detect {|u| u.orders.where(inventory_pool_id: @inventory_pool, status: status).empty? } + user = + @inventory_pool.users.detect do |u| + u.orders.where(inventory_pool_id: @inventory_pool, status: status).empty? + end expect(user).not_to be_nil - @no_of_lines_at_start.times.map { FactoryGirl.create :reservation, user: user, inventory_pool: @inventory_pool, status: status } + @no_of_lines_at_start.times.map do + FactoryGirl.create :reservation, user: user, inventory_pool: @inventory_pool, status: status + end @contract = user.orders.find_by(inventory_pool_id: @inventory_pool, status: status) end Given /^there is a "(SIGNED|CLOSED)" contract with reservations?$/ do |contract_type| status = contract_type.downcase.to_sym - @contract = FactoryGirl.create("#{contract_type.downcase}_contract", inventory_pool: @inventory_pool) + @contract = + FactoryGirl.create("#{contract_type.downcase}_contract", inventory_pool: @inventory_pool) @no_of_lines_at_start = @contract.reservations.count end When /^one tries to delete a line$/ do - @result_of_line_removal = begin - l = @contract.reservations.last.destroy - l.destroyed? - rescue - false - end + @result_of_line_removal = + begin + l = @contract.reservations.last.destroy + l.destroyed? + rescue StandardError + false + end end Then /^the amount of reservations decreases by one$/ do @@ -88,7 +103,11 @@ end Given /^required test data for contract tests existing$/ do - @inventory_pool = InventoryPool.all.detect {|ip| ip.users.customers.exists? and ip.reservations.unsubmitted.exists? and ip.reservations.submitted.exists? } + @inventory_pool = + InventoryPool.all.detect do |ip| + ip.users.customers.exists? and ip.reservations.unsubmitted.exists? and + ip.reservations.submitted.exists? + end @model_with_items = @inventory_pool.items.sample.model end @@ -108,27 +127,17 @@ end Given /^an? (submitted|unsubmitted) contract with reservations existing$/ do |arg1| - User.all.detect do |user| - @contract = user.orders.where(status: arg1).sample - end + User.all.detect { |user| @contract = user.orders.where(status: arg1).sample } end Given(/^a submitted contract with approvable reservations exists$/) do - User.all.detect do |user| - @contract = \ - user - .orders - .where(status: :submitted) - .detect { |rb| rb.approvable? } - end + User.all.detect { |user| @contract = user.orders.where(status: :submitted).detect(&:approvable?) } end When /^I approve the contract of the borrowing user$/ do b = @contract.approve('That will be fine.', true, @current_user) expect(b).to be true - @contract.reservations.each do |reservation| - expect(reservation.reload.status).to eq :approved - end + @contract.reservations.each { |reservation| expect(reservation.reload.status).to eq :approved } end Then /^the borrowing user gets one confirmation email$/ do @@ -146,7 +155,5 @@ end Then /^each line associated with the contract must have the same purpose description$/ do - @contract.reservations.each do |l| - expect(l.purpose.description).to eq @purpose - end + @contract.reservations.each { |l| expect(l.purpose.description).to eq @purpose } end diff --git a/features/step_definitions/technical/orders_controller_steps.rb b/features/step_definitions/technical/orders_controller_steps.rb index aa4261b722..c9a2dc79bf 100644 --- a/features/step_definitions/technical/orders_controller_steps.rb +++ b/features/step_definitions/technical/orders_controller_steps.rb @@ -3,13 +3,13 @@ @inventory_pool = @lending_manager.inventory_pools.first end -When /^the index action of the contracts controller is called with the filter parameter "(.*?)"$/ do |arg1| - response = get manage_contracts_path(@inventory_pool), {status: arg1, format: 'json'} +When / + ^the index action of the contracts controller is called with the filter parameter "(.*?)"$ + / do |arg1| + response = get manage_contracts_path(@inventory_pool), { status: arg1, format: 'json' } @json = JSON.parse response.body end Then /^the result of this action are all submitted contracts for the given inventory pool$/ do - @json.each do |contract| - expect(contract['status'].to_sym).to eq :submitted - end + @json.each { |contract| expect(contract['status'].to_sym).to eq :submitted } end diff --git a/features/step_definitions/technical/shibboleth_steps.rb b/features/step_definitions/technical/shibboleth_steps.rb index a1d35cf7f9..5e62ba5c28 100644 --- a/features/step_definitions/technical/shibboleth_steps.rb +++ b/features/step_definitions/technical/shibboleth_steps.rb @@ -7,27 +7,34 @@ When(/^I log in as Shibboleth user "(.*?)"$/) do |username| # Set an environment variables on the request, since that's how Shibboleth rolls - env = { 'uid' => username, - 'mail' => Faker::Internet.email, - 'givenName' => Faker::Name.first_name, - 'surname' => Faker::Name.last_name } + env = { + 'uid' => username, + 'mail' => Faker::Internet.email, + 'givenName' => Faker::Name.first_name, + 'surname' => Faker::Name.last_name + } get 'authenticator/shibboleth/login', nil, env end -Then(/^the user "(.*?)" should have "(.*?)" as an authentication system$/) do |username, class_name| +Then( + /^the user "(.*?)" should have "(.*?)" as an authentication system$/ +) do |username, class_name| as = AuthenticationSystem.where(class_name: class_name).first expect(as).not_to be_nil expect(User.where(login: username).first.authentication_system).to eq as end When(/^a Shibboleth configuration file with missing "(.*?)" setting is used$/) do |fieldname| - Setting::SHIBBOLETH_CONFIG = File.join(Rails.root, 'features', 'data', "shibboleth_missing_#{fieldname}.yml") + Setting::SHIBBOLETH_CONFIG = + File.join(Rails.root, 'features', 'data', "shibboleth_missing_#{fieldname}.yml") end Then(/^the missing field "(.*?)" should raise an error$/) do |fieldname| controller = Authenticator::ShibbolethAuthenticationController.new - expect { controller.load_config } - .to raise_error(RuntimeError, "Shibboleth configuration file is invalid or not present: The Shibboleth configuration file is missing the '#{fieldname}' setting.") + expect { controller.load_config }.to raise_error( + RuntimeError, + "Shibboleth configuration file is invalid or not present: The Shibboleth configuration file is missing the '#{fieldname}' setting." + ) end When(/^a complete Shibboleth configuration file is used$/) do diff --git a/features/step_definitions/technical/user_steps.rb b/features/step_definitions/technical/user_steps.rb index 390ac80ecf..cf0c3db245 100644 --- a/features/step_definitions/technical/user_steps.rb +++ b/features/step_definitions/technical/user_steps.rb @@ -1,5 +1,12 @@ -Given(/^there are at least (\d+) users with late take backs from at least (\d+) inventory pools where automatic suspension is activated$/) do |users_n, ips_n| - @reservations = Reservation.signed.where('end_date < ?', Date.today).distinct { |cl| cl.inventory_pool and cl.user } +Given( + / + ^there are at least (\d+) users with late take backs from at least (\d+) inventory pools where automatic suspension is activated$ + / +) do |users_n, ips_n| + @reservations = + Reservation.signed.where('end_date < ?', Date.today).distinct do |cl| + cl.inventory_pool and cl.user + end expect(@reservations.count).to be >= 2 end @@ -7,7 +14,9 @@ User.remind_and_suspend_all end -Then(/^every such user is suspended until '(\d+)\.(\d+)\.(\d+)' in the corresponding inventory pool$/) do |day, month, year| +Then( + /^every such user is suspended until '(\d+)\.(\d+)\.(\d+)' in the corresponding inventory pool$/ +) do |day, month, year| @reservations.each do |c| ip = c.inventory_pool u = c.user @@ -25,7 +34,6 @@ end end - Then(/^a user with login "(.*?)" exists$/) do |arg1| @user = User.find_by(login: arg1) expect(@user).not_to be nil @@ -37,13 +45,14 @@ Given(/^the following users exist$/) do |table| hashes_with_evaled_and_nilified_values(table).each do |hash_row| - - attrs = {language: Language.find_by_locale_name(hash_row['language']), - firstname: hash_row['firstname'], - lastname: hash_row['lastname'], - login: hash_row['login'] || hash_row['firstname'].downcase, - email: hash_row['email'], - address: hash_row['address']} + attrs = { + language: Language.find_by_locale_name(hash_row['language']), + firstname: hash_row['firstname'], + lastname: hash_row['lastname'], + login: hash_row['login'] || hash_row['firstname'].downcase, + email: hash_row['email'], + address: hash_row['address'] + } FactoryGirl.create(:user, attrs) end diff --git a/features/step_definitions/technical/visit_steps.rb b/features/step_definitions/technical/visit_steps.rb index 5862c403cf..b983ae43d6 100644 --- a/features/step_definitions/technical/visit_steps.rb +++ b/features/step_definitions/technical/visit_steps.rb @@ -3,7 +3,7 @@ def object_with_sign_state?(object, sign_state) end Given /^there are "(.*?)" visits$/ do |visit_type| - if visit_type == 'overdue' then + if visit_type == 'overdue' step 'there are "hand over" visits' @visits = @visits.where('date < ?', Date.today) else @@ -16,31 +16,31 @@ def object_with_sign_state?(object, sign_state) expect(@visits.all? { |visit| object_with_sign_state? visit, contract_state }).to be true end -Then /^(each of the reservations|at least one line) of such contract must also be "(.*?)"$/ do |arg1, line_state| +Then / + ^(each of the reservations|at least one line) of such contract must also be "(.*?)"$ + / do |arg1, line_state| @visits.each do |visit| - m = case arg1 - when 'each of the reservations' - :all? - when 'at least one line' - :any? - end - t = visit.reservations.send(m) do |line| - object_with_sign_state? line, line_state - end + m = + case arg1 + when 'each of the reservations' + :all? + when 'at least one line' + :any? + end + t = visit.reservations.send(m) { |line| object_with_sign_state? line, line_state } expect(t).to be true end end Then /^every visit with date < today is overdue$/ do - expect(@visits.all?{ |visit| visit.date < Date.today }).to be true + expect(@visits.all? { |visit| visit.date < Date.today }).to be true end Then(/^the other reservations of such contract must be "(.*?)"$/) do |line_state| @visits.each do |visit| - signed_lines, other_lines = visit.reservations.partition {|line| object_with_sign_state? line, 'signed' } - unless other_lines.empty? - other_lines.all? {|line| object_with_sign_state? line, line_state } - end + signed_lines, other_lines = + visit.reservations.partition { |line| object_with_sign_state? line, 'signed' } + other_lines.all? { |line| object_with_sign_state? line, line_state } unless other_lines.empty? end end diff --git a/features/step_definitions/technical/visits_controller_steps.rb b/features/step_definitions/technical/visits_controller_steps.rb index 64edc32995..d4748b3971 100644 --- a/features/step_definitions/technical/visits_controller_steps.rb +++ b/features/step_definitions/technical/visits_controller_steps.rb @@ -4,19 +4,42 @@ end Given /^test data setup for scenario "Writing an unavailable inventory code"$/ do - model = @inventory_pool.models.detect do |m| - m.reservations.joins(:contract).where(contracts: {inventory_pool_id: @inventory_pool}, returned_date: nil, item_id: nil).exists? and - m.reservations.joins(:contract).where(contracts: {inventory_pool_id: @inventory_pool}, returned_date: nil).where.not(item_id: nil).exists? - end + model = + @inventory_pool.models.detect do |m| + m.reservations.joins(:contract).where( + contracts: { inventory_pool_id: @inventory_pool }, returned_date: nil, item_id: nil + ) + .exists? and + m.reservations.joins(:contract).where( + contracts: { inventory_pool_id: @inventory_pool }, returned_date: nil + ) + .where + .not(item_id: nil) + .exists? + end expect(model).not_to be_nil - @line = model.reservations.joins(:contract).where(contracts: {inventory_pool_id: @inventory_pool}, returned_date: nil, item_id: nil).first + @line = + model.reservations.joins(:contract).where( + contracts: { inventory_pool_id: @inventory_pool }, returned_date: nil, item_id: nil + ) + .first expect(@line).not_to eq nil - @item = model.reservations.joins(:contract).where(contracts: {inventory_pool_id: @inventory_pool}, returned_date: nil).where.not(item_id: nil).first.item + @item = + model.reservations.joins(:contract).where( + contracts: { inventory_pool_id: @inventory_pool }, returned_date: nil + ) + .where + .not(item_id: nil) + .first + .item expect(@line.item).to eq nil end When /^an unavailable inventory code is assigned to a contract line$/ do - @response = post "/manage/#{@inventory_pool.id}/reservations/#{@line.id}/assign", {inventory_code: @item.inventory_code} + @response = + post "/manage/#{@inventory_pool.id}/reservations/#{@line.id}/assign", { + inventory_code: @item.inventory_code + } end Then /^the response from this action should( not)? be successful$/ do |arg1| @@ -28,14 +51,15 @@ end Given /^visit that is (.*)$/ do |arg1| - sign = case arg1 - when 'overdue' - '<' - when 'in future' - '>=' - else - raise - end + sign = + case arg1 + when 'overdue' + '<' + when 'in future' + '>=' + else + raise + end @visit = @inventory_pool.visits.hand_over.where("date #{sign} ?", Date.today).first end @@ -44,25 +68,30 @@ expect(@visit_count).to eq Visit.count + 1 end -When /^the index action of the visits controller is called with the filter parameter "(hand over|take back)" and a given date$/ do |arg1| +When / + ^the index action of the visits controller is called with the filter parameter "(hand over|take back)" and a given date$ + / do |arg1| @date = Date.today - path = case arg1 - when 'hand over' - "/manage/#{@inventory_pool.id}/visits/hand_overs.json" - when 'take back' - "/manage/#{@inventory_pool.id}/visits/take_backs.json" - end - response = get path, {date: @date.to_s, date_comparison: 'lteq'} + path = + case arg1 + when 'hand over' + "/manage/#{@inventory_pool.id}/visits/hand_overs.json" + when 'take back' + "/manage/#{@inventory_pool.id}/visits/take_backs.json" + end + response = get path, { date: @date.to_s, date_comparison: 'lteq' } @json = JSON.parse response.body end -Then /^the result of this action are all (hand over|take back) visits for the given inventory pool and the given date$/ do |arg1| +Then / + ^the result of this action are all (hand over|take back) visits for the given inventory pool and the given date$ + / do |arg1| expect(@json.empty?).to be false @json.each do |visit| - expect(visit['action']).to eq arg1.gsub(/\s/,'_') + expect(visit['action']).to eq arg1.gsub(/\s/, '_') if @date <= Date.today expect(Date.parse(visit['date'])).to be <= @date - else + else expect(Date.parse(visit['date'])).to eq @date end end diff --git a/features/step_definitions/user_management_steps.rb b/features/step_definitions/user_management_steps.rb index da814f5381..6fc1392f49 100644 --- a/features/step_definitions/user_management_steps.rb +++ b/features/step_definitions/user_management_steps.rb @@ -4,22 +4,23 @@ @user = User.where(is_admin: true).first end -Given /^a customer "([^"]*)"( exists)?$/ do |name,foo| - @user = LeihsFactory.create_user({login: name }, - {role: :customer, - inventory_pool: @inventory_pool}) +Given /^a customer "([^"]*)"( exists)?$/ do |name, foo| + @user = + LeihsFactory.create_user({ login: name }, { role: :customer, inventory_pool: @inventory_pool }) r = @user.access_rights.active.first r.save end -Given /a (\w+) '([^']*)' for inventory pool '([^']*)'$/ do |role,who,ip_name| +Given /a (\w+) '([^']*)' for inventory pool '([^']*)'$/ do |role, who, ip_name| step "inventory pool '#{ip_name}'" role = role.to_sym expect(role).not_to be_nil - @user = LeihsFactory.create_user({login: who}, - {role: role, - inventory_pool: InventoryPool.find_by_name(ip_name), - password: 'pass' }) + @user = + LeihsFactory.create_user( + { login: who }, { + role: role, inventory_pool: InventoryPool.find_by_name(ip_name), password: 'pass' + } + ) @user.save! end @@ -28,18 +29,15 @@ end Given "customer '$who' has access to inventory pool $ip_s" do |who, ip_s| - inventory_pools = ip_s.split(' and ').collect { | ip_name | - InventoryPool.find_by_name ip_name - } + inventory_pools = ip_s.split(' and ').collect { |ip_name| InventoryPool.find_by_name ip_name } user = User.find_by_login(who) || FactoryGirl.create(:user, login: who) - inventory_pools.each { |ip| + inventory_pools.each do |ip| LeihsFactory.define_role(user, ip, :customer) expect(user.inventory_pools.include?(ip)).to be true - } + end end -When /^I create a new user '([^']*)' at '([^']*)'( in ')?([^']*)'?$/ \ -do |name,email,filler,ip| +When /^I create a new user '([^']*)' at '([^']*)'( in ')?([^']*)'?$/ do |name, email, filler, ip| step "I create a new inventory pool '#{ip}'" unless ip.blank? # TODO: for some reason, cucumber sometimes won't properly clean up @@ -54,6 +52,6 @@ click_button 'Submit' end -Given "'$name' has password '$pass'" do |name,pass| +Given "'$name' has password '$pass'" do |name, pass| LeihsFactory.create_db_auth(login: name, password: pass) end diff --git a/features/step_definitions/view_steps.rb b/features/step_definitions/view_steps.rb index 343dd9aa7c..03dc4f0006 100644 --- a/features/step_definitions/view_steps.rb +++ b/features/step_definitions/view_steps.rb @@ -6,7 +6,7 @@ # response.should render_template("backend/#{title}/index") #end -Then "I see the '$title' list" do | title | +Then "I see the '$title' list" do |title| expect(has_selector?('.buttons .activated', text: title)).to be true expect(has_selector?('.table-overview .fresh')).to be true diff --git a/features/step_definitions/web_extra_steps.rb b/features/step_definitions/web_extra_steps.rb index 6c0b6f1b62..70a6c97c99 100644 --- a/features/step_definitions/web_extra_steps.rb +++ b/features/step_definitions/web_extra_steps.rb @@ -20,22 +20,26 @@ When /^I follow the sloppy link "([^"]*)"(?: within "([^"]*)")?$/ do |text, selector| with_scope(selector) do - - # Capybara has no regex matching on click_link, and we + # Capybara has no regex matching on click_link, and we # have quite sloppy links containing images, numbers, elks # and bananas between the tags. This can match them all. # Well, maybe not the elks. - find('a', text: /.*#{text}.*/i).click -true + find('a', text: /.*#{text}.*/).click + true end end When /^I follow the sloppy link "([^"]*)" in the greybox$/ do |text| - # Wait for the frame to finish appearing - expect(has_selector?('#GB_frame', visible: true)).to be true + expect( + has_selector?( + # Wait for the frame to finish appearing + '#GB_frame', + visible: true + ) + ).to be true within_frame 'GB_frame' do - step "I follow the sloppy link \"#{text}\"" + step "I follow the sloppy link undefined#{text}undefined" end end @@ -50,19 +54,18 @@ end # using this step with 'within' has not been tested yet! -Then /^"([^"]*)" should appear before "([^"]*)"(?: within "([^"]*)")?$/ do -|first, second, selector| +Then / + ^"([^"]*)" should appear before "([^"]*)"(?: within "([^"]*)")?$ + / do |first, second, selector| step 'I wait for the spinner to disappear' - with_scope(selector) do - page.body.index(first).should < page.body.index(second) - end + with_scope(selector) { page.body.index(first).should < page.body.index(second) } end When 'I wait for the spinner to disappear' do # capybara black magic - wait for div to become invisible - expect(has_xpath?( "//div[@id='loading_panel']", visible: false)).to be true + expect(has_xpath?("//div[@id='loading_panel']", visible: false)).to be true end When 'I remove the flash' do - find("#flash .fa-times-circle").click + find('#flash .fa-times-circle').click end diff --git a/features/step_definitions/web_steps.rb b/features/step_definitions/web_steps.rb index 5eba5bad4d..5056010202 100644 --- a/features/step_definitions/web_steps.rb +++ b/features/step_definitions/web_steps.rb @@ -18,7 +18,6 @@ # * http://elabs.se/blog/15-you-re-cuking-it-wrong # - require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), '..', 'support', 'paths')) @@ -36,43 +35,25 @@ def with_scope(locator) # visit path_to(page_name) #end -When(/^(?:|I )go to (.+)$/) do |page_name| - visit path_to(page_name) -end +When(/^(?:|I )go to (.+)$/) { |page_name| visit path_to(page_name) } -When(/^(?:|I )am on (.+)$/) do |page_name| - expect(current_path).to eq path_to(page_name) -end +When(/^(?:|I )am on (.+)$/) { |page_name| expect(current_path).to eq path_to(page_name) } -When(/^(?:|I )press "([^"]*)"$/) do |button| - click_button(button) -end +When(/^(?:|I )press "([^"]*)"$/) { |button| click_button(button) } -When(/^(?:|I )follow "([^"]*)"$/) do |link| - click_link(link) -end +When(/^(?:|I )follow "([^"]*)"$/) { |link| click_link(link) } -When(/^(?:|I )fill in "([^"]*)" with "([^"]*)"$/) do |field, value| - fill_in(field, with: value) -end +When(/^(?:|I )fill in "([^"]*)" with "([^"]*)"$/) { |field, value| fill_in(field, with: value) } -When(/^(?:|I )fill in "([^"]*)" for "([^"]*)"$/) do |value, field| - fill_in(field, with: value) -end +When(/^(?:|I )fill in "([^"]*)" for "([^"]*)"$/) { |value, field| fill_in(field, with: value) } -When(/^(?:|I )select "([^"]*)" from "([^"]*)"$/) do |value, field| - select(value, from: field) -end +When(/^(?:|I )select "([^"]*)" from "([^"]*)"$/) { |value, field| select(value, from: field) } -When(/^(?:|I )choose "([^"]*)"$/) do |field| - choose(field) -end +When(/^(?:|I )choose "([^"]*)"$/) { |field| choose(field) } -Then(/^(?:|I )should see "([^"]*)"$/) do |text| - page.has_content?(text) -end +Then(/^(?:|I )should see "([^"]*)"$/) { |text| page.has_content?(text) } -Then(/^(?:|I )should see \/([^\/]*)\/$/) do |regexp| +Then(%r{^(?:|I )should see \/([^\/]*)\/$}) do |regexp| regexp = Regexp.new(regexp) if page.respond_to? :should @@ -90,7 +71,7 @@ def with_scope(locator) end end -Then(/^(?:|I )should not see \/([^\/]*)\/$/) do |regexp| +Then(%r{^(?:|I )should not see \/([^\/]*)\/$}) do |regexp| regexp = Regexp.new(regexp) if page.respond_to? :should @@ -120,10 +101,6 @@ def with_scope(locator) end end -Then(/^show me the page$/) do - save_and_open_page # rubocop:disable Lint/Debugger -end +Then(/^show me the page$/) { save_and_open_page } # rubocop:disable Lint/Debugger -Then(/^I accept the flash message$/) do - find("#flash .fa-times-circle").click -end +Then(/^I accept the flash message$/) { find('#flash .fa-times-circle').click } diff --git a/features/step_definitions/work_days_steps.rb b/features/step_definitions/work_days_steps.rb index 06b31717ac..ec983d4b82 100644 --- a/features/step_definitions/work_days_steps.rb +++ b/features/step_definitions/work_days_steps.rb @@ -1,4 +1,5 @@ -Given '$ip has default workdays' do +Given '$ip has default workdays' do + end Given 'inventory_pool is open on $days' do |days| @@ -18,17 +19,21 @@ Given 'holidays are from $startdate - $finished because of $reason' do |startdate, finish, reason| ip = LeihsFactory.create_inventory_pool - ip.holidays << Holiday.new(start_date: LeihsFactory.parsedate(startdate), - end_date: LeihsFactory.parsedate(finish), - name: reason) - ip.save + ip.holidays << + Holiday.new( + start_date: LeihsFactory.parsedate(startdate), + end_date: LeihsFactory.parsedate(finish), + name: reason + ) + ip.save end Given '$date is free because of $reason' do |date, reason| ip = LeihsFactory.create_inventory_pool - ip.holidays << Holiday.new(start_date: LeihsFactory.parsedate(date), - end_date: LeihsFactory.parsedate(date), - name: reason) + ip.holidays << + Holiday.new( + start_date: LeihsFactory.parsedate(date), end_date: LeihsFactory.parsedate(date), name: reason + ) ip.save end @@ -45,16 +50,19 @@ When '$who try to order an item for $date' do |who, date| inventory_pool, inv_manager, user, model = LeihsFactory.create_dataset_simple - # Login + # Login post login_path(login: user.login) step "I am logged in as '#{user.login}' with password '#{nil}'" @current_user.reservations.unsubmitted.delete_all if @reservations get borrow_root_path - @response = post borrow_reservations_path(model_id: model.id, - quantity: 1, - inventory_pool_id: inventory_pool.id, - start_date: date, - end_date: date) + @response = + post borrow_reservations_path( + model_id: model.id, + quantity: 1, + inventory_pool_id: inventory_pool.id, + start_date: date, + end_date: date + ) @reservations = @current_user.reservations.unsubmitted.where(inventory_pool_id: inventory_pool) end @@ -77,7 +85,7 @@ expect(line.save).to be true end -When 'trying to set the end date to the same date' do +When 'trying to set the end date to the same date' do line = @reservations.first line.end_date = LeihsFactory.parsedate(@date) @save_successful = line.save @@ -93,14 +101,13 @@ other_days.delete(day.strip) expect(@workday.send(day.strip)).to be true end - + other_days.each do |day| -# if @workday.send(day) == true -# puts "****************" -# puts @workday.inspect -# puts "****************" -# end - expect(@workday.send(day)).to be false + expect( + # end + @workday + .send(day) + ).to be false end end diff --git a/features/support/common_steps.rb b/features/support/common_steps.rb index 281a12f28f..2379a39f99 100644 --- a/features/support/common_steps.rb +++ b/features/support/common_steps.rb @@ -7,11 +7,11 @@ end Given 'resolved by $who on $date' do |who, date| - # do nothing + end Given /^reported by (.*) on (.*)/ do |who, date| - # do nothing + end Given /pending - (?!reported by)(.*)/ do |explanation| @@ -26,13 +26,13 @@ # It needs to be eventually migrated from culerity to capybara all the same When /I fill in (\w+) of "([^\"]*)" with "([^\"]*)"/ do |order, field, value| text_fields = $browser.text_fields - matching = text_fields.find_all { |t| t.id.match( field ) } + matching = text_fields.find_all { |t| t.id.match(field) } matching[order.to_i].set(value) end # Date changing hackery When 'I beam into the future to $date' do |date| - Dataset.back_to_date( LeihsFactory.parsedate( date ) ) + Dataset.back_to_date(LeihsFactory.parsedate(date)) end When 'I beam back into the present' do @@ -40,9 +40,7 @@ end Given(/^today corresponds to the start date of the order$/) do - if @contract - Dataset.back_to_date @contract.min_date - end + Dataset.back_to_date @contract.min_date if @contract visit current_path # reload the page in order to travel in time also in browser end @@ -53,26 +51,21 @@ end Then 'I close the flash message if visible' do - flash = first("#flash") - if flash - flash.find(".fa-times-circle").click - end + flash = first('#flash') + flash.find('.fa-times-circle').click if flash end When 'I scroll loading all pages' do sleep 2 - all('.page[data-page]').each do |data_page| - data_page.click - data_page.find('.line div', match: :first) - end + all('.page[data-page]').each(&:click) end Then 'I scroll to the end of the list' do - page.execute_script "window.scrollBy(0,10000)" + page.execute_script 'window.scrollBy(0,10000)' end Then 'I scroll to the end of the order list twice' do find('.list-of-lines .line', match: :first) - page.execute_script "window.scrollBy(0,10000)" - page.execute_script "window.scrollBy(0,10000)" + page.execute_script 'window.scrollBy(0,10000)' + page.execute_script 'window.scrollBy(0,10000)' end diff --git a/features/support/dataset.rb b/features/support/dataset.rb index d0c10a7a8d..95e9f712a9 100644 --- a/features/support/dataset.rb +++ b/features/support/dataset.rb @@ -12,11 +12,7 @@ def back_to_date(datetime = nil) mode = ENV['TIMECOP_MODE'] || :travel Timecop.send(mode, datetime) else - if ENV['TEST_DATETIME'] - back_to_date(Time.parse(ENV['TEST_DATETIME'])) - else - Timecop.return - end + ENV['TEST_DATETIME'] ? back_to_date(Time.parse(ENV['TEST_DATETIME'])) : Timecop.return end end @@ -35,6 +31,6 @@ def use_test_datetime srand(test_datetime) back_to_date(Time.parse(TEST_DATETIME)) - puts "\n ------------------------- TEST_DATETIME=#{TEST_DATETIME} -------------------------" + puts "undefined ------------------------- TEST_DATETIME=#{TEST_DATETIME} -------------------------" end end diff --git a/features/support/env.rb b/features/support/env.rb index c400d3abd2..c540e9e54a 100644 --- a/features/support/env.rb +++ b/features/support/env.rb @@ -59,15 +59,14 @@ Before('@ldap') do ENV['TMPDIR'] = File.join(Rails.root, 'tmp') # TODO: Move this out to something that runs *before* the test suite itself? - unless File.exist?(ENV['TMPDIR']) - Dir.mkdir(ENV['TMPDIR']) - end + Dir.mkdir(ENV['TMPDIR']) unless File.exist?(ENV['TMPDIR']) Setting::LDAP_CONFIG = File.join(Rails.root, 'features', 'data', 'LDAP_generic.yml') - @ldap_server = Ladle::Server.new( - port: 12345, - ldif: File.join(Rails.root, 'features', 'data', 'ldif', 'generic.ldif'), - domain: 'dc=example,dc=org' - ) + @ldap_server = + Ladle::Server.new( + port: 12345, + ldif: File.join(Rails.root, 'features', 'data', 'ldif', 'generic.ldif'), + domain: 'dc=example,dc=org' + ) @ldap_server.start end @@ -78,12 +77,10 @@ end Before do - Cucumber.logger.info "Current capybara driver: %s\n" % Capybara.current_driver + Cucumber.logger.info 'Current capybara driver: %sundefined' % Capybara.current_driver Dataset.restore_dump end ################################################################################## -After('@ldap') do - @ldap_server.stop -end +After('@ldap') { @ldap_server.stop } diff --git a/features/support/env_screenshots.rb b/features/support/env_screenshots.rb index ec499fa9d2..2b31f9e63e 100644 --- a/features/support/env_screenshots.rb +++ b/features/support/env_screenshots.rb @@ -1,23 +1,27 @@ def take_screenshot - @screenshot_dir ||= Rails.root.join('tmp','capybara') - Dir.mkdir @screenshot_dir rescue nil - path= @screenshot_dir.join("screenshot_#{Time.zone.now.iso8601.gsub(/:/,'-')}.png") + @screenshot_dir ||= Rails.root.join('tmp', 'capybara') + begin + Dir.mkdir @screenshot_dir + rescue StandardError + nil + end + path = @screenshot_dir.join("screenshot_#{Time.zone.now.iso8601.gsub(/:/, '-')}.png") case Capybara.current_driver when :selenium_firefox - page.driver.browser.save_screenshot(path) rescue nil + begin + page.driver.browser.save_screenshot(path) + rescue StandardError + nil + end else Rails.logger.warn "Taking screenshots is not implemented for #{Capybara.current_driver}." end end -After do |scenario| - take_screenshot if scenario.failed? -end +After { |scenario| take_screenshot if scenario.failed? } -AfterStep do |scenario| - if t = scenario.instance_eval{@tags} - if t.tags.map(&:name).include? '@take_screenshots' - take_screenshot - end +AfterStep do |scenario| + if t = scenario.instance_eval { @tags } + take_screenshot if t.tags.map(&:name).include? '@take_screenshots' end end diff --git a/features/support/helper.rb b/features/support/helper.rb index 6c517da182..eb558474dc 100644 --- a/features/support/helper.rb +++ b/features/support/helper.rb @@ -3,39 +3,36 @@ def link2(attributes) "#{attributes['name']}" end - def find_line(model) id = 0 - @contract.reservations.each do |line| - if model == line.model.name - return line - end - end + @contract.reservations.each { |line| return line if model == line.model.name } nil end def available_quantities_between(from, to, available_quantities) if available_quantities.count == 1 - if from >= available_quantities.first.date - return available_quantities - else - return [] - end + from >= available_quantities.first.date ? return available_quantities : return [] else - aq = available_quantities.select do |available_quantity| - available_quantity.date >= from and available_quantity.date <= to - end + aq = + available_quantities.select do |available_quantity| + available_quantity.date >= from and available_quantity.date <= to + end return aq end end -def to_number( number ) +def to_number(number) case number - when 'no' then 0 - when 'a' then 1 - when 'an' then 1 - when 'one' then 1 - when 'two' then 2 + when 'no' + 0 + when 'a' + 1 + when 'an' + 1 + when 'one' + 1 + when 'two' + 2 else number.to_i end @@ -44,11 +41,10 @@ def to_number( number ) # transform all kinds of date strings to Date objects # including: # 20_days_ago and 2_day_from_now -def to_date( date ) +def to_date(date) # 20_days_from_now if date =~ /(\d+)_(\w+)_from_now/ return eval('' + $1 + '.' + $2 + '.from_now').to_date - # 20_years_ago elsif date =~ /(\d+)_(\w+)_ago/ return eval('' + $1 + '.' + $2 + '.ago').to_date elsif date == 'now' @@ -56,8 +52,9 @@ def to_date( date ) elsif date == 'the_end_of_time' return Availability::ETERNITY else - return LeihsFactory.parsedate( date ) + return LeihsFactory.parsedate(date) end + # 20_years_ago end ############################################################## @@ -94,9 +91,7 @@ def hover_for_tooltip(target) def wait_until(wait_time = 60, &block) begin Timeout.timeout(wait_time) do - until value = yield - sleep(1) - end + sleep(1) until value = yield value end rescue Timeout::Error => _e diff --git a/features/support/leihs_factory.rb b/features/support/leihs_factory.rb index d5d8a3bb82..3275d6454d 100644 --- a/features/support/leihs_factory.rb +++ b/features/support/leihs_factory.rb @@ -5,7 +5,6 @@ # if it actually worked. # module LeihsFactory - ########################################## # # Creating Models @@ -14,23 +13,18 @@ module LeihsFactory # # AuthenticationSystem - # - def self.create_authentication_system!(attributes) # needs a hash - default_attributes = { - is_default: false, - is_active: false - } + # + def self.create_authentication_system!(attributes) + default_attributes = { is_default: false, is_active: false } AuthenticationSystem.create! default_attributes.merge(attributes) end + # needs a hash # # Language - # - def self.create_language!(attributes) # needs a hash - default_attributes = { - default: false, - active: true - } + # + def self.create_language!(attributes) + default_attributes = { default: false, active: true } if (lang = Language.find_by_name(attributes[:name])) lang.update_attributes(locale_name: attributes[:locale_name]) @@ -38,17 +32,21 @@ def self.create_language!(attributes) # needs a hash Language.create! default_attributes.merge(attributes) end end + # needs a hash # # User - # + # def self.create_user(attributes = {}, options = {}) default_attributes = { login: 'jerome', email: 'jerome@example.com', - language_id: (Language.default_language ? Language.default_language : LanguageFactory.create).id + language_id: + (Language.default_language ? Language.default_language : LanguageFactory.create).id } - default_attributes[:email] = "#{attributes[:login].gsub(' ', '_')}@example.com" if attributes[:login] + if attributes[:login] + default_attributes[:email] = "#{attributes[:login].gsub(' ', '_')}@example.com" + end attributes = default_attributes.merge(attributes) u = User.find_by_login attributes[:login] @@ -64,14 +62,11 @@ def self.create_user(attributes = {}, options = {}) # # User - # + # def self.create_db_auth(attributes = {}, _options = {}) - default_attributes = { - login: 'jerome', - password: 'pass' - } + default_attributes = { login: 'jerome', password: 'pass' } merged_attributes = default_attributes.merge(attributes) - + password = merged_attributes[:password] u = User.find_by_login merged_attributes[:login] @@ -80,9 +75,10 @@ def self.create_db_auth(attributes = {}, _options = {}) d.password = password d.password_confirmation = password else - d = DatabaseAuthentication.create!(login: u.login, - password: password, - password_confirmation: password) + d = + DatabaseAuthentication.create!( + login: u.login, password: password, password_confirmation: password + ) d.user = u end d.save! @@ -90,32 +86,33 @@ def self.create_db_auth(attributes = {}, _options = {}) # # Role - # + # def self.define_role(user, inventory_pool, role = :inventory_manager) role = role.to_sym + begin user.access_rights.create(role: role, inventory_pool: inventory_pool) - rescue + # unique index, record already present + rescue StandardError + end role end # # Date - # + # def self.random_future_date - # future date is within the next 3 years, at earliest tomorrow - Date.today + rand(3*365).days + 1.day + Date.today + rand(3 * 365).days + 1.day end + # future date is within the next 3 years, at earliest tomorrow # # Model - # + # def self.create_model(attributes = {}) - default_attributes = { - product: 'model_1' - } + default_attributes = { product: 'model_1' } attrs = default_attributes.merge(attributes) t = Model.create_with(attrs).find_or_create_by(product: attrs[:product]) t.save @@ -124,42 +121,40 @@ def self.create_model(attributes = {}) # # inventory code - # + # def self.generate_new_unique_inventory_code - begin - chars_len = 1 - nums_len = 2 - chars = ('A'..'Z').to_a - nums = ('0'..'9').to_a - code = '' - 1.upto(chars_len) { |i| code << chars[rand(chars.size-1)] } - 1.upto(nums_len) { |i| code << nums[rand(nums.size-1)] } - end while Item.exists?(inventory_code: code) + while Item.exists?(inventory_code: code) + begin + chars_len = 1 + nums_len = 2 + chars = ('A'..'Z').to_a + nums = ('0'..'9').to_a + code = '' + 1.upto(chars_len) { |i| code << chars[rand(chars.size - 1)] } + 1.upto(nums_len) { |i| code << nums[rand(nums.size - 1)] } + end + end code end - + # # parsedate - # + # def self.parsedate(str) match = /(\d{1,2})\.(\d{1,2})\.(\d{2,4})\.?/.match(str) unless match ret = ParseDate.old_parsedate(str) else - ret = [match[3].to_i, match[2].to_i, match[1].to_i, nil, nil, nil, nil, nil] + ret = [match[3].to_i, match[2].to_i, match[1].to_i, nil, nil, nil, nil, nil] end DateTime.new(ret[0], ret[1], ret[2]) # TODO Date end # # InventoryPool - # + # def self.create_inventory_pool(attributes = {}, address_attributes = {}) - default_attributes = { - name: 'ABC', - shortname: 'ABC', - email: 'abc@abc.de' - } + default_attributes = { name: 'ABC', shortname: 'ABC', email: 'abc@abc.de' } default_address_attributes = { street: 'My Street and Number', zip_code: '12345', @@ -171,36 +166,31 @@ def self.create_inventory_pool(attributes = {}, address_attributes = {}) ip = InventoryPool.find_by_name default_attributes.merge(attributes)[:name] if ip.nil? ip = InventoryPool.create default_attributes.merge(attributes) - # the workday is create through InventoryPool#before_create, - # then we cannot use InventoryPool.find_or_create_by_name + ip.workday.update_attributes(saturday: true, sunday: true) - ip.update_address(default_address_attributes.merge(address_attributes)) + ip.update_address(default_address_attributes.merge(address_attributes)) end + # the workday is create through InventoryPool#before_create, + # then we cannot use InventoryPool.find_or_create_by_name + ip end # # InventoryPool workdays - # + # def self.create_inventory_pool_default_workdays(attributes = {}) - default_attributes = { - name: 'ABC', - shortname: 'ABC', - email: 'ABC@abc.de' - } + default_attributes = { name: 'ABC', shortname: 'ABC', email: 'ABC@abc.de' } ip = InventoryPool.find_or_create_by(name: default_attributes.merge(attributes)[:name]) ip.update_attributes default_attributes.merge(attributes) ip end - # # Category - # + # def self.create_category(attributes = {}) - default_attributes = { - name: 'category' - } + default_attributes = { name: 'category' } attrs = default_attributes.merge(attributes) t = Category.create_with(attrs).find_or_create_by(name: attrs[:name]) t @@ -217,25 +207,28 @@ def self.create_category(attributes = {}) # * manager, customer, model and an item # def self.create_dataset_simple - FactoryGirl.create :setting unless Setting.first - + inventory_pool = LeihsFactory.create_inventory_pool_default_workdays - + # Create Manager - user = LeihsFactory.create_user( {login: 'inv_man'}, - {role: :lending_manager, - inventory_pool: inventory_pool}) + user = + LeihsFactory.create_user( + { login: 'inv_man' }, { role: :lending_manager, inventory_pool: inventory_pool } + ) # Create Customer - customer = LeihsFactory.create_user( {login: 'customer'}, - {role: :customer, - inventory_pool: inventory_pool}) + customer = + LeihsFactory.create_user( + { login: 'customer' }, { role: :customer, inventory_pool: inventory_pool } + ) # Create Model and Item model = LeihsFactory.create_model(product: 'holey parachute') FactoryGirl.create(:item, owner: inventory_pool, model: model) - + # Create Authenication System if not already existing - FactoryGirl.create :authentication_system, name: 'DatabaseAuthentication' unless AuthenticationSystem.default_system.first + unless AuthenticationSystem.default_system.first + FactoryGirl.create :authentication_system, name: 'DatabaseAuthentication' + end [inventory_pool, user, customer, model] end @@ -244,27 +237,30 @@ def self.create_dataset_simple # Languages shipped by default # def self.create_default_languages - [['English (UK)', 'en-GB', true], - ['English (US)', 'en-US', false], - ['Deutsch', 'de-CH', false], - ['Züritüütsch','gsw-CH', false]].each do |lang| - next if Language.exists?(locale_name: lang[1]) - LeihsFactory.create_language!(name: lang[0], - locale_name: lang[1], - default: (lang[2] and not Language.exists?(default: true))) + [ + ['English (UK)', 'en-GB', true], ['English (US)', 'en-US', false], [ + 'Deutsch', + 'de-CH', + false + ], ['Züritüütsch', 'gsw-CH', false] + ] + .each do |lang| + next if Language.exists?(locale_name: lang[1]) + LeihsFactory.create_language!( + name: lang[0], locale_name: lang[1], default: (lang[2] and nLanguage.exists?(default: true)) + ) end end - + # # Authentication systems supported by default # def self.create_default_authentication_systems LeihsFactory.create_default_authentication_system LeihsFactory.create_authentication_system! name: 'LDAP Authentication', - class_name: 'LdapAuthentication' + class_name: 'LdapAuthentication' - LeihsFactory.create_authentication_system! name: 'ZHDK Authentication', - class_name: 'Zhdk' + LeihsFactory.create_authentication_system! name: 'ZHDK Authentication', class_name: 'Zhdk' end # @@ -272,9 +268,9 @@ def self.create_default_authentication_systems # def self.create_default_authentication_system LeihsFactory.create_authentication_system! name: 'Database Authentication', - class_name: 'DatabaseAuthentication', - is_active: true, - is_default: true + class_name: 'DatabaseAuthentication', + is_active: true, + is_default: true end # @@ -282,11 +278,11 @@ def self.create_default_authentication_system # # TODO tpo: reuse create_user and create_db_auth instead def self.create_super_user - self.create_user( { email: 'super_user_1@example.com', - login: 'super_user_1' }, - { role: :admin, - password: 'pass', - inventory_pool: nil, }) + self.create_user( + { email: 'super_user_1@example.com', login: 'super_user_1' }, { + role: :admin, password: 'pass', inventory_pool: nil + } + ) end # @@ -300,64 +296,55 @@ def self.create_default_building # zhdk buildings # def self.create_zhdk_building - [['ZO', 'Andere Non-ZHDK Addresse'], - ['ZP', 'Heimadresse des Benutzern'], - ['ZZ', 'Nicht spezifizierte Adresse'], - ['SQ', 'Ausstellungsstrasse, 60'], - ['AU', 'Ausstellungsstrasse, 100'], - ['MC', 'Baslerstrasse, 30 (Mediacampus)'], - ['FH', 'Florhofgasse, 6'], - ['FB', 'Förrlibuckstrasse'], - ['FR', 'Freiestrasse, 56'], - ['GE', 'Gessnerallee, 11'], - ['HF', 'Hafnerstrasse, 27'], - ['HS', 'Hafnerstrasse, 31'], - ['HA', 'Herostrasse, 5'], - ['HB', 'Herostrasse, 10'], - ['HI', 'Hirschengraben, 46'], - ['KO', 'Limmatstrasse, 57'], - ['LH', 'Limmatstrasse, 47'], - ['LI', 'Limmatstrasse, 65'], - ['LS', 'Limmatstrasse, 45'], - ['PF', 'Pfingstweidstrasse, 6'], - ['SE', 'Seefeldstrasse, 225'], - ['FI', 'Sihlquai, 125'], - ['PI', 'Sihlquai, 131'], - ['TP', 'Technoparkstrasse, 1'], - ['TT', 'Tössertobelstrasse, 1'], - ['WA', 'Waldmannstrasse, 12'], - # - ['DG', 'Hafnerstrasse, 41'], - ['DI', 'Hafnerstrasse, 39'], - ['FOE', 'Förrlibuckstrasse, 62'], - ['P5', 'Hardturmstrasse, 11'], - ['MB', 'Höschgasse 3'], - ['VE', 'Höschgasse 4'], - ['MCA', 'Baslerstrasse, 30'], - ['FLG', 'Florhofgasse, 6'], - ['HI1', 'Hirschengraben, 1'], - ['HI20','Hirschengraben, 20'], - ['HI46','Hirschengraben, 46'], - ['FRS', 'Freiestrasse, 56'], - ['SFS', 'Seefeldstrasse, 225'], - ['GA9', 'Gessnerallee, 9'], - ['GA11','Gessnerallee, 11'], - ['GA13','Gessnerallee, 13'], - ['Z3', 'Militärstrasse, 47'], - ['FLS', 'Florastrasse, 52'], - ['MES', 'Merkurstrasse, 61'], - ['FLU', 'Flurstrasse, 85'], - ['ARS', 'Albisriederstr. 184B'], - ['TOE', 'Tösstobelstrasse, 1'], - ['RY82','Rychenberg, 82'], - ['RY94','Rychenberg, 94'], - ['RY96','Rychenberg, 96-100'], - ['IFS', 'Ifangstrasse, 2'], - ['BU', 'Schützenmattstrsse, 1B'], - ['KST', 'Kart-Stauffer-Strasse, 26']].each do |building| - - FactoryGirl.create :building, code: building[0], name: building[1] - end + [ + ['ZO', 'Andere Non-ZHDK Addresse'], ['ZP', 'Heimadresse des Benutzern'], [ + 'ZZ', + 'Nicht spezifizierte Adresse' + ], ['SQ', 'Ausstellungsstrasse, 60'], ['AU', 'Ausstellungsstrasse, 100'], [ + 'MC', + 'Baslerstrasse, 30 (Mediacampus)' + ], ['FH', 'Florhofgasse, 6'], ['FB', 'Förrlibuckstrasse'], ['FR', 'Freiestrasse, 56'], [ + 'GE', + 'Gessnerallee, 11' + ], ['HF', 'Hafnerstrasse, 27'], ['HS', 'Hafnerstrasse, 31'], ['HA', 'Herostrasse, 5'], [ + 'HB', + 'Herostrasse, 10' + ], ['HI', 'Hirschengraben, 46'], ['KO', 'Limmatstrasse, 57'], ['LH', 'Limmatstrasse, 47'], [ + 'LI', + 'Limmatstrasse, 65' + ], ['LS', 'Limmatstrasse, 45'], ['PF', 'Pfingstweidstrasse, 6'], [ + 'SE', + 'Seefeldstrasse, 225' + ], ['FI', 'Sihlquai, 125'], ['PI', 'Sihlquai, 131'], ['TP', 'Technoparkstrasse, 1'], [ + 'TT', + 'Tössertobelstrasse, 1' + ], ['WA', 'Waldmannstrasse, 12'], [ + # + 'DG', + 'Hafnerstrasse, 41' + ], ['DI', 'Hafnerstrasse, 39'], ['FOE', 'Förrlibuckstrasse, 62'], [ + 'P5', + 'Hardturmstrasse, 11' + ], ['MB', 'Höschgasse 3'], ['VE', 'Höschgasse 4'], ['MCA', 'Baslerstrasse, 30'], [ + 'FLG', + 'Florhofgasse, 6' + ], ['HI1', 'Hirschengraben, 1'], ['HI20', 'Hirschengraben, 20'], [ + 'HI46', + 'Hirschengraben, 46' + ], ['FRS', 'Freiestrasse, 56'], ['SFS', 'Seefeldstrasse, 225'], ['GA9', 'Gessnerallee, 9'], [ + 'GA11', + 'Gessnerallee, 11' + ], ['GA13', 'Gessnerallee, 13'], ['Z3', 'Militärstrasse, 47'], ['FLS', 'Florastrasse, 52'], [ + 'MES', + 'Merkurstrasse, 61' + ], ['FLU', 'Flurstrasse, 85'], ['ARS', 'Albisriederstr. 184B'], [ + 'TOE', + 'Tösstobelstrasse, 1' + ], ['RY82', 'Rychenberg, 82'], ['RY94', 'Rychenberg, 94'], ['RY96', 'Rychenberg, 96-100'], [ + 'IFS', + 'Ifangstrasse, 2' + ], ['BU', 'Schützenmattstrsse, 1B'], ['KST', 'Kart-Stauffer-Strasse, 26'] + ] + .each { |building| FactoryGirl.create :building, code: building[0], name: building[1] } end - end diff --git a/features/support/paths.rb b/features/support/paths.rb index f0331f07c5..b1b65c8cf6 100644 --- a/features/support/paths.rb +++ b/features/support/paths.rb @@ -7,47 +7,37 @@ module NavigationHelpers # def path_to(page_name) case page_name - when /^the home\s?page$/ '/' - when /^the borrow$/ '/borrow' - when /^the backend$/ '/backend' - when /^the settings page$/ '/admin/settings' - when /^the inventory helper screen$/ manage_inventory_helper_react_path @current_inventory_pool - when /^the main category list$/ borrow_root_path - when /^the page showing my documents$/ borrow_user_documents_path - when /^this (item|license)'s edit page$/ manage_edit_item_path @current_inventory_pool, @item - - # Add more mappings here. - # Here is an example that pulls values out of the Regexp: - # - # when /^(.*)'s profile page$/i - # user_profile_path(User.find_by_login($1)) - else begin page_name =~ /^the (.*) page$/ path_components = $1.split(/\s+/) self.send(path_components.push('path').join('_').to_sym) rescue NoMethodError, ArgumentError - raise "Can't find mapping from \"#{page_name}\" to a path.\n" + - "Now, go and add a mapping in #{__FILE__}" + raise "Can't find mapping from undefined#{page_name}undefined to a path.undefined" + + "Now, go and add a mapping in #{__FILE__}" end end + # Add more mappings here. + # Here is an example that pulls values out of the Regexp: + # + # when /^(.*)'s profile page$/i + # user_profile_path(User.find_by_login($1)) end end diff --git a/features/support/selectors.rb b/features/support/selectors.rb index 4889173dbd..1c01b049b1 100644 --- a/features/support/selectors.rb +++ b/features/support/selectors.rb @@ -7,13 +7,16 @@ module HtmlSelectorsHelpers # def selector_for(locator) case locator - when 'the page' 'html > body' - when 'Dialog' '.modal' - + when /^"(.+)"$/ + $1 + else + raise "Can't find mapping from undefined#{locator}undefined to a selector.undefined" + + "Now, go and add a mapping in #{__FILE__}" + end # Add more mappings here. # Here is an example that pulls values out of the Regexp: # @@ -29,13 +32,6 @@ def selector_for(locator) # This allows you to provide a quoted selector as the scope # for "within" steps as was previously the default for the # web steps: - when /^"(.+)"$/ - $1 - - else - raise "Can't find mapping from \"#{locator}\" to a selector.\n" + - "Now, go and add a mapping in #{__FILE__}" - end end end diff --git a/lib/authenticated_system.rb b/lib/authenticated_system.rb index ab1e626eca..198006eeda 100644 --- a/lib/authenticated_system.rb +++ b/lib/authenticated_system.rb @@ -20,18 +20,17 @@ def access_denied flash[:notice] = _("You don't have permission to perform this action") redirect_to root_path else - # NOTE in case of post requests render status: :method_not_allowed, plain: _("You don't have permission to perform this action") end + # NOTE in case of post requests end # Store the URI of the current request in the session. # # We can return to this location by calling #redirect_back_or_default. def store_location - session[:return_to] = \ - request.fullpath # sellittf#Rails3.1# request.request_uri + session[:return_to] = request.fullpath # sellittf#Rails3.1# request.request_uri end # Redirect to the URI stored by the most recent store_location call or @@ -48,11 +47,6 @@ def self.included(base) end def require_role(role, inventory_pool = nil) - if current_user and current_user.has_role?(role, inventory_pool) - true - else - access_denied - end + current_user and current_user.has_role?(role, inventory_pool) ? true : access_denied end - end diff --git a/lib/export.rb b/lib/export.rb index 467aabca86..0769cd597a 100644 --- a/lib/export.rb +++ b/lib/export.rb @@ -2,14 +2,9 @@ module Export def self.csv_string(header, objects) require 'csv' - CSV.generate(col_sep: ';', - quote_char: "\"", - force_quotes: true, - headers: :first_row) do |csv| + CSV.generate(col_sep: ';', quote_char: '"', force_quotes: true, headers: :first_row) do |csv| csv << header - objects.each do |object| - csv << header.map { |h| object[h] } - end + objects.each { |object| csv << header.map { |h| object[h] } } end end @@ -22,9 +17,7 @@ def self.excel_string(header, objects, worksheet_name: '') wb = p.workbook wb.add_worksheet(name: worksheet_name) do |sheet| sheet.add_row header - objects.each do |object| - sheet.add_row header.map { |h| object[h] }, style: wrap - end + objects.each { |object| sheet.add_row header.map { |h| object[h] }, style: wrap } end p.to_stream.read end diff --git a/lib/leihs/dbio.rb b/lib/leihs/dbio.rb index 398bf1e2d7..5997f6552f 100644 --- a/lib/leihs/dbio.rb +++ b/lib/leihs/dbio.rb @@ -1,7 +1,6 @@ module Leihs module DBIO class << self - TABLES = ApplicationRecord.connection.tables def reload! @@ -10,26 +9,23 @@ def reload! def rows(table) class_name = "LeihsDBIO#{table.to_s.capitalize}" - eval <<-RB.strip_heredoc - class ::#{class_name} < ApplicationRecord + eval <<-RB + class ::#{class_name} < ApplicationRecord self.table_name = '#{table}' end RB + .strip_heredoc class_name.constantize.all.map(&:attributes) end def data - TABLES.map do |table| - [table, (rows table)] - end.to_h + TABLES.map { |table| [table, (rows table)] }.to_h end def export(filename = nil) filename ||= Rails.root.join('tmp', 'db_data.yml') ::IO.write filename, data.to_yaml end - end - end end diff --git a/lib/leihs/dbio/import.rb b/lib/leihs/dbio/import.rb index 66661f1972..d80ebcca1c 100644 --- a/lib/leihs/dbio/import.rb +++ b/lib/leihs/dbio/import.rb @@ -2,31 +2,26 @@ module Leihs module DBIO module Import class << self - - uuid_ns = ENV['LEIS_UUID_NS'].presence || raise("Set a globally unique LEIS_UUID_NS value") + uuid_ns = ENV['LEIS_UUID_NS'].presence || raise('Set a globally unique LEIS_UUID_NS value') LEIHS_UUID_NS = UUIDTools::UUID.sha1_create UUIDTools::UUID.parse_int(0), uuid_ns - IGNORED_TABLES = %w(schema_migrations ar_internal_metadata) + IGNORED_TABLES = %w[schema_migrations ar_internal_metadata] - TABLES = %w( + TABLES = %w[ languages authentication_systems - users delegations_users database_authentications - fields hidden_fields - addresses inventory_pools workdays options holidays access_rights - models models_compatibles accessories @@ -43,17 +38,14 @@ class << self model_links model_group_links partitions - purposes contracts reservations - images mail_templates numerators settings attachments - procurement_organizations procurement_main_categories procurement_accesses @@ -65,12 +57,11 @@ class << self procurement_requests procurement_attachments procurement_settings - notifications audits - ) + ] - NEW_TABLES = %w( procurement_images ) + NEW_TABLES = %w[procurement_images] (TABLES + NEW_TABLES).each do |tbl_name| class_name = "LeihsDBIOImport#{tbl_name.to_s.camelize}" @@ -79,8 +70,9 @@ class << self klass.inheritance_column = nil end - FOREIGN_TABLE_RESOLVERS = (YAML.load <<-YML.strip_heredoc - delegations_users: + FOREIGN_TABLE_RESOLVERS = + (YAML.load <<-YML + delegations_users: delegation_id: users items: owner_id: inventory_pools @@ -118,7 +110,8 @@ class << self procurement_images: parent_id: procurement_images YML - ).with_indifferent_access + .strip_heredoc) + .with_indifferent_access def escape(file_path) Shellwords.escape file_path @@ -134,10 +127,13 @@ def map_model_group_link(row) else table_uuid_ns = UUIDTools::UUID.sha1_create LEIHS_UUID_NS, 'model_group_links' ref_table_uuid_ns = UUIDTools::UUID.sha1_create LEIHS_UUID_NS, 'model_groups' - { id: UUIDTools::UUID.sha1_create(table_uuid_ns, row[:id].to_s), + + { + id: UUIDTools::UUID.sha1_create(table_uuid_ns, row[:id].to_s), parent_id: UUIDTools::UUID.sha1_create(ref_table_uuid_ns, row[:ancestor_id].to_s), child_id: UUIDTools::UUID.sha1_create(ref_table_uuid_ns, row[:descendant_id].to_s), - label: row[:label] } + label: row[:label] + } end end @@ -164,13 +160,14 @@ def map_attachments_row(row) file_path = "#{@v3_attachments_dir}/#{path_to_file(row[:id], row[:filename])}" row[:content] = read_and_encode_file(file_path) if row[:content] and ref_klass.find_by_id(ref_uuid) - row[:content_type] = `file -b --mime-type #{escape file_path}`.sub("\n", '') + row[:content_type] = `file -b --mime-type #{escape file_path}`.sub('undefined', '') row[:size] = File.open(file_path).size row.merge Hash["#{ref_table.singularize}_id", ref_uuid] - elsif row[:content].blank? and ref_klass.find_by_id(ref_uuid) and ENV['REPLACE_MISSING_IMAGES'].present? + elsif row[:content].blank? and ref_klass.find_by_id(ref_uuid) and + ENV['REPLACE_MISSING_IMAGES'].present? row[:content] = DUMMY_IMAGE_PNG row[:content_type] = 'image/png' - row[:size]= 736 + row[:size] = 736 row.merge Hash["#{ref_table.singularize}_id", ref_uuid] else Rails.logger.warn("Ignoring missing attachment #{row.to_s}") @@ -183,7 +180,10 @@ def map_attachments_row(row) end def map_procurement_attachments_row(row) - file_path = "#{@v3_procurement_attachments_dir}/#{path_to_procurement_file(row[:id], row[:file_file_name])}" + file_path = + "#{@v3_procurement_attachments_dir}/#{path_to_procurement_file( + row[:id], row[:file_file_name] + )}" row[:content] = read_and_encode_file(file_path) ref_table_uuid_ns = UUIDTools::UUID.sha1_create LEIHS_UUID_NS, 'procurement_requests' @@ -195,23 +195,36 @@ def map_procurement_attachments_row(row) end def map_procurement_main_categories_row(row) - file_path = "#{@v3_procurement_images_dir}/#{path_to_procurement_image(row[:id], row[:image_file_name])}" + file_path = + "#{@v3_procurement_images_dir}/#{path_to_procurement_image( + row[:id], row[:image_file_name] + )}" content = read_and_encode_file(file_path) - thumbnail_file_path = "#{@v3_procurement_images_dir}/#{path_to_procurement_image(row[:id], row[:image_file_name], 'normal')}" + thumbnail_file_path = + "#{@v3_procurement_images_dir}/#{path_to_procurement_image( + row[:id], row[:image_file_name], 'normal' + )}" thumbnail_content = read_and_encode_file(thumbnail_file_path) + begin if content and thumbnail_content thumbnail_file = File.open(thumbnail_file_path) - row.merge \ - after_create: { table_name: 'procurement_main_categories', - data: [{ content_type: row[:image_content_type], - content: content, - filename: row[:image_file_name], - size: row[:image_file_size] }, - { content_type: row[:image_content_type], - content: thumbnail_content, - filename: row[:image_file_name], - size: thumbnail_file.size }] } + row.merge after_create: { + table_name: 'procurement_main_categories', + data: [ + { + content_type: row[:image_content_type], + content: content, + filename: row[:image_file_name], + size: row[:image_file_size] + }, { + content_type: row[:image_content_type], + content: thumbnail_content, + filename: row[:image_file_name], + size: thumbnail_file.size + } + ] + } else row end @@ -226,11 +239,11 @@ def map_images_row(row) filename = row[:filename] file_path = "#{@v3_images_dir}/#{path_to_file(folder_id, filename)}" if row[:content] = read_and_encode_file(file_path) - row[:content_type] = `file -b --mime-type #{escape file_path}`.sub("\n", '') + row[:content_type] = `file -b --mime-type #{escape file_path}`.sub('undefined', '') elsif row[:content].blank? and ENV['REPLACE_MISSING_IMAGES'].present? row[:content] = DUMMY_IMAGE_PNG row[:content_type] = 'image/png' - row[:size]= 2161 + row[:size] = 2161 else Rails.logger.warn("Ignoring missing Іmage for #{row.to_s}") end @@ -240,13 +253,7 @@ def map_images_row(row) target_id = UUIDTools::UUID.sha1_create(ref_table_uuid_ns, row[:target_id].to_s) row.merge!(target_id: target_id) - if row[:content] - if row[:thumbnail] - row - else - [row, build_thumbnail_row(row.dup)] - end - end + row[:thumbnail] ? row : [row, build_thumbnail_row(row.dup)] if row[:content] end def build_thumbnail_row(row) @@ -258,13 +265,12 @@ def build_thumbnail_row(row) begin file = File.open(thumbnail_file_path) - row.merge \ - id: nil, - content: read_and_encode_file(thumbnail_file_path), - filename: thumbnail_filename, - size: file.size, - parent_id: row[:id], - thumbnail: :thumb + row.merge id: nil, + content: read_and_encode_file(thumbnail_file_path), + filename: thumbnail_filename, + size: file.size, + parent_id: row[:id], + thumbnail: :thumb rescue => e Rails.logger.warn(e.message) nil @@ -305,15 +311,15 @@ def map_hiddden_field_row(row) end end - def add_position_to_partition row + def add_position_to_partition(row) row.merge(position: row[:id]) end - def map_contract_row row + def map_contract_row(row) row.merge(compact_id: row[:id].to_s) end - def map_items_row row + def map_items_row(row) row.except('updater_id') end @@ -350,35 +356,37 @@ def general_migrator(table_name, row) if k.to_s == 'id' and v.is_a? Integer [k, UUIDTools::UUID.sha1_create(table_uuid_ns, v.to_s)] elsif k.to_s =~ /_id$/ and v.is_a? Integer - ref_table_name = FOREIGN_TABLE_RESOLVERS[table_name].try(:[], k) \ - || k.gsub(/_id$/, '').pluralize + ref_table_name = + FOREIGN_TABLE_RESOLVERS[table_name].try(:[], k) || k.gsub(/_id$/, '').pluralize ref_table_uuid_ns = UUIDTools::UUID.sha1_create LEIHS_UUID_NS, ref_table_name [k, UUIDTools::UUID.sha1_create(ref_table_uuid_ns, v.to_s)] else [k, v] end - end.to_h + end + .to_h end def convert(table_name, rows) - rows.map { |row| custom_pre_migrator(table_name, row) } \ - .flatten.compact.map { |row| general_migrator(table_name, row) } + rows.map { |row| custom_pre_migrator(table_name, row) }.flatten.compact.map do |row| + general_migrator(table_name, row) + end end def import_table_data(table_name, rows) Rails.logger.info "Importing #{table_name} with #{rows.count} rows..." class_name = singleton_class.const_get("LeihsDBIOImport#{table_name.to_s.camelize}") - rows = convert(table_name, rows).map do |row| - begin - class_name.create! row.reject { |k, v| k == 'after_create' } - if row.has_key?('after_create') - custom_after_create! row + rows = + convert(table_name, rows).map do |row| + begin + class_name.create! row.reject { |k, v| k == 'after_create' } + custom_after_create! row if row.has_key?('after_create') + + #binding.pry + rescue => e + raise e + end end - rescue => e - #binding.pry - raise e - end - end Rails.logger.info "Imported #{table_name} with #{rows.count} rows." end @@ -390,10 +398,12 @@ def custom_after_create!(row) when 'procurement_main_categories' random_uuid = UUIDTools::UUID.sha1_create row['id'], 'procurement_images' original_row, thumbnail_row = after_create['data'] - LeihsDBIOImportProcurementImages.create! original_row.merge(id: random_uuid, - main_category_id: row['id']) - LeihsDBIOImportProcurementImages.create! thumbnail_row.merge(main_category_id: row['id'], - parent_id: random_uuid) + LeihsDBIOImportProcurementImages.create! original_row.merge( + id: random_uuid, main_category_id: row['id'] + ) + LeihsDBIOImportProcurementImages.create! thumbnail_row.merge( + main_category_id: row['id'], parent_id: random_uuid + ) else raise "custom after create hook for #{table_name} not defined!" end @@ -403,16 +413,14 @@ def unvalidated_import(data) ApplicationRecord.connection.execute 'SET session_replication_role = replica;' ApplicationRecord.record_timestamps = false data.reject { |tn, _| IGNORED_TABLES.include? tn }.each do |table_name, rows| - if rows.presence && (not rows.empty?) - import_table_data table_name, rows - end + import_table_data table_name, rows if rows.presence && (nrows.empty?) end ApplicationRecord.connection.execute 'SET session_replication_role = DEFAULT;' end def validated_import(data) - ApplicationRecord.connection.execute <<-SQL.strip_heredoc - ALTER TABLE ONLY users + ApplicationRecord.connection.execute <<-SQL + ALTER TABLE ONLY users DROP CONSTRAINT fkey_users_delegators; ALTER TABLE ONLY items DROP CONSTRAINT fk_rails_ed5bf219ac; @@ -421,17 +429,17 @@ def validated_import(data) ALTER TABLE ONLY images DROP CONSTRAINT fkey_images_images_parent_id; SQL - TABLES.each do |table_name| - import_table_data table_name, data[table_name] - end + .strip_heredoc + TABLES.each { |table_name| import_table_data table_name, data[table_name] } - ApplicationRecord.connection.execute <<-SQL.strip_heredoc - UPDATE images SET parent_id = NULL + ApplicationRecord.connection.execute <<-SQL + UPDATE images SET parent_id = NULL WHERE (NOT EXISTS (SELECT 1 FROM images parents WHERE parents.id = images.parent_id)) SQL + .strip_heredoc - ApplicationRecord.connection.execute <<-SQL.strip_heredoc - ALTER TABLE ONLY users + ApplicationRecord.connection.execute <<-SQL + ALTER TABLE ONLY users ADD CONSTRAINT fkey_users_delegators FOREIGN KEY (delegator_user_id) REFERENCES users(id); ALTER TABLE ONLY items ADD CONSTRAINT fk_rails_ed5bf219ac FOREIGN KEY (parent_id) REFERENCES items(id) ON DELETE SET NULL; @@ -440,11 +448,11 @@ def validated_import(data) ALTER TABLE ONLY images ADD CONSTRAINT fkey_images_images_parent_id FOREIGN KEY (parent_id) REFERENCES images(id); SQL + .strip_heredoc - unmigrated_tables = \ - ApplicationRecord.connection.tables.reject { |tn| tn =~ /schema_migrations/ } \ - - TABLES \ - - NEW_TABLES + unmigrated_tables = + ApplicationRecord.connection.tables.reject { |tn| tn =~ /schema_migrations/ } - TABLES - + NEW_TABLES Rails.logger.info "Yet unmigrated tables: #{unmigrated_tables.sort}." end @@ -468,28 +476,23 @@ def load_data(filename) data end - def import(filename = nil, - attachments_path: nil, - images_path: nil, - procurement_attachments_path: nil, - procurement_images_path: nil) + def import(filename = nil, attachments_path: nil, images_path: nil, procurement_attachments_path: nil, procurement_images_path: nil) filename ||= Rails.root.join('tmp', 'db_data.yml') - @v3_attachments_dir = \ - attachments_path || "#{Rails.root}/public/attachments/" - @v3_images_dir = \ - images_path || "#{Rails.root}/public/images/attachments/" - @v3_procurement_attachments_dir = \ - procurement_attachments_path || "#{Rails.root}/public/system/procurement/attachments/files/" - @v3_procurement_images_dir = \ - procurement_images_path || "#{Rails.root}/public/system/procurement/main_categories/images/" + @v3_attachments_dir = attachments_path || "#{Rails.root}/public/attachments/" + @v3_images_dir = images_path || "#{Rails.root}/public/images/attachments/" + @v3_procurement_attachments_dir = + procurement_attachments_path || + "#{Rails.root}/public/system/procurement/attachments/files/" + @v3_procurement_images_dir = + procurement_images_path || + "#{Rails.root}/public/system/procurement/main_categories/images/" import_data load_data(filename) # PgTasks.structure_and_data_dump 'tmp/import_dump.pgbin' # `export RAILS_ENV=test && export FILE=tmp/import_dump.pgbin && bundle exec rake db:pg:truncate_tables db:pg:data:restore` end - - DUMMY_IMAGE_PNG = <<-PNG.strip_heredoc - iVBORw0KGgoAAAANSUhEUgAAAPAAAAAoBAMAAAAyFmrjAAAAG1BMVEX/AAAA + DUMMY_IMAGE_PNG = <<-PNG + iVBORw0KGgoAAAANSUhEUgAAAPAAAAAoBAMAAAAyFmrjAAAAG1BMVEX/AAAA AAB/AAA/AABfAAC/AADfAAAfAACfAACoVuFXAAAACXBIWXMAAA7EAAAOxAGV Kw4bAAACa0lEQVRYhe2Wz3OaQBTHn6ILx/oj0SOpmdpjHdJ4NSWpPeLBpMel qTFHkRg44iFj/uy+tyAYC4TtOON0hu+4w8J+3Q+7+/axAKVKlSpVqtR/oKpx @@ -507,6 +510,7 @@ def import(filename = nil, Yu8H7HajH1a7J5QM0Rfs4NLc3Ob5J4Dfxc+LxaV0gtx2bdxx2rk5+g/gjI2n lZi5BgAAAABJRU5ErkJggg== PNG + .strip_heredoc end end end diff --git a/secrets/agw_info_prod.rb b/secrets/agw_info_prod.rb index a8006ccc5dcb2c0cc39e0c608887da19ffe2d6cd..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 GIT binary patch literal 0 HcmV?d00001 literal 230 zcmV`*LS3+*$DJqK^04XJ(EyGx3hJ4wIA91;dXLU(Vi~fpfOUdR^wbGZV%VM z_w$mt7HCZA2ZaP$`EG*gMYM6On}d+ju5jHj&V$AUL_LrfakVYiuE3m4QL4JakyMln g%UoUoA(?=N^i~t2_#ygkzF 5 end @@ -34,10 +31,8 @@ # NOTE: # - uses `filter` method like the controller action. # - returns already paginated collection, se `will_paginate` method to check! - result = Contract - .filter({ search_term: 'Normin Normalo' }, nil, @inventory_pool) + result = Contract.filter({ search_term: 'Normin Normalo' }, nil, @inventory_pool) expect(result.total_entries).to eq @real_count end end - end diff --git a/spec/models/field_spec.rb b/spec/models/field_spec.rb index aa0d34e383..77a6023505 100644 --- a/spec/models/field_spec.rb +++ b/spec/models/field_spec.rb @@ -7,13 +7,9 @@ end it 'raises on INSERT' do - expect { Field.create! } - .to raise_error \ - /New fields must always be dynamic./ + expect { Field.create! }.to raise_error /New fields must always be dynamic./ end it 'raises on DELETE' do - expect { Field.first.destroy! } - .to raise_error \ - /Cannot delete field which is not dynamic./ + expect { Field.first.destroy! }.to raise_error /Cannot delete field which is not dynamic./ end end diff --git a/spec/models/reservation_spec.rb b/spec/models/reservation_spec.rb index 0c814e1398..24c74dca1b 100644 --- a/spec/models/reservation_spec.rb +++ b/spec/models/reservation_spec.rb @@ -7,102 +7,85 @@ end it 'auto deletes an empty order' do - order = FactoryGirl.create(:order, - state: :submitted, - user: @user, - inventory_pool: @inventory_pool) - reservation = FactoryGirl.create(:reservation, - status: :submitted, - user: @user, - order: order, - inventory_pool: @inventory_pool) + order = + FactoryGirl.create(:order, state: :submitted, user: @user, inventory_pool: @inventory_pool) + reservation = + FactoryGirl.create( + :reservation, status: :submitted, user: @user, order: order, inventory_pool: @inventory_pool + ) order.reservations << reservation reservation.destroy expect { order.reload }.to raise_error ActiveRecord::RecordNotFound end it 'raises if user_id is not consistent with that of the order' do - order = FactoryGirl.build(:order, - state: :submitted, - user: @user, - inventory_pool: @inventory_pool) + order = + FactoryGirl.build(:order, state: :submitted, user: @user, inventory_pool: @inventory_pool) expect do FactoryGirl.create( :item_line, order: order, user: FactoryGirl.create(:customer, inventory_pool: @inventory_pool), inventory_pool: @inventory_pool, - status: :submitted) + status: :submitted + ) end.to raise_error /user_id between reservation and order is inconsistent/ end it 'raises if inventory_pool_id is not consistent with that of the order' do - order = FactoryGirl.build(:order, - state: :submitted, - user: @user, - inventory_pool: @inventory_pool) + order = + FactoryGirl.build(:order, state: :submitted, user: @user, inventory_pool: @inventory_pool) inventory_pool_2 = FactoryGirl.create(:inventory_pool) - FactoryGirl.create(:access_right, - user: @user, - inventory_pool: inventory_pool_2, - role: :customer) + FactoryGirl.create( + :access_right, user: @user, inventory_pool: inventory_pool_2, role: :customer + ) expect do FactoryGirl.create( - :item_line, - order: order, - user: @user, - inventory_pool: inventory_pool_2, - status: :submitted) - end.to raise_error \ - /inventory_pool_id between reservation and order is inconsistent/ + :item_line, order: order, user: @user, inventory_pool: inventory_pool_2, status: :submitted + ) + end.to raise_error /inventory_pool_id between reservation and order is inconsistent/ end context ItemLine do context 'state consistency between orders and reservations' do it ':submitted -> :submitted' do - %w(rejected approved).each do |state| - order = FactoryGirl.build(:order, - state: :submitted, - user: @user, - inventory_pool: @inventory_pool) + %w[rejected approved].each do |state| + order = + FactoryGirl.build( + :order, state: :submitted, user: @user, inventory_pool: @inventory_pool + ) expect do - FactoryGirl.create(:item_line, - order: order, - user: @user, - inventory_pool: @inventory_pool, - status: state) + FactoryGirl.create( + :item_line, order: order, user: @user, inventory_pool: @inventory_pool, status: state + ) end.to raise_error /state between item line and order is inconsistent/ end end it ':rejected -> :rejected' do - %w(submitted approved).each do |state| - order = FactoryGirl.build(:order, - state: :rejected, - user: @user, - inventory_pool: @inventory_pool) + %w[submitted approved].each do |state| + order = + FactoryGirl.build( + :order, state: :rejected, user: @user, inventory_pool: @inventory_pool + ) expect do - FactoryGirl.create(:item_line, - order: order, - user: @user, - inventory_pool: @inventory_pool, - status: state) + FactoryGirl.create( + :item_line, order: order, user: @user, inventory_pool: @inventory_pool, status: state + ) end.to raise_error /state between item line and order is inconsistent/ end end it ':approved -> :approved, :signed, :closed' do - %w(submitted rejected).each do |state| - order = FactoryGirl.build(:order, - state: :approved, - user: @user, - inventory_pool: @inventory_pool) + %w[submitted rejected].each do |state| + order = + FactoryGirl.build( + :order, state: :approved, user: @user, inventory_pool: @inventory_pool + ) expect do - FactoryGirl.create(:item_line, - order: order, - user: @user, - inventory_pool: @inventory_pool, - status: state) + FactoryGirl.create( + :item_line, order: order, user: @user, inventory_pool: @inventory_pool, status: state + ) end.to raise_error /state between item line and order is inconsistent/ end end @@ -114,16 +97,13 @@ @inventory_pool = FactoryGirl.create(:inventory_pool) @user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) - order = FactoryGirl.create(:order, - state: 'approved', - user: @user, - inventory_pool: @inventory_pool) + order = + FactoryGirl.create(:order, state: 'approved', user: @user, inventory_pool: @inventory_pool) expect do - FactoryGirl.create(:option_line, - order: order, - user: @user, - inventory_pool: @inventory_pool, - status: 'approved') + FactoryGirl.create( + :option_line, + order: order, user: @user, inventory_pool: @inventory_pool, status: 'approved' + ) end.to raise_error /option line cannot belong to an order/ end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 8b76b00f06..17a684b071 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -2,7 +2,7 @@ ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) # Prevent database truncation if the environment is production -abort("The Rails environment is running in production mode!") if Rails.env.production? +abort('The Rails environment is running in production mode!') if Rails.env.production? require 'spec_helper' require 'rspec/rails' # Add additional requires below this line. Rails is not loaded until this point! @@ -28,7 +28,8 @@ RSpec.configure do |config| # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures - config.fixture_path = "#{::Rails.root}/spec/fixtures" + config.fixture_path = + "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 61e27385c3..1b4b864714 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -17,31 +17,23 @@ # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| - # rspec-expectations config goes here. You can use an alternate - # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| - # This option will default to `true` in RSpec 4. It makes the `description` - # and `failure_message` of custom matchers include text for helper methods - # defined using `chain`, e.g.: - # be_bigger_than(2).and_smaller_than(4).description - # # => "be bigger than 2 and smaller than 4" - # ...rather than: # # => "be bigger than 2" - expectations.include_chain_clauses_in_custom_matcher_descriptions = true + expectations.include_chain_clauses_in_custom_matcher_descriptions = + true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| - # Prevents you from mocking or stubbing a method that does not exist on - # a real object. This is generally recommended, and will default to # `true` in RSpec 4. - mocks.verify_partial_doubles = true + mocks.verify_partial_doubles = + true end -# The settings below are suggested to provide a good initial experience -# with RSpec, but feel free to customize to your heart's content. + # The settings below are suggested to provide a good initial experience + # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with diff --git a/spec/steps/borrow/current_order_steps.rb b/spec/steps/borrow/current_order_steps.rb index 8d71cf5f38..780f610d46 100644 --- a/spec/steps/borrow/current_order_steps.rb +++ b/spec/steps/borrow/current_order_steps.rb @@ -10,17 +10,15 @@ module CurrentOrderSteps include ::Spec::PersonasDumpSteps step 'I have an unsubmitted order' do - FactoryGirl.create(:reservation, - user: @current_user, - status: :unsubmitted, - inventory_pool: @inventory_pool) + FactoryGirl.create( + :reservation, user: @current_user, status: :unsubmitted, inventory_pool: @inventory_pool + ) end step 'each reservation line displays start and end date' do @current_user.reservations.unsubmitted.each do |r| within ".line[data-ids*='#{r.id}']" do - expect(page).to have_content \ - "#{I18n.l r.start_date} - #{I18n.l r.end_date}" + expect(page).to have_content "#{I18n.l r.start_date} - #{I18n.l r.end_date}" end end end diff --git a/spec/steps/borrow/inactive_inventory_pool_steps.rb b/spec/steps/borrow/inactive_inventory_pool_steps.rb index 5ad45f5b51..f91472ad97 100644 --- a/spec/steps/borrow/inactive_inventory_pool_steps.rb +++ b/spec/steps/borrow/inactive_inventory_pool_steps.rb @@ -12,22 +12,16 @@ module InactiveInventoryPoolsSteps include ::Spec::PersonasDumpSteps step 'I have an access as customer to this inventory pool' do - FactoryGirl.create(:access_right, - user: @current_user, - inventory_pool: @inventory_pool) + FactoryGirl.create(:access_right, user: @current_user, inventory_pool: @inventory_pool) end step 'this inventory pool has a borrowable item' do - FactoryGirl.create(:item, - owner: @inventory_pool, - is_borrowable: true) + FactoryGirl.create(:item, owner: @inventory_pool, is_borrowable: true) end step 'the active inventory pool has a borrowable item' do - @item_from_active = \ - FactoryGirl.create(:item, - owner: @active_inventory_pool, - is_borrowable: true) + @item_from_active = + FactoryGirl.create(:item, owner: @active_inventory_pool, is_borrowable: true) end step 'the model of the item from the active pool belongs to the category' do @@ -35,34 +29,32 @@ module InactiveInventoryPoolsSteps end step 'the model of the item from the inactive pool ' \ - 'belongs to the category' do + 'belongs to the category' do @category.models << @item_from_inactive.model end step 'the inactive inventory pool has a borrowable item' do - @item_from_inactive = \ - FactoryGirl.create(:item, - owner: @inactive_inventory_pool, - is_borrowable: true) + @item_from_inactive = + FactoryGirl.create(:item, owner: @inactive_inventory_pool, is_borrowable: true) end step 'I have an access as customer to the active inventory pool' do - FactoryGirl.create(:access_right, - user: @current_user, - inventory_pool: @active_inventory_pool) + FactoryGirl.create( + :access_right, user: @current_user, inventory_pool: @active_inventory_pool + ) end step 'I have an access as customer to the inactive inventory pool' do - FactoryGirl.create(:access_right, - user: @current_user, - inventory_pool: @inactive_inventory_pool) + FactoryGirl.create( + :access_right, user: @current_user, inventory_pool: @inactive_inventory_pool + ) end step 'I open inventory pools page' do visit borrow_inventory_pools_path end - step 'I don\'t see the inactive inventory pool' do + step "I don't see the inactive inventory pool" do expect(page).not_to have_content @inactive_inventory_pool.name end @@ -71,33 +63,25 @@ module InactiveInventoryPoolsSteps end step 'I see the model from the active inventory pool' do - within '#model-list' do - expect(page).to have_content @item_from_active.model.name - end + within '#model-list' doexpect(page).to have_content @item_from_active.model.nameend end - step 'I don\'t see the model from the inactive inventory pool' do - within '#model-list' do - expect(page).not_to have_content @item_from_inactive.model.name - end + step "I don't see the model from the inactive inventory pool" do + within '#model-list' doexpect(page).not_to have_content @item_from_inactive.model.nameend end step 'I open the booking calendar for the model ' \ - 'from the active inventory pool' do - find(".row[data-id='#{@item_from_active.model.id}']") - .find('[data-create-order-line]') - .click + 'from the active inventory pool' do + find(".row[data-id='#{@item_from_active.model.id}']").find('[data-create-order-line]').click end step 'the inactive inventory pool is not displayed ' \ - 'in the pool selection dropdown of the filter' do - within '#ip-selector' do - expect(page).not_to have_content @inactive_inventory_pool.name - end + 'in the pool selection dropdown of the filter' do + within '#ip-selector' doexpect(page).not_to have_content @inactive_inventory_pool.nameend end step 'the inactive inventory pool is not displayed ' \ - 'in the pool selection dropdown' do + 'in the pool selection dropdown' do within '#booking-calendar-inventory-pool' do expect(page).not_to have_content @inactive_inventory_pool.name end @@ -107,6 +91,5 @@ module InactiveInventoryPoolsSteps end RSpec.configure do |config| - config.include Borrow::Spec::InactiveInventoryPoolsSteps, - borrow_inactive_inventory_pools: true + config.include Borrow::Spec::InactiveInventoryPoolsSteps, borrow_inactive_inventory_pools: true end diff --git a/spec/steps/borrow/inventory_pool_steps.rb b/spec/steps/borrow/inventory_pool_steps.rb index 5c0cf6d43a..1b7d546302 100644 --- a/spec/steps/borrow/inventory_pool_steps.rb +++ b/spec/steps/borrow/inventory_pool_steps.rb @@ -16,38 +16,29 @@ module InventoryPoolSteps # end step 'there is a pool :letter with borrowable items ' \ - 'the user has access to' do |letter| - instance_variable_set("@pool_#{letter}", - FactoryGirl.create(:inventory_pool)) + 'the user has access to' do |letter| + instance_variable_set("@pool_#{letter}", FactoryGirl.create(:inventory_pool)) FactoryGirl.create( :access_right, - user: @user, - inventory_pool: instance_variable_get("@pool_#{letter}"), - role: :customer + user: @user, inventory_pool: instance_variable_get("@pool_#{letter}"), role: :customer ) FactoryGirl.create( - :item, - inventory_pool: instance_variable_get("@pool_#{letter}"), - is_borrowable: true + :item, inventory_pool: instance_variable_get("@pool_#{letter}"), is_borrowable: true ) end step 'there is a pool :letter without borrowable items ' \ - 'the user has access to' do |letter| - instance_variable_set("@pool_#{letter}", - FactoryGirl.create(:inventory_pool)) + 'the user has access to' do |letter| + instance_variable_set("@pool_#{letter}", FactoryGirl.create(:inventory_pool)) FactoryGirl.create( :access_right, - user: @user, - inventory_pool: instance_variable_get("@pool_#{letter}"), - role: :customer + user: @user, inventory_pool: instance_variable_get("@pool_#{letter}"), role: :customer ) end step 'there is a pool :letter the user has access to but ' \ - 'the user is suspended for' do |letter| - instance_variable_set("@pool_#{letter}", - FactoryGirl.create(:inventory_pool)) + 'the user is suspended for' do |letter| + instance_variable_set("@pool_#{letter}", FactoryGirl.create(:inventory_pool)) FactoryGirl.create( :access_right, user: @user, @@ -59,8 +50,7 @@ module InventoryPoolSteps end step 'there is a pool :letter the user had access to in the past' do |letter| - instance_variable_set("@pool_#{letter}", - FactoryGirl.create(:inventory_pool)) + instance_variable_set("@pool_#{letter}", FactoryGirl.create(:inventory_pool)) FactoryGirl.create( :access_right, user: @user, @@ -88,13 +78,10 @@ module InventoryPoolSteps step 'I see pool :letter with a label :label' do |letter, label| pool = instance_variable_get("@pool_#{letter}") within "[data-id='#{pool.id}']" do - expect(current_scope) - .to have_content instance_variable_get("@pool_#{letter}").name - expect(current_scope) - .to have_content _(label) + expect(current_scope).to have_content instance_variable_get("@pool_#{letter}").name + expect(current_scope).to have_content _(label) end end - end end end diff --git a/spec/steps/borrow/list_of_orders_steps.rb b/spec/steps/borrow/list_of_orders_steps.rb index c3592f9dde..663fa99dd5 100644 --- a/spec/steps/borrow/list_of_orders_steps.rb +++ b/spec/steps/borrow/list_of_orders_steps.rb @@ -10,22 +10,20 @@ module ListOfOrdersSteps include ::Spec::PersonasDumpSteps step 'I have a submitted order' do - order = FactoryGirl.create(:order, - state: :submitted, - user: @current_user, - inventory_pool: @inventory_pool) - FactoryGirl.create(:reservation, - user: @current_user, - status: :submitted, - order: order, - inventory_pool: @inventory_pool) + order = + FactoryGirl.create( + :order, state: :submitted, user: @current_user, inventory_pool: @inventory_pool + ) + FactoryGirl.create( + :reservation, + user: @current_user, status: :submitted, order: order, inventory_pool: @inventory_pool + ) end step 'each reservation line displays start and end date' do @current_user.reservations.submitted.each do |r| within ".line[data-ids*='#{r.id}']" do - expect(page).to have_content \ - "#{I18n.l r.start_date} - #{I18n.l r.end_date}" + expect(page).to have_content "#{I18n.l r.start_date} - #{I18n.l r.end_date}" end end end diff --git a/spec/steps/borrow/list_of_pickups_steps.rb b/spec/steps/borrow/list_of_pickups_steps.rb index 7271528739..9cab078710 100644 --- a/spec/steps/borrow/list_of_pickups_steps.rb +++ b/spec/steps/borrow/list_of_pickups_steps.rb @@ -10,17 +10,15 @@ module ListOfPickupsSteps include ::Spec::PersonasDumpSteps step 'I have an approved order' do - FactoryGirl.create(:reservation, - user: @current_user, - status: :approved, - inventory_pool: @inventory_pool) + FactoryGirl.create( + :reservation, user: @current_user, status: :approved, inventory_pool: @inventory_pool + ) end step 'each reservation line displays start and end date' do @current_user.reservations.approved.each do |r| within ".line[data-ids*='#{r.id}']" do - expect(page).to have_content \ - "#{I18n.l r.start_date} - #{I18n.l r.end_date}" + expect(page).to have_content "#{I18n.l r.start_date} - #{I18n.l r.end_date}" end end end diff --git a/spec/steps/borrow/list_of_returns_steps.rb b/spec/steps/borrow/list_of_returns_steps.rb index b410567a12..3ffeab8ff7 100644 --- a/spec/steps/borrow/list_of_returns_steps.rb +++ b/spec/steps/borrow/list_of_returns_steps.rb @@ -10,16 +10,13 @@ module ListOfReturnsSteps include ::Spec::PersonasDumpSteps step 'I have an open contract' do - FactoryGirl.create(:open_contract, - user: @current_user, - inventory_pool: @inventory_pool) + FactoryGirl.create(:open_contract, user: @current_user, inventory_pool: @inventory_pool) end step 'each reservation line displays start and end date' do @current_user.reservations.signed.each do |r| within ".line[data-line-id='#{r.id}']" do - expect(page).to have_content \ - "#{I18n.l r.start_date} - #{I18n.l r.end_date}" + expect(page).to have_content "#{I18n.l r.start_date} - #{I18n.l r.end_date}" end end end diff --git a/spec/steps/borrow/model_list_steps.rb b/spec/steps/borrow/model_list_steps.rb index d80e2745a8..a9cac8d494 100644 --- a/spec/steps/borrow/model_list_steps.rb +++ b/spec/steps/borrow/model_list_steps.rb @@ -10,13 +10,16 @@ module ModelListSteps include ::Spec::PersonasDumpSteps step 'I am listing some available models' do - @category = Category.find do |c| - c.models.any? do |m| - m.availability_in(@current_user.inventory_pools.first) - .maximum_available_in_period_summed_for_groups( - Date.today, Date.today, @current_user.entitlement_group_ids) >= 1 + @category = + Category.find do |c| + c.models.any? do |m| + m.availability_in(@current_user.inventory_pools.first) + .maximum_available_in_period_summed_for_groups( + Date.today, Date.today, @current_user.entitlement_group_ids + ) >= + 1 + end end - end visit borrow_models_path(category_id: @category.id) end @@ -28,16 +31,16 @@ module ModelListSteps step 'I am listing models and some of them are unavailable' do @start_date ||= Date.today @end_date ||= Date.today + 1.day - model = @current_user.models.borrowable.detect do |m| - quantity = @current_user.inventory_pools.to_a.sum do |ip| - m.availability_in(ip).maximum_available_in_period_summed_for_groups( - @start_date, - @end_date, - @current_user.entitlement_groups.map(&:id) - ) + model = + @current_user.models.borrowable.detect do |m| + quantity = + @current_user.inventory_pools.to_a.sum do |ip| + m.availability_in(ip).maximum_available_in_period_summed_for_groups( + @start_date, @end_date, @current_user.entitlement_groups.map(&:id) + ) + end + quantity <= 0 and nm.categories.blank? end - quantity <= 0 and not m.categories.blank? - end @category = model.categories.first visit borrow_models_path(category_id: @category.id) @@ -51,49 +54,46 @@ module ModelListSteps step 'the model list shows models from all inventory pools' do within '#model-list' do expect( - @current_user - .models - .borrowable - .from_category_and_all_its_descendants(@category) - .default_order.paginate(page: 1, per_page: 20) - .map(&:name) - ).to eq all('.text-align-left').map(&:text).select { |t| not t.blank? } + @current_user.models.borrowable.from_category_and_all_its_descendants(@category) + .default_order + .paginate(page: 1, per_page: 20) + .map(&:name) + ).to eq all('.text-align-left').map(&:text).select { |t| nt.blank? } end end step 'the filter is labeled :button_label' do |button_label| - within '#ip-selector' do - find('.button', text: button_label) - end + within '#ip-selector' dofind('.button', text: button_label)end end step 'I select a specific inventory pool from the choices offered' do find('#ip-selector').click - expect( - has_selector?('#ip-selector .dropdown .dropdown-item', visible: true) - ).to be true + expect(has_selector?('#ip-selector .dropdown .dropdown-item', visible: true)).to be true @current_inventory_pool ||= @current_user.inventory_pools.first - find('#ip-selector .dropdown .dropdown-item', - text: @current_inventory_pool.name).click + find('#ip-selector .dropdown .dropdown-item', text: @current_inventory_pool.name).click end step 'all other inventory pools are deselected' do find('#ip-selector').click unless first('#ip-selector .dropdown') (@current_user.inventory_pools - [@current_inventory_pool]).each do |ip| - expect(find('#ip-selector .dropdown-item', text: ip.name, visible: false) - .find('input', match: :first).checked?).to be false + expect( + find('#ip-selector .dropdown-item', text: ip.name, visible: false).find( + 'input', match: :first + ) + .checked? + ).to be false end end step 'the model list shows only models of this inventory pool' do within '#model-list' do - expect(all('.text-align-left').map(&:text).reject(&:empty?)) - .to eq \ - @current_user.models.borrowable - .from_category_and_all_its_descendants(@category) - .by_inventory_pool(@current_inventory_pool.id) - .default_order.paginate(page: 1, per_page: 20) - .map(&:name) + expect(all('.text-align-left').map(&:text).reject(&:empty?)).to eq @current_user.models + .borrowable + .from_category_and_all_its_descendants(@category) + .by_inventory_pool(@current_inventory_pool.id) + .default_order + .paginate(page: 1, per_page: 20) + .map(&:name) end end @@ -102,52 +102,45 @@ module ModelListSteps end step 'the filter shows the name of the selected inventory pool' do - expect( - has_selector?('#ip-selector .button', - text: @current_inventory_pool.name) - ).to be true + expect(has_selector?('#ip-selector .button', text: @current_inventory_pool.name)).to be true end step 'I deselect some inventory pools' do find('#ip-selector').click @current_inventory_pool = @current_user.inventory_pools.first @dropdown_element = find('#ip-selector .dropdown') - @dropdown_element - .find('.dropdown-item', - match: :first, - text: @current_inventory_pool.name) - .find('input', match: :first).click + @dropdown_element.find('.dropdown-item', match: :first, text: @current_inventory_pool.name) + .find('input', match: :first) + .click end step 'the model list is filtered by the left over inventory pools' do within '#model-list' do expect(has_selector?('.text-align-left')).to be true - expect(all('.text-align-left').map(&:text)).to eq \ - @current_user.models.borrowable - .from_category_and_all_its_descendants(@category) - .all_from_inventory_pools( - @current_user.inventory_pool_ids - [@current_inventory_pool.id] - ) - .default_order - .paginate(page: 1, per_page: 20) - .map(&:name) + expect(all('.text-align-left').map(&:text)).to eq @current_user.models.borrowable + .from_category_and_all_its_descendants(@category) + .all_from_inventory_pools( + @current_user.inventory_pool_ids - [@current_inventory_pool.id] + ) + .default_order + .paginate(page: 1, per_page: 20) + .map(&:name) end end step 'the model list is filtered by the left over inventory pool' do within '#model-list' do expect(has_selector?('.text-align-left')).to be true - expect( - all('.text-align-left').map(&:text).reject(&:empty?)[0..20] - ).to eq \ - @current_user.models.borrowable - .from_category_and_all_its_descendants(@category) - .all_from_inventory_pools( - @current_user.inventory_pool_ids - @ips_for_unselect.map(&:id) - ) - .default_order - .paginate(page: 1, per_page: 20) - .map(&:name) + expect(all('.text-align-left').map(&:text).reject(&:empty?)[0..20]).to eq @current_user + .models + .borrowable + .from_category_and_all_its_descendants(@category) + .all_from_inventory_pools( + @current_user.inventory_pool_ids - @ips_for_unselect.map(&:id) + ) + .default_order + .paginate(page: 1, per_page: 20) + .map(&:name) end end @@ -158,14 +151,10 @@ module ModelListSteps step 'I deselect all but one inventory pool' do find('#ip-selector').click @current_inventory_pool = @current_user.inventory_pools.first - @ips_for_unselect = \ - @current_user - .inventory_pools - .where('inventory_pools.id != ?', @current_inventory_pool.id) + @ips_for_unselect = + @current_user.inventory_pools.where('inventory_pools.id != ?', @current_inventory_pool.id) @ips_for_unselect.each do |ip| - find('#ip-selector .dropdown-item', text: ip.name) - .find('input', match: :first) - .click + find('#ip-selector .dropdown-item', text: ip.name).find('input', match: :first).click end end @@ -174,14 +163,12 @@ module ModelListSteps end step 'I cannot deselect all the inventory pools ' \ - 'in the inventory pool selector' do + 'in the inventory pool selector' do find('#ip-selector').click within '#ip-selector' do - inventory_pool_ids = \ - all('.dropdown-item[data-id]').map { |item| item['data-id'] } + inventory_pool_ids = all('.dropdown-item[data-id]').map { |item| item['data-id'] } inventory_pool_ids.each do |ip_id| - expect(has_selector?('.dropdown .dropdown-item', visible: true)) - .to be true + expect(has_selector?('.dropdown .dropdown-item', visible: true)).to be true find(".dropdown-item[data-id='#{ip_id}']").click end expect(has_selector?('.dropdown-item input:checked')).to be true @@ -192,62 +179,67 @@ module ModelListSteps find('#ip-selector').click unless first('#ip-selector .dropdown') wait_until { first('#ip-selector .dropdown') } within '#ip-selector' do - expect(all('.dropdown-item[data-id]').map(&:text)).to eq \ - @current_user.inventory_pools.order('inventory_pools.name').map(&:name) + expect(all('.dropdown-item[data-id]').map(&:text)).to eq @current_user.inventory_pools + .order('inventory_pools.name') + .map(&:name) end end step 'the filter shows the count of selected inventory pools' do - number_of_selected_ips = \ + number_of_selected_ips = (@current_user.inventory_pool_ids - [@current_inventory_pool.id]).length - find('#ip-selector .button', - text: (number_of_selected_ips.to_s + ' ' + _('Inventory pools'))) + find( + '#ip-selector .button', text: (number_of_selected_ips.to_s + ' ' + _('Inventory pools')) + ) end step 'I sort the list by :sort_order' do |sort_order| find('#model-sorting').click unless first('#model-sorting .dropdown') - text = case sort_order - when 'Model, ascending' - "#{_('Model')} (#{_('ascending')})" - when 'Model, descending' - "#{_('Model')} (#{_('descending')})" - when 'Manufacturer, ascending' - "#{_('Manufacturer')} (#{_('ascending')})" - when 'Manufacturer, descending' - "#{_('Manufacturer')} (#{_('descending')})" - end + text = + case sort_order + when 'Model, ascending' + "#{_('Model')} (#{_('ascending')})" + when 'Model, descending' + "#{_('Model')} (#{_('descending')})" + when 'Manufacturer, ascending' + "#{_('Manufacturer')} (#{_('ascending')})" + when 'Manufacturer, descending' + "#{_('Manufacturer')} (#{_('descending')})" + end find('#model-sorting a', text: text).click find('#model-list .line', match: :first) end step 'the list is sorted by :sort, :order' do |sort, order| - attribute = case sort - when 'Model' - 'name' - when 'Manufacturer' - 'manufacturer' - end - direction = case order - when 'ascending' - 'asc' - when 'descending' - 'desc' - end + attribute = + case sort + when 'Model' + 'name' + when 'Manufacturer' + 'manufacturer' + end + direction = + case order + when 'ascending' + 'asc' + when 'descending' + 'desc' + end within '#model-list' do - expect(all('.text-align-left').map(&:text).reject(&:empty?)).to eq \ - @current_user.models.borrowable - .from_category_and_all_its_descendants(@category) - .order_by_attribute_and_direction(attribute, direction) - .paginate(page: 1, per_page: 20) - .map(&:name) + expect(all('.text-align-left').map(&:text).reject(&:empty?)).to eq @current_user.models + .borrowable + .from_category_and_all_its_descendants(@category) + .order_by_attribute_and_direction(attribute, direction) + .paginate(page: 1, per_page: 20) + .map(&:name) end end step 'those models are shown whose names or ' \ - 'manufacturers match the search term' do - expect( - all('#model-list .line', text: /.*#{@search_term}.*/i).first.text - ).to match(/.*#{@search_term}.*/) + 'manufacturers match the search term' do + expect(all('#model-list .line', text: /.*#{@search_term}.*/).first.text).to match( + /.*#{@search_term}.*/ + ) end step 'no lending period is set' do @@ -283,22 +275,18 @@ module ModelListSteps end step 'the list is filtered by models that are ' \ - 'available in that time frame' do + 'available in that time frame' do within '#model-list' do all('.line[data-id]', minimum: 1).each do |model_el| - model = \ - Model.find_by_id(model_el['data-id']) \ - || Model.find_by_id(model_el.reload['data-id']) + model = + Model.find_by_id(model_el['data-id']) || Model.find_by_id(model_el.reload['data-id']) expect(model).not_to be_nil - quantity = @current_user.inventory_pools.to_a.sum do |ip| - model - .availability_in(ip) - .maximum_available_in_period_summed_for_groups( - @start_date, - @end_date, - @current_user.entitlement_groups.map(&:id) + quantity = + @current_user.inventory_pools.to_a.sum do |ip| + model.availability_in(ip).maximum_available_in_period_summed_for_groups( + @start_date, @end_date, @current_user.entitlement_groups.map(&:id) ) - end + end if quantity <= 0 @unavailable_model_found = true expect(model_el[:class]['grayed-out']).to be @@ -332,7 +320,7 @@ module ModelListSteps end step 'I can also use a date picker to specify start and ' \ - 'end date instead of entering them by hand' do + 'end date instead of entering them by hand' do find('#start-date').set I18n.l Date.today find('.ui-datepicker') find('#end-date').set I18n.l Date.today @@ -340,16 +328,9 @@ module ModelListSteps end step 'I see the models of the selected category' do - @category = \ - Category.find \ - Rack::Utils.parse_nested_query( - URI.parse(current_url).query - )['category_id'] - models = \ - @current_user - .models - .borrowable - .from_category_and_all_its_descendants(@category) + @category = + Category.find Rack::Utils.parse_nested_query(URI.parse(current_url).query)['category_id'] + models = @current_user.models.borrowable.from_category_and_all_its_descendants(@category) within '#model-list' do sleep 2 all('.line[data-id]').reject { |el| el.text.blank? }.each do |model_line| @@ -361,15 +342,12 @@ module ModelListSteps step 'I see the sort options' do within '#model-sorting' do - expect(has_selector?('.dropdown *[data-sort]', visible: false)) - .to be true + expect(has_selector?('.dropdown *[data-sort]', visible: false)).to be true end end step 'I see the inventory pool selector' do - within '#ip-selector' do - expect(has_selector?('.dropdown', visible: false)).to be true - end + within '#ip-selector' doexpect(has_selector?('.dropdown', visible: false)).to be trueend end step 'I see filters for start and end date' do @@ -408,9 +386,7 @@ module ModelListSteps end step 'the next block of models is loaded and shown' do - within '#model-list' do - expect(all('.line').count).to be > 20 - end + within '#model-list' doexpect(all('.line').count).to be > 20end end step 'I scroll to the end of the list' do @@ -418,22 +394,15 @@ module ModelListSteps end step 'I scroll loading all pages' do - all('.page[data-page]').each do |data_page| - data_page.click - data_page.find('.line div', match: :first) - end + all('.page[data-page]').each(&:click) end step 'all models of the chosen category have been loaded and shown' do sleep 2 within '#model-list' do - expect(all('.line', minimum: 1).size) - .to eq \ - @current_user - .models - .borrowable - .from_category_and_all_its_descendants(@category) - .length + expect(all('.line', minimum: 1).size).to eq @current_user.models.borrowable + .from_category_and_all_its_descendants(@category) + .length end end @@ -452,20 +421,14 @@ module ModelListSteps end end expect( - has_selector?( - "img[src*='/models/#{@model.id}/image_thumb?offset=0']", - visible: false - ) + has_selector?("img[src*='/models/#{@model.id}/image_thumb?offset=0']", visible: false) ).to be true end end step 'there is a model with images, description and properties' do - @model = \ - @current_user - .models - .borrowable - .find do |m| + @model = + @current_user.models.borrowable.find do |m| !m.images.blank? and !m.description.blank? and !m.properties.blank? end end @@ -475,10 +438,8 @@ module ModelListSteps end step 'I select all inventory pools using the ' \ - '"All inventory pools" function' do - within '#ip-selector' do - find('.dropdown-item', text: _('All inventory pools')).click - end + '"All inventory pools" function' do + within '#ip-selector' dofind('.dropdown-item', text: _('All inventory pools')).clickend end step 'all inventory pools are selected' do @@ -490,23 +451,14 @@ module ModelListSteps end step 'the model list contains models from all inventory pools' do - ip_ids = \ - find('#ip-selector') - .all('.dropdown-item[data-id]') - .map { |ip| ip['data-id'] } + ip_ids = find('#ip-selector').all('.dropdown-item[data-id]').map { |ip| ip['data-id'] } step 'I scroll to the end of the list' sleep 2 - models = \ - @current_user - .models - .borrowable - .from_category_and_all_its_descendants(@category) - .all_from_inventory_pools(ip_ids) - .order_by_attribute_and_direction 'model', 'name' + models = + @current_user.models.borrowable.from_category_and_all_its_descendants(@category) + .all_from_inventory_pools(ip_ids).order_by_attribute_and_direction 'model', 'name' within '#model-list' do - expect( - all('.text-align-left').map(&:text).reject(&:empty?).uniq - ).to eq models.map(&:name) + expect(all('.text-align-left').map(&:text).reject(&:empty?).uniq).to eq models.map(&:name) end end @@ -547,9 +499,7 @@ module ModelListSteps end step 'all inventory pools are selected again in the inventory pool filter' do - within '#ip-selector' do - all("input[type='checkbox']").each &:checked? - end + within '#ip-selector' doall("input[type='checkbox']").each &:checked?end end step 'start and end date are both blank' do @@ -557,7 +507,7 @@ module ModelListSteps expect(find('input#end-date').value.empty?).to be true end - step 'the button \"Reset all filters\" is not visible' do + step 'the button "Reset all filters" is not visible' do expect(has_selector?('#reset-all-filter', visible: false)).to be true end @@ -570,12 +520,10 @@ module ModelListSteps expect(has_no_selector?('.page.fetched')).to be true sleep 2 within '#model-list' do - expect(all('.text-align-left').map(&:text).reject(&:empty?)).to eq \ - @current_user - .models - .from_category_and_all_its_descendants(@category) - .default_order - .map(&:name) + expect(all('.text-align-left').map(&:text).reject(&:empty?)).to eq @current_user.models + .from_category_and_all_its_descendants(@category) + .default_order + .map(&:name) end end @@ -586,8 +534,7 @@ module ModelListSteps step 'I release the focus from this field' expect(all('.ui-datepicker-calendar', visible: true).empty?).to be true find('#ip-selector').click - expect(has_selector?('#ip-selector .dropdown-item', visible: true)) - .to be true + expect(has_selector?('#ip-selector .dropdown-item', visible: true)).to be true all('#ip-selector .dropdown-item').first.click find('#model-sorting').click within '#model-sorting' do @@ -617,9 +564,7 @@ module ModelListSteps loop do find('#booking-calendar-end-date').native.send_key :up find('.end-date') - if page.has_selector?('.end-date.closed') - break - end + break if page.has_selector?('.end-date.closed') end while all('.end-date.selected.available:not(.closed)').empty? @@ -672,10 +617,7 @@ module ModelListSteps expect(find('#end-date').value).to be == I18n.localize(@end_date) end step 'the filter has previously selected inventory pool' do - expect( - has_selector?('#ip-selector .button', - text: @current_inventory_pool.name) - ).to be true + expect(has_selector?('#ip-selector .button', text: @current_inventory_pool.name)).to be true end step 'the filter has previously selected sorting option' do @@ -707,6 +649,4 @@ module ModelListSteps end end -RSpec.configure do |config| - config.include Borrow::Spec::ModelListSteps, borrow_model_list: true -end +RSpec.configure { |config| config.include Borrow::Spec::ModelListSteps, borrow_model_list: true } diff --git a/spec/steps/borrow/order_mail_steps.rb b/spec/steps/borrow/order_mail_steps.rb index e15ed652a3..5b27aa5e32 100644 --- a/spec/steps/borrow/order_mail_steps.rb +++ b/spec/steps/borrow/order_mail_steps.rb @@ -10,9 +10,8 @@ module OrderMailSteps include ::Spec::PersonasDumpSteps step "'deliver_received_order_notifications' is set to true " \ - 'in admin settings' do - Setting.first.update_attributes! \ - deliver_received_order_notifications: true + 'in admin settings' do + Setting.first.update_attributes! deliver_received_order_notifications: true end step 'there exists pool :letter' do |letter| @@ -24,29 +23,29 @@ module OrderMailSteps end step 'I have access to pool :letter' do |letter| - FactoryGirl.create \ - :access_right, - user: @customer, - inventory_pool: ivar_get("@pool_#{letter}"), - role: :customer + FactoryGirl.create :access_right, + user: @customer, inventory_pool: ivar_get("@pool_#{letter}"), role: :customer end - step 'pool :pool_letter has a borrowable item for model :model_letter' \ - do |pool_letter, model_letter| - FactoryGirl.create(:item, - model: ivar_get("@model_#{model_letter}"), - is_borrowable: true, - owner: ivar_get("@pool_#{pool_letter}"), - inventory_pool: ivar_get("@pool_#{pool_letter}")) + step 'pool :pool_letter has a borrowable item for model :model_letter' do |pool_letter, model_letter| + FactoryGirl.create( + :item, + model: ivar_get("@model_#{model_letter}"), + is_borrowable: true, + owner: ivar_get("@pool_#{pool_letter}"), + inventory_pool: ivar_get("@pool_#{pool_letter}") + ) end step 'the customer has an unsubmitted reservation for model :model_letter ' \ - 'and pool :pool_letter' do |model_letter, pool_letter| - FactoryGirl.create(:reservation, - status: :unsubmitted, - user: @customer, - inventory_pool: ivar_get("@pool_#{pool_letter}"), - model: ivar_get("@model_#{model_letter}")) + 'and pool :pool_letter' do |model_letter, pool_letter| + FactoryGirl.create( + :reservation, + status: :unsubmitted, + user: @customer, + inventory_pool: ivar_get("@pool_#{pool_letter}"), + model: ivar_get("@model_#{model_letter}") + ) end step 'I open the current order page' do @@ -66,26 +65,24 @@ module OrderMailSteps end step 'one mail with received template was sent to pool :letter' do |letter| - m = ActionMailer::Base.deliveries.find do |mail| - mail.to.first == ivar_get("@pool_#{letter}").email and - mail.subject.match(/received/i) - end + m = + ActionMailer::Base.deliveries.find do |mail| + mail.to.first == ivar_get("@pool_#{letter}").email and mail.subject.match(/received/) + end expect(m).to be end step 'one mail with submitted template for pool :letter ' \ - 'was sent to the customer' do |letter| - m = ActionMailer::Base.deliveries.find do |mail| - mail.to.first == @customer.email and - mail.subject.match(/submitted/i) and - mail.body.match(/#{ivar_get("@pool_#{letter}").name}/) - end + 'was sent to the customer' do |letter| + m = + ActionMailer::Base.deliveries.find do |mail| + mail.to.first == @customer.email and mail.subject.match(/submitted/) and + mail.body.match(/#{ivar_get("@pool_#{letter}").name}/) + end expect(m).to be end end end end -RSpec.configure do |config| - config.include Borrow::Spec::OrderMailSteps, borrow_order_mails: true -end +RSpec.configure { |config| config.include Borrow::Spec::OrderMailSteps, borrow_order_mails: true } diff --git a/spec/steps/borrow/submit_order_steps.rb b/spec/steps/borrow/submit_order_steps.rb index f9a3897b31..1ac230ee16 100644 --- a/spec/steps/borrow/submit_order_steps.rb +++ b/spec/steps/borrow/submit_order_steps.rb @@ -11,8 +11,9 @@ module SubmitOrderSteps step 'I am suspended for a pool I am a customer of' do ar = AccessRight.find_by(inventory_pool: @inventory_pool, role: :customer) - ar.update_attributes(suspended_until: Date.tomorrow, - suspended_reason: Faker::Lorem.sentence) + ar.update_attributes( + suspended_until: Date.tomorrow, suspended_reason: Faker::Lorem.sentence + ) end step 'there is a borrowable item in this pool' do @@ -20,12 +21,11 @@ module SubmitOrderSteps end step 'I have an unsubmitted order for this pool ' \ - 'and the model of this item' do - FactoryGirl.create(:reservation, - user: @customer, - inventory_pool: @inventory_pool, - status: :unsubmitted, - model: @item.model) + 'and the model of this item' do + FactoryGirl.create( + :reservation, + user: @customer, inventory_pool: @inventory_pool, status: :unsubmitted, model: @item.model + ) end step 'I open the page for this order' do diff --git a/spec/steps/current_order_steps.rb b/spec/steps/current_order_steps.rb index 8d71cf5f38..780f610d46 100644 --- a/spec/steps/current_order_steps.rb +++ b/spec/steps/current_order_steps.rb @@ -10,17 +10,15 @@ module CurrentOrderSteps include ::Spec::PersonasDumpSteps step 'I have an unsubmitted order' do - FactoryGirl.create(:reservation, - user: @current_user, - status: :unsubmitted, - inventory_pool: @inventory_pool) + FactoryGirl.create( + :reservation, user: @current_user, status: :unsubmitted, inventory_pool: @inventory_pool + ) end step 'each reservation line displays start and end date' do @current_user.reservations.unsubmitted.each do |r| within ".line[data-ids*='#{r.id}']" do - expect(page).to have_content \ - "#{I18n.l r.start_date} - #{I18n.l r.end_date}" + expect(page).to have_content "#{I18n.l r.start_date} - #{I18n.l r.end_date}" end end end diff --git a/spec/steps/integration/time_zone_steps.rb b/spec/steps/integration/time_zone_steps.rb index 326b29f5ff..c8cc161b7e 100644 --- a/spec/steps/integration/time_zone_steps.rb +++ b/spec/steps/integration/time_zone_steps.rb @@ -10,7 +10,7 @@ module TimeZoneSteps step 'the time zone is set to :time_zone' do |time_zone| ApplicationRecord.connection.execute <<-SQL - UPDATE settings SET time_zone = '#{time_zone}' + UPDATE settings SET time_zone = '#{time_zone}' SQL end @@ -38,6 +38,4 @@ module TimeZoneSteps end end -RSpec.configure do |config| - config.include Spec::TimeZoneSteps, time_zone: true -end +RSpec.configure { |config| config.include Spec::TimeZoneSteps, time_zone: true } diff --git a/spec/steps/manage/availability_calendar_steps.rb b/spec/steps/manage/availability_calendar_steps.rb index d9ea874931..0d8c4c4056 100644 --- a/spec/steps/manage/availability_calendar_steps.rb +++ b/spec/steps/manage/availability_calendar_steps.rb @@ -13,12 +13,11 @@ module AvailabilityCalendarSteps step 'there is a Group :group_name' do |group_name| @inventory_pool ||= @current_user.inventory_pools.managed.first - @group_members = 5.times.map do - FactoryGirl.create(:customer, inventory_pool: @inventory_pool) - end - @group = FactoryGirl.create \ - :group, name: group_name, users: @group_members, \ - inventory_pool: @inventory_pool + @group_members = + 5.times.map { FactoryGirl.create(:customer, inventory_pool: @inventory_pool) } + @group = + FactoryGirl.create :group, + name: group_name, users: @group_members, inventory_pool: @inventory_pool end step 'there is a Model :model_name' do |model_name| @@ -26,46 +25,46 @@ module AvailabilityCalendarSteps end step 'this Model has :num lendable Items' do |num| - @items = num.to_i.times.map do - FactoryGirl.create( - :item, - model: @model, - inventory_pool: @current_inventory_pool - ) - end + @items = + num.to_i.times.map do + FactoryGirl.create(:item, model: @model, inventory_pool: @current_inventory_pool) + end end step 'those Items are all asigned to this Group' do - FactoryGirl.create(:entitlement, - model: @model, - quantity: @items.length, - entitlement_group: @group) + FactoryGirl.create( + :entitlement, model: @model, quantity: @items.length, entitlement_group: @group + ) end step ':num of those Items are already lent' do |num| @lent_items = @items.sample(num.to_i) - FactoryGirl.create(:open_contract, - items: @lent_items, - user: @group_members.sample, - inventory_pool: @inventory_pool, - start_date: Date.today, - end_date: Date.tomorrow) + FactoryGirl.create( + :open_contract, + items: @lent_items, + user: @group_members.sample, + inventory_pool: @inventory_pool, + start_date: Date.today, + end_date: Date.tomorrow + ) end step ':num of those Items are in the current Order ' \ - 'from a user belonging to this Group' do |num| + 'from a user belonging to this Group' do |num| order_user = @group_members.sample - @order = FactoryGirl.create(:order, - state: :submitted, - user: order_user, - inventory_pool: @inventory_pool) + @order = + FactoryGirl.create( + :order, state: :submitted, user: order_user, inventory_pool: @inventory_pool + ) num.to_i.times.each do |item| - FactoryGirl.create(:reservation, - status: :submitted, - model: @model, - user: order_user, - order: @order, - inventory_pool: @inventory_pool) + FactoryGirl.create( + :reservation, + status: :submitted, + model: @model, + user: order_user, + order: @order, + inventory_pool: @inventory_pool + ) end end @@ -79,26 +78,23 @@ module AvailabilityCalendarSteps expect(numbers_col_txt).to eq label end - step 'the timeline shows :as assigned of :av available for the group' \ - do |as, av| + step 'the timeline shows :as assigned of :av available for the group' do |as, av| @order_line ||= find('#lines .order-line', text: @model.product) within(@order_line.find('.multibutton')) do - find('.dropdown-holder').click - - new_window = window_opened_by { find('[data-open-time-line]').click } - within_window new_window do - find('div.row > div > div > div', text: 'Total') - find( - "div[title='Entitlement Info #{@group.id}']", - text: "#{av} reserviert für Gruppe #{@group.name}"\ - ', davon zugewiesen' - ) - expect( - find("div[title='Entitlement #{@group.id}']") - .text.start_with?(as) - ).to eq(true) - new_window.close - end + find('.dropdown-holder').click + + new_window = window_opened_by { find('[data-open-time-line]').click } + within_window new_window do + find('div.row > div > div > div', text: 'Total') + find( + "div[title='Entitlement Info #{@group.id}']", + text: + "#{av} reserviert für Gruppe #{@group.name}" \ + ', davon zugewiesen' + ) + expect(find("div[title='Entitlement #{@group.id}']").text.start_with?(as)).to eq(true) + new_window.close + end end end @@ -107,20 +103,18 @@ module AvailabilityCalendarSteps within('.modal.in') do day_cell = find('td.start-date') total_quantity = day_cell.find('.fc-day-content .total_quantity').text - displayed_availabilty = day_cell.find('.fc-day-content') - .text.sub(/#{total_quantity}$/, '').strip + displayed_availabilty = + day_cell.find('.fc-day-content').text.sub(/#{total_quantity}$/, '').strip expect(displayed_availabilty).to eq num find('div.modal-close', text: _('Cancel')).click end end - end end end RSpec.configure do |config| - config.include Manage::Spec::AvailabilityCalendarSteps, - manage_availability_calendar: true + config.include Manage::Spec::AvailabilityCalendarSteps, manage_availability_calendar: true end diff --git a/spec/steps/manage/case_insensitive_inventory_code_steps.rb b/spec/steps/manage/case_insensitive_inventory_code_steps.rb index 75f7a50244..9b529d552b 100644 --- a/spec/steps/manage/case_insensitive_inventory_code_steps.rb +++ b/spec/steps/manage/case_insensitive_inventory_code_steps.rb @@ -11,10 +11,13 @@ module CaseInsensitiveInventoryCodeSteps step 'there is an item with uppercase inventory code in the current pool' do @inventory_code = Faker::Lorem.word.upcase - @item = FactoryGirl.create(:item, - inventory_pool: @current_inventory_pool, - owner: @current_inventory_pool, - inventory_code: @inventory_code) + @item = + FactoryGirl.create( + :item, + inventory_pool: @current_inventory_pool, + owner: @current_inventory_pool, + inventory_code: @inventory_code + ) end step 'I open the page for creating a new item' do @@ -27,15 +30,12 @@ module CaseInsensitiveInventoryCodeSteps step 'I select a model' do model = @current_inventory_pool.models.first - type_into_and_select_from_autocomplete( - 'div#model_id input', - model.name - ) + type_into_and_select_from_autocomplete('div#model_id input', model.name) end step 'I see an error message in regards to ' \ - 'already existing inventory code' do - find('#error-modal', text: _('Inventory code has already been taken')) + 'already existing inventory code' do + find('#error-modal', text: _('Inventory code has already been taken')) end step 'the item was not saved' do @@ -43,8 +43,7 @@ module CaseInsensitiveInventoryCodeSteps end step 'there is a customer in the current pool' do - @customer = \ - FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) + @customer = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) end step 'I open hand over for this customer' do @@ -78,9 +77,7 @@ module CaseInsensitiveInventoryCodeSteps end step 'the new item line was added to the hand over' do - within '#lines' do - find("input[value='#{@inventory_code}']") - end + within '#lines' dofind("input[value='#{@inventory_code}']")end end step 'the item is selected for take back' do @@ -88,23 +85,24 @@ module CaseInsensitiveInventoryCodeSteps end step 'the new item line was created in the data base' do - line = Reservation.find_by(user_id: @customer.id, - item_id: @item.id, - status: :approved, - inventory_pool_id: @current_inventory_pool.id) + line = + Reservation.find_by( + user_id: @customer.id, + item_id: @item.id, + status: :approved, + inventory_pool_id: @current_inventory_pool.id + ) expect(line).to be end step 'I choose a building' do - type_into_and_select_from_autocomplete \ - 'div#building_id input[name="item[building_id]"]', - Building.general.name + type_into_and_select_from_autocomplete 'div#building_id input[name="item[building_id]"]', + Building.general.name end step 'I choose a room' do - type_into_and_select_from_autocomplete \ - 'div#room_id input[name="item[room_id]"]', - Building.general.rooms.find_by_general(true).name + type_into_and_select_from_autocomplete 'div#room_id input[name="item[room_id]"]', + Building.general.rooms.find_by_general(true).name end end end @@ -112,5 +110,5 @@ module CaseInsensitiveInventoryCodeSteps RSpec.configure do |config| config.include Manage::Spec::CaseInsensitiveInventoryCodeSteps, - manage_case_insensitive_inventory_code: true + manage_case_insensitive_inventory_code: true end diff --git a/spec/steps/manage/category_crud_steps.rb b/spec/steps/manage/category_crud_steps.rb index bcb0b89602..379f85100b 100644 --- a/spec/steps/manage/category_crud_steps.rb +++ b/spec/steps/manage/category_crud_steps.rb @@ -34,9 +34,7 @@ module CategoryCrudSteps end step 'I remove the image' do - within '#images' do - find("[data-type='inline-entry'] [data-remove]").click - end + within '#images' dofind("[data-type='inline-entry'] [data-remove]").clickend end step 'I add another image' do @@ -63,6 +61,5 @@ def add_image(image) end RSpec.configure do |config| - config.include Manage::Spec::CategoryCrudSteps, - manage_category_crud: true + config.include Manage::Spec::CategoryCrudSteps, manage_category_crud: true end diff --git a/spec/steps/manage/create_software_license_steps.rb b/spec/steps/manage/create_software_license_steps.rb index 2079ec5401..420c13de57 100644 --- a/spec/steps/manage/create_software_license_steps.rb +++ b/spec/steps/manage/create_software_license_steps.rb @@ -13,59 +13,44 @@ module CreateSoftwareLicenseSteps visit manage_new_item_path(@current_inventory_pool, type: :license) end - step 'the possible select values for :field are as follows:' \ - do |field, table| + step 'the possible select values for :field are as follows:' do |field, table| within find('.field', text: _(field)) do options = all('select option').map(&:text) expect(table.raw.flatten).to be == options end end - step 'the possible radio button values for :field are as follows:' \ - do |field, table| + step 'the possible radio button values for :field are as follows:' do |field, table| within find('.field', text: _(field)) do table.raw.flatten.each do |val| - within('label', text: val) do - find("input[type='radio']") - end + within('label', text: val) { find("input[type='radio']") } end end end - step 'the possible checkbox values for :field are as follows:' \ - do |field, table| + step 'the possible checkbox values for :field are as follows:' do |field, table| within find('.field', text: _(field)) do table.raw.flatten.each do |val| - within('label', text: val) do - find("input[type='checkbox']") - end + within('label', text: val) { find("input[type='checkbox']") } end end end step 'for :field one can select a date' do |field| - within find('.field', text: _(field)) do - find('input') - end + within find('.field', text: _(field)) dofind('input')end end step 'for :field one can enter some value' do |field| - within find('.field', text: _(field)) do - find("input[type='text'],textarea") - end + within find('.field', text: _(field)) dofind("input[type='text'],textarea")end end step 'for :field one can choose a value via autocomplete' do |field| - within find('.field', text: _(field)) do - find('input') - end + within find('.field', text: _(field)) dofind('input')end end step 'the default radio button for :field is :value' do |field, value| within find('.field', text: _(field)) do - within('label', text: _(value)) do - expect(find('input').checked?).to eq(true) - end + within('label', text: _(value)) { expect(find('input').checked?).to eq(true) } end end @@ -131,9 +116,7 @@ module CreateSoftwareLicenseSteps find('input[data-quantity-allocation]').set quantity find('input[data-room-allocation]').set room end - @attributes[:properties].merge!( - quantity_allocations: [{ quantity: quantity, room: room }] - ) + @attributes[:properties].merge!(quantity_allocations: [{ quantity: quantity, room: room }]) end step "I check 'Linux' for operating system" do @@ -150,9 +133,7 @@ module CreateSoftwareLicenseSteps end step 'I set a date for license expiration' do - within('.field', text: _('License expiration')) do - find('input').set '01/01/2099' - end + within('.field', text: _('License expiration')) { find('input').set '01/01/2099' } @attributes[:properties].merge!(license_expiration: '2099-01-01') end @@ -162,8 +143,7 @@ module CreateSoftwareLicenseSteps end step 'the field :field is not visible' do |field| - expect(page).not_to \ - have_selector('.field', text: /^#{field}/) + expect(page).not_to have_selector('.field', text: /^#{field}/) end step "I select 'Yes' for maintenance contract" do @@ -172,9 +152,7 @@ module CreateSoftwareLicenseSteps end step 'I set a date for maintenance expiration' do - within('.field', text: _('Maintenance expiration')) do - find('input').set '01/01/2099' - end + within('.field', text: _('Maintenance expiration')) { find('input').set '01/01/2099' } @attributes[:properties].merge!(maintenance_expiration: '2099-01-01') end @@ -186,9 +164,7 @@ module CreateSoftwareLicenseSteps end step "I select 'OK' for borrowable" do - within('.field', text: _('Borrowable')) do - find('label', text: 'OK').find('input').click - end + within('.field', text: _('Borrowable')) { find('label', text: 'OK').find('input').click } @attributes.merge!(is_borrowable: true) end @@ -206,11 +182,8 @@ module CreateSoftwareLicenseSteps step 'the license has been saved in the database successfully' do license = nil - wait_until do - license = Item.find_by_inventory_code(@inventory_code) - end - expect(license.attributes.deep_include? @attributes.deep_stringify_keys) - .to be true + wait_until { license = Item.find_by_inventory_code(@inventory_code) } + expect(license.attributes.deep_include? @attributes.deep_stringify_keys).to be true end ############################################################################# @@ -218,8 +191,8 @@ module CreateSoftwareLicenseSteps class ::Hash def deep_include?(sub_hash) sub_hash.keys.all? do |key| - self.key?(key) && ( - if sub_hash[key].is_a?(Hash) + self.key?(key) && + (if sub_hash[key].is_a?(Hash) self[key].is_a?(Hash) && self[key].deep_include?(sub_hash[key]) else self[key] == sub_hash[key] @@ -232,6 +205,5 @@ def deep_include?(sub_hash) end RSpec.configure do |config| - config.include Manage::Spec::CreateSoftwareLicenseSteps, - manage_create_software_license: true + config.include Manage::Spec::CreateSoftwareLicenseSteps, manage_create_software_license: true end diff --git a/spec/steps/manage/delegations_steps.rb b/spec/steps/manage/delegations_steps.rb index 8cf5bf2ba8..ab8ba63c3e 100644 --- a/spec/steps/manage/delegations_steps.rb +++ b/spec/steps/manage/delegations_steps.rb @@ -17,93 +17,96 @@ module DelegationsSteps end step 'the user has a session for the delegation' do - FactoryGirl.create(:user_session, - user: @user, - delegation: @delegation) + FactoryGirl.create(:user_session, user: @user, delegation: @delegation) end step 'the user has unsubmitted reservation for the delegation' do - FactoryGirl.create(:reservation, - status: :unsubmitted, - user: @delegation, - delegated_user: @user, - inventory_pool: @current_inventory_pool) + FactoryGirl.create( + :reservation, + status: :unsubmitted, + user: @delegation, + delegated_user: @user, + inventory_pool: @current_inventory_pool + ) end step 'the user has submitted reservation for the delegation' do ActiveRecord::Base.transaction do - order = FactoryGirl.create(:order, - user: @delegation, - state: :submitted, - inventory_pool: @current_inventory_pool) - @submitted_reservation = \ - FactoryGirl.create(:reservation, - :with_assigned_item, - status: :submitted, - user: @delegation, - order: order, - delegated_user: @user, - inventory_pool: @current_inventory_pool) + order = + FactoryGirl.create( + :order, user: @delegation, state: :submitted, inventory_pool: @current_inventory_pool + ) + @submitted_reservation = + FactoryGirl.create( + :reservation, + :with_assigned_item, + status: :submitted, + user: @delegation, + order: order, + delegated_user: @user, + inventory_pool: @current_inventory_pool + ) end end step 'the user has rejected reservation for the delegation' do ActiveRecord::Base.transaction do - order = FactoryGirl.create(:order, - user: @delegation, - state: :rejected, - inventory_pool: @current_inventory_pool) - @rejected_reservation = \ - FactoryGirl.create(:reservation, - :with_assigned_item, - status: :rejected, - user: @delegation, - order: order, - delegated_user: @user, - inventory_pool: @current_inventory_pool) + order = + FactoryGirl.create( + :order, user: @delegation, state: :rejected, inventory_pool: @current_inventory_pool + ) + @rejected_reservation = + FactoryGirl.create( + :reservation, + :with_assigned_item, + status: :rejected, + user: @delegation, + order: order, + delegated_user: @user, + inventory_pool: @current_inventory_pool + ) end end step 'the user has closed reservation for the delegation' do ActiveRecord::Base.transaction do - contract = FactoryGirl.create(:closed_contract, - user: @delegation, - inventory_pool: @current_inventory_pool) - @closed_reservation = \ - FactoryGirl.create(:reservation, - :with_assigned_item, - status: :closed, - user: @delegation, - delegated_user: @user, - contract: contract, - inventory_pool: @current_inventory_pool) + contract = + FactoryGirl.create( + :closed_contract, user: @delegation, inventory_pool: @current_inventory_pool + ) + @closed_reservation = + FactoryGirl.create( + :reservation, + :with_assigned_item, + status: :closed, + user: @delegation, + delegated_user: @user, + contract: contract, + inventory_pool: @current_inventory_pool + ) end end step 'the user has a submitted reservation' do ActiveRecord::Base.transaction do - order = FactoryGirl.create(:order, - user: @user, - state: :submitted, - inventory_pool: @current_inventory_pool) - @submitted_reservation = \ - FactoryGirl.create(:reservation, - status: :submitted, - user: @user, - order: order, - inventory_pool: @current_inventory_pool) + order = + FactoryGirl.create( + :order, user: @user, state: :submitted, inventory_pool: @current_inventory_pool + ) + @submitted_reservation = + FactoryGirl.create( + :reservation, + status: :submitted, user: @user, order: order, inventory_pool: @current_inventory_pool + ) end end step 'I open the edit page of the delegation' do - visit manage_edit_inventory_pool_user_path(@current_inventory_pool, - @delegation) + visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @delegation) end step 'I remove the user' do - find('#users .line', text: @user.name) - .find('button', _('Remove')) - .click + find('#users .line', text: @user.name).find('button', _('Remove')).click end step 'I save' do @@ -111,26 +114,23 @@ module DelegationsSteps end step 'the user is no longer member of the delegation' do - expect(@delegation.reload.delegated_users.map(&:id)) - .not_to include @user.id + expect(@delegation.reload.delegated_users.map(&:id)).not_to include @user.id end step 'the user does not have any unsubmitted reservations ' \ - 'for the delegation' do + 'for the delegation' do expect( - Reservation.where(user: @delegation, - delegated_user: @user, - status: :unsubmitted) + Reservation.where(user: @delegation, delegated_user: @user, status: :unsubmitted) ).to be_empty end step 'the user has still the same submitted reservation ' \ - 'for the delegation' do + 'for the delegation' do expect(@submitted_reservation.reload).to be end step 'the user has still the same submitted reservation ' \ - 'for the delegation' do + 'for the delegation' do expect(@submitted_reservation.reload).to be end @@ -151,14 +151,10 @@ module DelegationsSteps end step 'the user is still member of the delegation' do - expect(@delegation.reload.delegated_users.map(&:id)) - .to include @user.id + expect(@delegation.reload.delegated_users.map(&:id)).to include @user.id end end end end -RSpec.configure do |config| - config.include Manage::Spec::DelegationsSteps, - manage_delegations: true -end +RSpec.configure { |config| config.include Manage::Spec::DelegationsSteps, manage_delegations: true } diff --git a/spec/steps/manage/edit_user_steps.rb b/spec/steps/manage/edit_user_steps.rb index 7f769ae773..ddb155f6a9 100644 --- a/spec/steps/manage/edit_user_steps.rb +++ b/spec/steps/manage/edit_user_steps.rb @@ -12,8 +12,7 @@ module EditUserSteps include ::Spec::PersonasDumpSteps step 'there is a group in the current pool' do - @group = FactoryGirl.create(:group, - inventory_pool: @current_inventory_pool) + @group = FactoryGirl.create(:group, inventory_pool: @current_inventory_pool) end step 'the user belongs to this group' do @@ -21,14 +20,11 @@ module EditUserSteps end step 'open the edit page of the user' do - visit manage_edit_inventory_pool_user_path(@current_inventory_pool, - @user) + visit manage_edit_inventory_pool_user_path(@current_inventory_pool, @user) end step 'I remove the group' do - within '#change-groups .list-of-lines' do - click_button _('Remove') - end + within '#change-groups .list-of-lines' doclick_button _('Remove')end end step 'I save' do @@ -45,7 +41,4 @@ module EditUserSteps end end -RSpec.configure do |config| - config.include Manage::Spec::EditUserSteps, - manage_edit_user: true -end +RSpec.configure { |config| config.include Manage::Spec::EditUserSteps, manage_edit_user: true } diff --git a/spec/steps/manage/global_search_steps.rb b/spec/steps/manage/global_search_steps.rb index e8afcd994c..07fe22b499 100644 --- a/spec/steps/manage/global_search_steps.rb +++ b/spec/steps/manage/global_search_steps.rb @@ -13,82 +13,83 @@ module GlobalSearchSteps include ::Spec::LoginSteps include ::Spec::PersonasDumpSteps - step 'a signed contract :n for a user matching :search_string exists' \ - do |n, search_string| - user = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool, - firstname: search_string) - instance_variable_set \ - "@contract_#{n}", - FactoryGirl.create(:open_contract, - user: user, - inventory_pool: @current_inventory_pool) + step 'a signed contract :n for a user matching :search_string exists' do |n, search_string| + user = + FactoryGirl.create( + :customer, inventory_pool: @current_inventory_pool, firstname: search_string + ) + instance_variable_set "@contract_#{n}", + FactoryGirl.create( + :open_contract, user: user, inventory_pool: @current_inventory_pool + ) end step 'a signed contract :n for a second user matching ' \ - ':search_string exists' \ - do |n, search_string| - user = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool, - firstname: search_string) - instance_variable_set \ - "@contract_#{n}", - FactoryGirl.create(:open_contract, - user: user, - inventory_pool: @current_inventory_pool) - end - - step 'a signed contract :n for a delegation matching :search_string exists' \ - do |n, search_string| - delegator_user = \ - FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool) - delegation = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool, - delegator_user: delegator_user, - firstname: search_string) - instance_variable_set \ - "@contract_#{n}", - FactoryGirl.create(:open_contract, - user: delegation, - inventory_pool: @current_inventory_pool) + ':search_string exists' do |n, search_string| + user = + FactoryGirl.create( + :customer, inventory_pool: @current_inventory_pool, firstname: search_string + ) + instance_variable_set "@contract_#{n}", + FactoryGirl.create( + :open_contract, user: user, inventory_pool: @current_inventory_pool + ) + end + + step 'a signed contract :n for a delegation matching :search_string exists' do |n, search_string| + delegator_user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) + delegation = + FactoryGirl.create( + :customer, + inventory_pool: @current_inventory_pool, + delegator_user: delegator_user, + firstname: search_string + ) + instance_variable_set "@contract_#{n}", + FactoryGirl.create( + :open_contract, + user: delegation, inventory_pool: @current_inventory_pool + ) end step 'a closed contract :n for a user matching :search_string ' \ - 'created on :date exists' do |n, search_string, date| - user = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool, - firstname: search_string) - instance_variable_set \ - "@contract_#{n}", - FactoryGirl.create(:closed_contract, - created_at: Date.strptime(date, '%d.%m.%Y'), - user: user, - inventory_pool: @current_inventory_pool) + 'created on :date exists' do |n, search_string, date| + user = + FactoryGirl.create( + :customer, inventory_pool: @current_inventory_pool, firstname: search_string + ) + instance_variable_set "@contract_#{n}", + FactoryGirl.create( + :closed_contract, + created_at: Date.strptime(date, '%d.%m.%Y'), + user: user, + inventory_pool: @current_inventory_pool + ) end step 'a closed contract :n for a contact person of a delegation ' \ - 'matching :search_string created on :date exists' \ - do |n, search_string, date| - contact_person = \ - FactoryGirl.create(:customer, - firstname: search_string, - inventory_pool: @current_inventory_pool) - delegator_user = \ - FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool) - delegation = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool, - delegator_user: delegator_user, - firstname: search_string) + 'matching :search_string created on :date exists' do |n, search_string, date| + contact_person = + FactoryGirl.create( + :customer, firstname: search_string, inventory_pool: @current_inventory_pool + ) + delegator_user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) + delegation = + FactoryGirl.create( + :customer, + inventory_pool: @current_inventory_pool, + delegator_user: delegator_user, + firstname: search_string + ) delegation.delegated_users << contact_person - instance_variable_set \ - "@contract_#{n}", - FactoryGirl.create(:closed_contract, - created_at: Date.strptime(date, '%d.%m.%Y'), - user: delegation, - contact_person: contact_person, - inventory_pool: @current_inventory_pool) + instance_variable_set "@contract_#{n}", + FactoryGirl.create( + :closed_contract, + created_at: Date.strptime(date, '%d.%m.%Y'), + user: delegation, + contact_person: contact_person, + inventory_pool: @current_inventory_pool + ) end step 'I search globally for :search_string' do |search_string| @@ -104,8 +105,7 @@ module GlobalSearchSteps step 'within the contracts box I see contracts sorted as follows:' do |table| within '#contracts .list-of-lines' do expect(all('.row[data-id]').map { |r| r['data-id'] }).to be == - table.raw.flatten.map \ - { |row| instance_variable_get("@#{row.sub(' ', '_')}").id } + table.raw.flatten.map { |row| instance_variable_get("@#{row.sub(' ', '_')}").id } end end @@ -118,9 +118,8 @@ module GlobalSearchSteps end step 'there is a retired item' do - @retired_item = FactoryGirl.create(:item, - retired: Date.today, - retired_reason: Faker::Lorem.sentence) + @retired_item = + FactoryGirl.create(:item, retired: Date.today, retired_reason: Faker::Lorem.sentence) end step 'there is an inactive inventory pool' do @@ -141,9 +140,7 @@ module GlobalSearchSteps end step 'I see within the items box the item' do - within '#items' do - find('.line', text: @retired_item.inventory_code) - end + within '#items' dofind('.line', text: @retired_item.inventory_code)end end step 'the item line contains the name of the inactive inventory pool' do @@ -164,8 +161,7 @@ def check_contracts_within_container(css_path, table) expect(find(css_path)).not_to have_selector('[data-loading]') within css_path do expect(all('.row[data-id]').map { |r| r['data-id'] }).to be == - table.raw.flatten.map \ - { |row| instance_variable_get("@#{row.sub(' ', '_')}").id } + table.raw.flatten.map { |row| instance_variable_get("@#{row.sub(' ', '_')}").id } end end end @@ -173,6 +169,5 @@ def check_contracts_within_container(css_path, table) end RSpec.configure do |config| - config.include Manage::Spec::GlobalSearchSteps, - manage_global_search: true + config.include Manage::Spec::GlobalSearchSteps, manage_global_search: true end diff --git a/spec/steps/manage/hand_over_steps.rb b/spec/steps/manage/hand_over_steps.rb index 937c8b6632..b92d91a92a 100644 --- a/spec/steps/manage/hand_over_steps.rb +++ b/spec/steps/manage/hand_over_steps.rb @@ -23,12 +23,14 @@ module HandOverSteps end step 'the customer has borrowed the item for today' do - FactoryGirl.create(:open_contract, - user: @customer, - inventory_pool: @inventory_pool, - start_date: Date.today, - end_date: Date.tomorrow, - items: [@item]) + FactoryGirl.create( + :open_contract, + user: @customer, + inventory_pool: @inventory_pool, + start_date: Date.today, + end_date: Date.tomorrow, + items: [@item] + ) end step 'I open hand over for the user' do @@ -45,10 +47,10 @@ module HandOverSteps end step 'I see an error message that the item ' \ - 'is already assigned to a contract' do - expect(find('#flash .error').text) - .to match \ - /#{@item.inventory_code} is already assigned to a different contract/ + 'is already assigned to a contract' do + expect(find('#flash .error').text).to match / + #{@item.inventory_code} is already assigned to a different contract + / end step 'the reservation line was not created' do @@ -57,54 +59,43 @@ module HandOverSteps expect(find('#lines').text).to be_blank end - step "I enter the item's model name in the :add_assign input field" \ - do |add_assign| + step "I enter the item's model name in the :add_assign input field" do |add_assign| raise unless add_assign == 'Add/Assign' find('#assign-or-add-input input').set @item.model.name end step "I choose the item's model name from the displayed dropdown" do - within '.ui-autocomplete' do - find('a', text: @item.model.name).click - end + within '.ui-autocomplete' dofind('a', text: @item.model.name).clickend end step "a reservation line for the item's model name was added" do - within '#lines' do - find('.line', text: @item.model.name) - end + within '#lines' dofind('.line', text: @item.model.name)end end - step "I enter the license's model name in the :add_assign input field" \ - do |add_assign| + step "I enter the license's model name in the :add_assign input field" do |add_assign| raise unless add_assign == 'Add/Assign' find('#assign-or-add-input input').set @license.model.name end step "I choose the license's model name from the displayed dropdown" do - within '.ui-autocomplete' do - find('a', text: @license.model.name).click - end + within '.ui-autocomplete' dofind('a', text: @license.model.name).clickend end step "a reservation line for the license's model name was added" do - within '#lines' do - find('.line', text: @license.model.name) - end + within '#lines' dofind('.line', text: @license.model.name)end end step 'I assign the item to its model line' do - find('#lines .line', text: @item.model.name) - .find('[data-assign-item-form] input') - .set @item.inventory_code + find('#lines .line', text: @item.model.name).find('[data-assign-item-form] input').set @item + .inventory_code find('.ui-autocomplete a', text: @item.inventory_code).click end step 'I assign the license to its model line' do rescue_displaced_flash do - find('#lines .line', text: @license.model.name) - .find('[data-assign-item-form] input') - .set @license.inventory_code + find('#lines .line', text: @license.model.name).find( + '[data-assign-item-form] input' + ).set @license.inventory_code find('.ui-autocomplete a', text: @license.inventory_code).click end end @@ -114,9 +105,7 @@ module HandOverSteps end step 'I enter the purpose' do - within '.modal' do - fill_in 'purpose', with: Faker::Lorem.sentence - end + within '.modal' dofill_in 'purpose', with: Faker::Lorem.sentenceend end step 'I click on "Hand Over"' do @@ -124,44 +113,34 @@ module HandOverSteps end step 'I switch to the contract window' do - wait_until do - page.driver.browser.window_handles.count > 1 - end + wait_until { page.driver.browser.window_handles.count > 1 } last_window = page.driver.browser.window_handles.last page.driver.browser.switch_to.window last_window end step 'the contract includes the inventory code of the item' do - within '.contract' do - page.should have_content @item.inventory_code - end + within '.contract' dopage.should have_content @item.inventory_codeend end step 'the contract includes the inventory code of the license' do - within '.contract' do - page.should have_content @item.inventory_code - end + within '.contract' dopage.should have_content @item.inventory_codeend end - step 'I add item\'s model line to the hand over' do + step "I add item's model line to the hand over" do within '#assign-or-add' do find('#assign-or-add-input input').set @item.model.name find('.ui-autocomplete a', text: @item.model.name).click end end - step 'I click in the assign item input field on the item\'s model line' do - within('.line[data-id]', text: @item.model.name) do - find('input[data-assign-item]').click - end + step "I click in the assign item input field on the item's model line" do + within('.line[data-id]', text: @item.model.name) { find('input[data-assign-item]').click } end - step 'I see item\'s location in the assign item dropdown' do + step "I see item's location in the assign item dropdown" do within('.line[data-id]', text: @item.model.name) do within('.ui-autocomplete') do - within('a', text: @item.inventory_code) do - expect(page).to have_content @item.location - end + within('a', text: @item.inventory_code) { expect(page).to have_content @item.location } end end end @@ -169,7 +148,4 @@ module HandOverSteps end end -RSpec.configure do |config| - config.include Manage::Spec::HandOverSteps, - manage_hand_over: true -end +RSpec.configure { |config| config.include Manage::Spec::HandOverSteps, manage_hand_over: true } diff --git a/spec/steps/manage/inactive_inventory_pools_steps.rb b/spec/steps/manage/inactive_inventory_pools_steps.rb index 1cdc3c7b16..a820835c1c 100644 --- a/spec/steps/manage/inactive_inventory_pools_steps.rb +++ b/spec/steps/manage/inactive_inventory_pools_steps.rb @@ -10,13 +10,12 @@ module InactiveInventoryPoolSteps include ::Spec::PersonasDumpSteps step 'there exists an inactive inventory pool ' \ - 'I have access to as :role' do |role| - @inactive_inventory_pool = \ - FactoryGirl.create(:inventory_pool, is_active: false) - FactoryGirl.create(:access_right, - user: @current_user, - inventory_pool: @inactive_inventory_pool, - role: role.sub(' ', '_')) + 'I have access to as :role' do |role| + @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, is_active: false) + FactoryGirl.create( + :access_right, + user: @current_user, inventory_pool: @inactive_inventory_pool, role: role.sub(' ', '_') + ) end step 'I hover over the current inventory pool in navigation bar' do @@ -35,8 +34,7 @@ module InactiveInventoryPoolSteps end step 'there exists an inactive inventory pool' do - @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, - is_active: false) + @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, is_active: false) end step 'open the edit page for the item' do @@ -44,7 +42,7 @@ module InactiveInventoryPoolSteps end step 'I fill in the name of the inactive inventory pool ' \ - 'for "Responsible department"' do + 'for "Responsible department"' do find('#inventory_pool_id input').set @inactive_inventory_pool.name end @@ -53,12 +51,15 @@ module InactiveInventoryPoolSteps end step 'there is a retired item which is owned by the the current pool ' \ - 'but in responsibility of the inactive inventory pool' do - @item = FactoryGirl.create(:item, - retired: Date.today, - retired_reason: Faker::Lorem.sentence, - inventory_pool: @inactive_inventory_pool, - owner: @current_inventory_pool) + 'but in responsibility of the inactive inventory pool' do + @item = + FactoryGirl.create( + :item, + retired: Date.today, + retired_reason: Faker::Lorem.sentence, + inventory_pool: @inactive_inventory_pool, + owner: @current_inventory_pool + ) end step 'I open the inventory list' do @@ -66,18 +67,16 @@ module InactiveInventoryPoolSteps end step 'I enter the inventory code of the item ' \ - 'in the inventory search field' do + 'in the inventory search field' do find('#list-search').set @item.inventory_code end step 'no item is found' do - within '#inventory' do - expect(page).to have_content _('No entries found') - end + within '#inventory' doexpect(page).to have_content _('No entries found')end end step 'I there is not possibility to choose the inactive inventory pool ' \ - 'from the inventory pools select field' do + 'from the inventory pools select field' do within "select[name='responsible_inventory_pool_id']" do expect(page).not_to have_content @inactive_inventory_pool.name end @@ -88,19 +87,17 @@ module InactiveInventoryPoolSteps end step 'choose the responsible department via field select box' do - type_into_and_select_from_autocomplete( - '#field-input', _('Responsible department') - ) + type_into_and_select_from_autocomplete('#field-input', _('Responsible department')) end step 'I fill in the name of the inactive inventory pool ' \ - 'in the responsible department field' do + 'in the responsible department field' do + end end end end RSpec.configure do |config| - config.include Manage::Spec::InactiveInventoryPoolSteps, - manage_inactive_inventory_pools: true + config.include Manage::Spec::InactiveInventoryPoolSteps, manage_inactive_inventory_pools: true end diff --git a/spec/steps/manage/inventory_steps.rb b/spec/steps/manage/inventory_steps.rb index 5702b1e7a0..75c1fec9b9 100644 --- a/spec/steps/manage/inventory_steps.rb +++ b/spec/steps/manage/inventory_steps.rb @@ -12,11 +12,10 @@ module InventorySteps include ::Spec::PersonasDumpSteps step 'there is an item the current pool is owner of ' \ - 'situated in room :room' do |room| - FactoryGirl.create(:item, - owner: @current_inventory_pool, - room: FactoryGirl.create(:room, - name: room)) + 'situated in room :room' do |room| + FactoryGirl.create( + :item, owner: @current_inventory_pool, room: FactoryGirl.create(:room, name: room) + ) end step 'I open the inventory list page' do @@ -28,7 +27,7 @@ module InventorySteps end step 'I see one model line corresponding to the item ' \ - 'situated in :room' do |room| + 'situated in :room' do |room| items = Item.joins(:room).where(rooms: { name: room }) expect(items.count).to be == 1 item = Item.joins(:room).where(rooms: { name: room }).first @@ -41,20 +40,22 @@ module InventorySteps step 'there are :n items for the model in the current inventory pool' do |n| n.to_i.times do - FactoryGirl.create(:item, - model: @model, - owner: @current_inventory_pool, - inventory_pool: @current_inventory_pool) + FactoryGirl.create( + :item, + model: @model, owner: @current_inventory_pool, inventory_pool: @current_inventory_pool + ) end end step 'there are :n licenses for the software ' \ - 'in the current inventory pool' do |n| + 'in the current inventory pool' do |n| n.to_i.times do - FactoryGirl.create(:license, - model: @software, - owner: @current_inventory_pool, - inventory_pool: @current_inventory_pool) + FactoryGirl.create( + :license, + model: @software, + owner: @current_inventory_pool, + inventory_pool: @current_inventory_pool + ) end end @@ -83,9 +84,9 @@ module InventorySteps end step 'I open the dropdown for the :model_type' do |model_type| - find('#inventory .line.row', - text: instance_variable_get("@#{model_type}").name) - .find("[data-type='inventory-expander']") + find('#inventory .line.row', text: instance_variable_get("@#{model_type}").name).find( + "[data-type='inventory-expander']" + ) .click end @@ -95,26 +96,23 @@ module InventorySteps end step 'the :item_type lines are sorted alphabetically ' \ - 'by their inventory code' do |item_type| - model_type = case item_type - when 'item' - 'model' - when 'license' - 'software' - end - expect( - @lines.map { |l| l.first('.col2of5 .row').text } - ).to eq( - instance_variable_get("@#{model_type}") - .items - .send(item_type.pluralize) - .order(:inventory_code).map(&:inventory_code) + 'by their inventory code' do |item_type| + model_type = + case item_type + when 'item' + 'model' + when 'license' + 'software' + end + expect(@lines.map { |l| l.first('.col2of5 .row').text }).to eq( + instance_variable_get("@#{model_type}").items.send(item_type.pluralize).order( + :inventory_code + ) + .map(&:inventory_code) ) end end end end -RSpec.configure do |config| - config.include Manage::Spec::InventorySteps, manage_inventory: true -end +RSpec.configure { |config| config.include Manage::Spec::InventorySteps, manage_inventory: true } diff --git a/spec/steps/manage/model_crud_steps.rb b/spec/steps/manage/model_crud_steps.rb index a837ad7296..f174ee692b 100644 --- a/spec/steps/manage/model_crud_steps.rb +++ b/spec/steps/manage/model_crud_steps.rb @@ -34,9 +34,7 @@ module ModelCrudSteps end step 'I remove the image' do - within '#images' do - find("[data-type='inline-entry'] [data-remove]").click - end + within '#images' dofind("[data-type='inline-entry'] [data-remove]").clickend end step 'I add another image' do @@ -62,7 +60,4 @@ def add_image(image) end end -RSpec.configure do |config| - config.include Manage::Spec::ModelCrudSteps, - manage_model_crud: true -end +RSpec.configure { |config| config.include Manage::Spec::ModelCrudSteps, manage_model_crud: true } diff --git a/spec/steps/manage/serial_number_validation_steps.rb b/spec/steps/manage/serial_number_validation_steps.rb index 96028f8fd0..610159b819 100644 --- a/spec/steps/manage/serial_number_validation_steps.rb +++ b/spec/steps/manage/serial_number_validation_steps.rb @@ -10,10 +10,12 @@ module SerialNumberValidationSteps include ::Spec::PersonasDumpSteps step 'there is an item with serial number :serial_number' do |serial_number| - FactoryGirl.create(:item, - owner_id: @current_inventory_pool.id, - serial_number: serial_number, - skip_serial_number_validation: true) + FactoryGirl.create( + :item, + owner_id: @current_inventory_pool.id, + serial_number: serial_number, + skip_serial_number_validation: true + ) end step 'I open the page for creating a new item' do @@ -26,10 +28,7 @@ module SerialNumberValidationSteps step 'I select a model' do model = @current_inventory_pool.models.first - type_into_and_select_from_autocomplete( - 'div#model_id input', - model.name - ) + type_into_and_select_from_autocomplete('div#model_id input', model.name) end step 'I enter serial number :serial_number' do |serial_number| @@ -38,9 +37,8 @@ module SerialNumberValidationSteps end step 'I see a confirmation dialog that there already exists same ' \ - 'or similar serial number' do - expect(page.driver.browser.switch_to.alert.text) - .to match /serial number already exists/ + 'or similar serial number' do + expect(page.driver.browser.switch_to.alert.text).to match /serial number already exists/ end step 'I stay on the create item page' do @@ -48,8 +46,7 @@ module SerialNumberValidationSteps end step 'I stay on the edit item page' do - expect(current_path) - .to be == manage_edit_item_path(@current_inventory_pool, @item) + expect(current_path).to be == manage_edit_item_path(@current_inventory_pool, @item) end step 'the loading icon was hidden' do @@ -66,13 +63,11 @@ module SerialNumberValidationSteps step 'I was redirected to the inventory page' do find('#inventory') - expect(current_path) - .to be == manage_inventory_path(@current_inventory_pool) + expect(current_path).to be == manage_inventory_path(@current_inventory_pool) end step 'there is another item in the current inventory pool' do - @item = FactoryGirl.create(:item, - owner_id: @current_inventory_pool.id) + @item = FactoryGirl.create(:item, owner_id: @current_inventory_pool.id) end step 'I open the page for editing an item' do @@ -88,15 +83,13 @@ module SerialNumberValidationSteps end step 'I choose a building' do - type_into_and_select_from_autocomplete \ - 'div#building_id input[name="item[building_id]"]', - Building.general.name + type_into_and_select_from_autocomplete 'div#building_id input[name="item[building_id]"]', + Building.general.name end step 'I choose a room' do - type_into_and_select_from_autocomplete \ - 'div#room_id input[name="item[room_id]"]', - Building.general.rooms.find_by_general(true).name + type_into_and_select_from_autocomplete 'div#room_id input[name="item[room_id]"]', + Building.general.rooms.find_by_general(true).name end step 'I open the inventory helper page' do @@ -111,36 +104,30 @@ module SerialNumberValidationSteps fill_in('item[shelf]', with: (@shelf = Faker::Lorem.word)) end - step 'I apply the values on item with serial number :serial_number' \ - do |serial_number| + step 'I apply the values on item with serial number :serial_number' do |serial_number| @item = Item.find_by_serial_number(serial_number) type_into_and_select_from_autocomplete('#item-input', @item.inventory_code) end step 'I see a warning in regards to existing serial number' do within('#flash .notice') do - page.should \ - have_content _('Same or similar serial number already exists.') + page.should have_content _('Same or similar serial number already exists.') end end step 'the values were successfully applied to the item ' \ - 'with serial number :serial_number' do |serial_number| + 'with serial number :serial_number' do |serial_number| expect(@item.reload.shelf).to be == @shelf end - step 'there is first item with serial number :serial_number' \ - do |serial_number| - @item_1 = FactoryGirl.create(:item, - owner: @current_inventory_pool, - serial_number: serial_number) + step 'there is first item with serial number :serial_number' do |serial_number| + @item_1 = + FactoryGirl.create(:item, owner: @current_inventory_pool, serial_number: serial_number) end - step 'there is second item with serial number :serial_number' \ - do |serial_number| - @item_2 = FactoryGirl.build(:item, - owner: @current_inventory_pool, - serial_number: serial_number) + step 'there is second item with serial number :serial_number' do |serial_number| + @item_2 = + FactoryGirl.build(:item, owner: @current_inventory_pool, serial_number: serial_number) @item_2.skip_serial_number_validation = true @item_2.save! end @@ -158,13 +145,11 @@ module SerialNumberValidationSteps end step 'I add the first item' do - type_into_and_select_from_autocomplete('#search-item', - @item_1.inventory_code) + type_into_and_select_from_autocomplete('#search-item', @item_1.inventory_code) end step 'I add the second item' do - type_into_and_select_from_autocomplete('#search-item', - @item_2.inventory_code) + type_into_and_select_from_autocomplete('#search-item', @item_2.inventory_code) end step 'I choose the general building' do @@ -200,6 +185,5 @@ module SerialNumberValidationSteps end RSpec.configure do |config| - config.include Manage::Spec::SerialNumberValidationSteps, - manage_serial_number_validation: true + config.include Manage::Spec::SerialNumberValidationSteps, manage_serial_number_validation: true end diff --git a/spec/steps/manage/take_back_steps.rb b/spec/steps/manage/take_back_steps.rb index 75f70fbfa0..301cc4ed57 100644 --- a/spec/steps/manage/take_back_steps.rb +++ b/spec/steps/manage/take_back_steps.rb @@ -10,29 +10,32 @@ module TakeBackSteps include ::Spec::PersonasDumpSteps step 'there exists an open contract' do - user = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool) - @contract = FactoryGirl.create(:open_contract, - inventory_pool: @current_inventory_pool, - user: user) + user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) + @contract = + FactoryGirl.create(:open_contract, inventory_pool: @current_inventory_pool, user: user) end step 'the contract has an item line' do - @option_line = \ - FactoryGirl.create(:option_line, - user: @contract.user, - inventory_pool: @contract.inventory_pool, - contract: @contract, - status: :signed) + @option_line = + FactoryGirl.create( + :option_line, + user: @contract.user, + inventory_pool: @contract.inventory_pool, + contract: @contract, + status: :signed + ) end step 'the contract has an option line' do - @item_line = \ - FactoryGirl.create(:item_line, :with_assigned_item, - user: @contract.user, - inventory_pool: @contract.inventory_pool, - contract: @contract, - status: :signed) + @item_line = + FactoryGirl.create( + :item_line, + :with_assigned_item, + user: @contract.user, + inventory_pool: @contract.inventory_pool, + contract: @contract, + status: :signed + ) end step 'I open the take back page for the user of this contract' do @@ -49,9 +52,7 @@ module TakeBackSteps end step 'within modal dialog I click on :label' do |label| - within '.modal' do - click_on _(label) - end + within '.modal' doclick_on _(label)end end step 'I see :text' do |text| @@ -63,9 +64,7 @@ module TakeBackSteps end step 'all the reservations of the contract are :state' do |state| - @contract.reload.reservations.each do |r| - expect(r.status).to be == state.to_sym - end + @contract.reload.reservations.each { |r| expect(r.status).to be == state.to_sym } end step 'I hover over the purpose icon of the item line' do @@ -76,16 +75,11 @@ module TakeBackSteps find(".line[data-id='#{@option_line.id}'] .fa-comment").hover end - step 'I see the contract\'s purpose in the shown tooltip' do - within '.tooltipster-base' do - expect(current_scope).to have_content @contract.purpose - end + step "I see the contract's purpose in the shown tooltip" do + within '.tooltipster-base' doexpect(current_scope).to have_content @contract.purposeend end end end end -RSpec.configure do |config| - config.include Manage::Spec::TakeBackSteps, - manage_take_back: true -end +RSpec.configure { |config| config.include Manage::Spec::TakeBackSteps, manage_take_back: true } diff --git a/spec/steps/manage/visits_verification_filter_steps.rb b/spec/steps/manage/visits_verification_filter_steps.rb index c81a86f3b5..da6026ca59 100644 --- a/spec/steps/manage/visits_verification_filter_steps.rb +++ b/spec/steps/manage/visits_verification_filter_steps.rb @@ -14,8 +14,7 @@ module VisitsVerificationFilterSteps end step 'there is a lending manager in this inventory pool' do - @lending_manager = FactoryGirl.create(:lending_manager, - inventory_pool: @inventory_pool) + @lending_manager = FactoryGirl.create(:lending_manager, inventory_pool: @inventory_pool) end step 'I am logged in as the lending manager' do @@ -26,8 +25,7 @@ module VisitsVerificationFilterSteps end step 'there is an entitlement group with required verification' do - @entitlement_group = \ - FactoryGirl.create(:group, is_verification_required: true) + @entitlement_group = FactoryGirl.create(:group, is_verification_required: true) @inventory_pool.entitlement_groups << @entitlement_group end @@ -36,8 +34,7 @@ module VisitsVerificationFilterSteps end step 'there is a hand over :n without required verification' do |n| - user = FactoryGirl.create(:customer, - inventory_pool: @inventory_pool) + user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) date = Date.today + n.to_i.day FactoryGirl.create( @@ -52,18 +49,12 @@ module VisitsVerificationFilterSteps instance_variable_set( "@hand_over_#{n}", - Visit.find_by( - user: user, - inventory_pool: @inventory_pool, - type: 'hand_over', - date: date - ) + Visit.find_by(user: user, inventory_pool: @inventory_pool, type: 'hand_over', date: date) ) end step 'there is a hand over :n with user to verify' do |n| - user = FactoryGirl.create(:customer, - inventory_pool: @inventory_pool) + user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) @entitlement_group.users << user date = Date.today + n.to_i.day @@ -79,24 +70,16 @@ module VisitsVerificationFilterSteps instance_variable_set( "@hand_over_#{n}", - Visit.find_by( - user: user, - inventory_pool: @inventory_pool, - type: 'hand_over', - date: date - ) + Visit.find_by(user: user, inventory_pool: @inventory_pool, type: 'hand_over', date: date) ) end step 'there is a hand over :n with user and model to verify' do |n| - user = FactoryGirl.create(:customer, - inventory_pool: @inventory_pool) + user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) model = FactoryGirl.create(:model_with_items) @entitlement_group.users << user - @entitlement_group.entitlements << \ - FactoryGirl.create(:entitlement, - model: model, - quantity: 1) + @entitlement_group.entitlements << + FactoryGirl.create(:entitlement, model: model, quantity: 1) date = Date.today + n.to_i.day FactoryGirl.create( @@ -111,27 +94,19 @@ module VisitsVerificationFilterSteps instance_variable_set( "@hand_over_#{n}", - Visit.find_by( - user: user, - inventory_pool: @inventory_pool, - type: 'hand_over', - date: date - ) + Visit.find_by(user: user, inventory_pool: @inventory_pool, type: 'hand_over', date: date) ) end step 'there is a take back :n without required verification' do |n| - user = FactoryGirl.create(:customer, - inventory_pool: @inventory_pool) + user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) date = Date.today + n.to_i.day model = FactoryGirl.create(:model_with_items) ApplicationRecord.transaction do - contract = FactoryGirl.build(:contract, - user: user, - state: :open, - inventory_pool: @inventory_pool) - contract.reservations << \ + contract = + FactoryGirl.build(:contract, user: user, state: :open, inventory_pool: @inventory_pool) + contract.reservations << FactoryGirl.build( :reservation, inventory_pool: @inventory_pool, @@ -148,28 +123,20 @@ module VisitsVerificationFilterSteps instance_variable_set( "@take_back_#{n}", - Visit.find_by( - user: user, - inventory_pool: @inventory_pool, - type: 'take_back', - date: date - ) + Visit.find_by(user: user, inventory_pool: @inventory_pool, type: 'take_back', date: date) ) end step 'there is a take back :n with user to verify' do |n| - user = FactoryGirl.create(:customer, - inventory_pool: @inventory_pool) + user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) model = FactoryGirl.create(:model_with_items) @entitlement_group.users << user date = Date.today + n.to_i.day ApplicationRecord.transaction do - contract = FactoryGirl.build(:contract, - user: user, - state: :open, - inventory_pool: @inventory_pool) - contract.reservations << \ + contract = + FactoryGirl.build(:contract, user: user, state: :open, inventory_pool: @inventory_pool) + contract.reservations << FactoryGirl.build( :reservation, inventory_pool: @inventory_pool, @@ -186,32 +153,22 @@ module VisitsVerificationFilterSteps instance_variable_set( "@take_back_#{n}", - Visit.find_by( - user: user, - inventory_pool: @inventory_pool, - type: 'take_back', - date: date - ) + Visit.find_by(user: user, inventory_pool: @inventory_pool, type: 'take_back', date: date) ) end step 'there is a take back :n with user and model to verify' do |n| - user = FactoryGirl.create(:customer, - inventory_pool: @inventory_pool) + user = FactoryGirl.create(:customer, inventory_pool: @inventory_pool) model = FactoryGirl.create(:model_with_items) @entitlement_group.users << user - @entitlement_group.entitlements << \ - FactoryGirl.create(:entitlement, - model: model, - quantity: 1) + @entitlement_group.entitlements << + FactoryGirl.create(:entitlement, model: model, quantity: 1) date = Date.today + n.to_i.day ApplicationRecord.transaction do - contract = FactoryGirl.build(:contract, - user: user, - state: :open, - inventory_pool: @inventory_pool) - contract.reservations << \ + contract = + FactoryGirl.build(:contract, user: user, state: :open, inventory_pool: @inventory_pool) + contract.reservations << FactoryGirl.build( :reservation, inventory_pool: @inventory_pool, @@ -228,12 +185,7 @@ module VisitsVerificationFilterSteps instance_variable_set( "@take_back_#{n}", - Visit.find_by( - user: user, - inventory_pool: @inventory_pool, - type: 'take_back', - date: date - ) + Visit.find_by(user: user, inventory_pool: @inventory_pool, type: 'take_back', date: date) ) end @@ -242,22 +194,16 @@ module VisitsVerificationFilterSteps end step 'I click on hand over tab' do - within '#list-tabs' do - find('a', text: _('Hand Over')).click - end + within '#list-tabs' dofind('a', text: _('Hand Over')).clickend end step 'I click on take back tab' do - within '#list-tabs' do - find('a', text: _('Take Back')).click - end + within '#list-tabs' dofind('a', text: _('Take Back')).clickend end step 'I see :n visits' do |n| within '#visits' do - unless n.to_i.zero? - find('[data-id]', match: :first) - end + find('[data-id]', match: :first) unless n.to_i.zero? expect(all('[data-id]').count).to be == n.to_i end end @@ -285,5 +231,5 @@ module VisitsVerificationFilterSteps RSpec.configure do |config| config.include Manage::Spec::VisitsVerificationFilterSteps, - manage_visits_verification_filter: true + manage_visits_verification_filter: true end diff --git a/spec/steps/shared/common_steps.rb b/spec/steps/shared/common_steps.rb index 8519d0b701..730460f726 100644 --- a/spec/steps/shared/common_steps.rb +++ b/spec/steps/shared/common_steps.rb @@ -9,15 +9,15 @@ module CommonSteps def wait_until(wait_time = 60, &block) begin Timeout.timeout(wait_time) do - until value = block.call - sleep(1) - end + sleep(1) until value = block.call value end - rescue Timeout::Error + # rubocop:disable Style/RaiseArgs - fail Timeout::Error.new(block.source) + # rubocop:enable Style/RaiseArgs + rescue Timeout::Error + fail Timeout::Error.new(block.source) end end @@ -43,9 +43,7 @@ def type_into_and_select_from_autocomplete(selector, value) step 'I close the flash message if visible' do flash = first('#flash') - if flash - flash.find('.fa-times-circle').click - end + flash.find('.fa-times-circle').click if flash end step 'I release the focus from this field' do @@ -79,7 +77,7 @@ def type_into_and_select_from_autocomplete(selector, value) def rescue_displaced_flash begin yield - rescue + rescue StandardError find('#flash .fa-times-circle').click retry end @@ -88,10 +86,12 @@ def rescue_displaced_flash def rescue_with_pry begin yield - rescue + # rubocop:disable Lint/Debugger - binding.pry + # rubocop:enable Lint/Debugger + rescue StandardError + binding.pry end end end diff --git a/spec/steps/shared/factory_steps.rb b/spec/steps/shared/factory_steps.rb index 3ce68c774e..3262992f60 100644 --- a/spec/steps/shared/factory_steps.rb +++ b/spec/steps/shared/factory_steps.rb @@ -5,26 +5,23 @@ module FactorySteps end step 'there exists an active inventory pool' do - @active_inventory_pool = FactoryGirl.create(:inventory_pool, - is_active: true) + @active_inventory_pool = FactoryGirl.create(:inventory_pool, is_active: true) end step 'there exists an inactive inventory pool' do - @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, - is_active: false) + @inactive_inventory_pool = FactoryGirl.create(:inventory_pool, is_active: false) end step 'there is a customer for the current pool' do - @user = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool) + @user = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) end step 'there is a customer delegation for the current pool' do - delegator = FactoryGirl.create(:customer, - inventory_pool: @current_inventory_pool) - @delegation = FactoryGirl.create(:customer, - delegator_user_id: delegator.id, - inventory_pool: @current_inventory_pool) + delegator = FactoryGirl.create(:customer, inventory_pool: @current_inventory_pool) + @delegation = + FactoryGirl.create( + :customer, delegator_user_id: delegator.id, inventory_pool: @current_inventory_pool + ) end step 'there exists a software' do @@ -37,9 +34,7 @@ module FactorySteps step 'there exists a model with items' do @model = FactoryGirl.create(:model) - 3.times do - FactoryGirl.create(:item, model: @model) - end + 3.times { FactoryGirl.create(:item, model: @model) } end step 'there exists a category' do diff --git a/spec/steps/shared/login_steps.rb b/spec/steps/shared/login_steps.rb index 583057dad7..a21f93bd8c 100644 --- a/spec/steps/shared/login_steps.rb +++ b/spec/steps/shared/login_steps.rb @@ -9,8 +9,7 @@ module LoginSteps end step 'I log out' do - sign_out_button = first(".topbar form[action='/sign-out'] button", - visible: :all) + sign_out_button = first(".topbar form[action='/sign-out'] button", visible: :all) if sign_out_button sign_out_button.click else @@ -18,13 +17,11 @@ module LoginSteps end end - [:customer, :group_manager, :lending_manager, :inventory_manager] - .each do |role| + [:customer, :group_manager, :lending_manager, :inventory_manager].each do |role| step "I am logged in as #{role.to_s.sub('_', ' ')}" do ip = FactoryGirl.create(:inventory_pool) role == :customer ? @inventory_pool = ip : @current_inventory_pool = ip - @current_user = @customer = \ - FactoryGirl.create(role, inventory_pool: ip) + @current_user = @customer = FactoryGirl.create(role, inventory_pool: ip) step 'I log out' set_locale login_as_current_user @@ -54,10 +51,7 @@ module LoginSteps if role == 'admin' user.update_attributes! is_admin: true else - FactoryGirl.create( - :access_right, - user: user, inventory_pool: ip, role: role - ) + FactoryGirl.create(:access_right, user: user, inventory_pool: ip, role: role) end end end @@ -69,11 +63,12 @@ def set_current_inventory_pool end def set_locale - I18n.locale = if @current_user.language - @current_user.language.locale_name.to_sym - else - Language.default_language - end + I18n.locale = + if @current_user.language + @current_user.language.locale_name.to_sym + else + Language.default_language + end end def login_as_current_user diff --git a/spec/steps/shared/personas_dump_steps.rb b/spec/steps/shared/personas_dump_steps.rb index be107ff26f..62f0f4b973 100644 --- a/spec/steps/shared/personas_dump_steps.rb +++ b/spec/steps/shared/personas_dump_steps.rb @@ -3,8 +3,6 @@ module Spec module PersonasDumpSteps - step 'personas dump is loaded' do - ::Dataset.restore_dump - end + step 'personas dump is loaded' do::Dataset.restore_dumpend end end diff --git a/spec/turnip_helper.rb b/spec/turnip_helper.rb index 6a3071ef63..d5821e5ca9 100644 --- a/spec/turnip_helper.rb +++ b/spec/turnip_helper.rb @@ -13,9 +13,7 @@ class Object end [:firefox].each do |browser| - Capybara.register_driver browser do |app| - Capybara::Selenium::Driver.new app, browser: browser - end + Capybara.register_driver browser { |app| Capybara::Selenium::Driver.new app, browser: browser } end Capybara.configure do |config| @@ -24,24 +22,19 @@ class Object end RSpec.configure do |config| - config.raise_error_for_unimplemented_steps = true config.include Rails.application.routes.url_helpers config.before(type: :feature) do - PgTasks.truncate_tables() + PgTasks.truncate_tables FactoryGirl.create(:setting) unless Setting.first Capybara.current_driver = :firefox page.driver.browser.manage.window.maximize end config.after(type: :feature) do |example| - if ENV['CIDER_CI_TRIAL_ID'].present? - unless example.exception.nil? - take_screenshot - end - end + take_screenshot unless example.exception.nil? if ENV['CIDER_CI_TRIAL_ID'].present? page.driver.quit # OPTIMIZE force close browser popups Capybara.current_driver = Capybara.default_driver # PgTasks.truncate_tables() @@ -50,16 +43,23 @@ class Object def take_screenshot(screenshot_dir = nil, name = nil) screenshot_dir ||= Rails.root.join('tmp', 'capybara') name ||= "screenshot_#{Time.zone.now.iso8601.gsub(/:/, '-')}.png" - Dir.mkdir screenshot_dir rescue nil + + begin + Dir.mkdir screenshot_dir + rescue StandardError + nil + end path = screenshot_dir.join(name) case Capybara.current_driver when :firefox - page.driver.browser.save_screenshot(path) rescue nil + begin + page.driver.browser.save_screenshot(path) + rescue StandardError + nil + end else - Rails - .logger - .warn "Taking screenshots is not implemented for \ - #{Capybara.current_driver}." + Rails.logger.warn "Taking screenshots is not implemented for undefined #{Capybara + .current_driver}." end end end