Class: Admin::Packages::BaseController

Inherits:
BaseController show all
Defined in:
app/controllers/admin/packages/base_controller.rb

Overview

typed: ignore

Constant Summary

Constants inherited from BaseController

BaseController::INTERNAL_SERVER_ERROR_MESSAGE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BaseController

#destroy_session, #identity_cache_memoization, #sign_in_page, #user_developer_session

Methods included from LogrageCustomLogger

#append_info_to_payload

Methods included from AdminHelper

#dynamic_pricings_formatter, #link_to_admin_reservations_path_by_id, #link_to_admin_restaurants_path_by_id, #link_to_log, #optional_locales, #optional_locales_with_labels, #staff_signed_in?

Methods included from UpdateLocaleConcern

#setup_locale

Methods inherited from ApplicationController

#after_sign_in_path_for, #after_sign_out_path_for, #default_url_options, #identity_cache_memoization, #render_not_found, #routing_error, search_params_key=

Methods included from ControllerHelpers

#check_boolean_param, #get_banners, #inventory_params, #reservation_params

Instance Attribute Details

#packageObject

Returns the value of attribute package.



4
5
6
# File 'app/controllers/admin/packages/base_controller.rb', line 4

def package
  @package
end

Instance Method Details

#audit_dataObject



148
149
150
151
# File 'app/controllers/admin/packages/base_controller.rb', line 148

def audit_data
  @package = klass.find_by(id: params[package_id_param])
  render 'admin/packages/shared/audit_data'
end

#coverObject



167
168
169
170
# File 'app/controllers/admin/packages/base_controller.rb', line 167

def cover
  @form_url = cover_url(package.id)
  render template: 'admin/packages/cover/index'
end

#cover_url(package_id) ⇒ Object

Raises:

  • (NotImplementedError)


595
596
597
# File 'app/controllers/admin/packages/base_controller.rb', line 595

def cover_url(package_id)
  raise NotImplementedError
end

#createObject



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'app/controllers/admin/packages/base_controller.rb', line 218

def create
  package_params = params.require(:package).permit!.except(:id)

  if (package_params.key?(:pay_now) && package_params[:pay_now].to_s == 'true') &&
      (package_params.key?(:require_cc) && package_params[:require_cc].to_s == 'false')
    # Add the additional data when "pay_now" is true
    package_params[:charge_type] = HhPackage::Package::CHARGE_TYPE_ON_CHARGE
    package_params[:charge_amount_type] = 'relative'
    package_params[:relative_charge_percent] = 100
  end

  package = klass.new(package_params)
  if package.save
    render json: { success: true, data: serialize_package(package) }
  else
    render json: { success: false, message: package.errors.full_messages.to_sentence }
  end
end

#destroyObject



345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'app/controllers/admin/packages/base_controller.rb', line 345

def destroy
  if package.soft_destroy && package.restaurant_packages.each(&:soft_destroy)
    respond_to do |format|
      format.json { render json: { success: true } }
      format.html { redirect_to index_path, notice: 'Success' }
    end
  else
    message = package.errors.full_messages.to_sentence
    respond_to do |format|
      format.json { render json: { success: false, message: message } }
      format.html { redirect_back fallback_location: back_fallback_location, alert: message }
    end
  end
end

#duplicateObject



201
202
203
204
205
206
207
208
# File 'app/controllers/admin/packages/base_controller.rb', line 201

def duplicate
  dup_package_service = DupPackageService.new(package.class, package.id)
  if dup_package_service.execute
    redirect_back fallback_location: back_fallback_location, notice: 'Success'
  else
    redirect_back fallback_location: back_fallback_location, alert: 'Failed duplicate package'
  end
end

#editObject



212
# File 'app/controllers/admin/packages/base_controller.rb', line 212

def edit; end

#edit_package_path(package_id) ⇒ Object

Raises:

  • (NotImplementedError)


599
600
601
# File 'app/controllers/admin/packages/base_controller.rb', line 599

def edit_package_path(package_id)
  raise NotImplementedError
end

#filter_pricing_to_saves(pricings, pricing_model, dynamic_pricing_type) ⇒ Object



619
620
621
622
623
624
625
626
627
# File 'app/controllers/admin/packages/base_controller.rb', line 619

def filter_pricing_to_saves(pricings, pricing_model, dynamic_pricing_type)
  # can not use `.where` because the `package` is not saved yet
  pricings.select do |pricing|
    # find any pricing that is not marked for destruction and has different dynamic_pricing_type
    !pricing.marked_for_destruction? &&
      pricing.dynamic_pricing_type == dynamic_pricing_type &&
      pricing.pricing_model == pricing_model
  end
end

#find_packageObject



378
379
380
381
382
383
384
# File 'app/controllers/admin/packages/base_controller.rb', line 378

def find_package
  # TODO remove kids_prices
  self.package = klass.includes(:pricings, :pricing_groups, :agendas, :menu_sections,
                                :translations, :kids_prices,
                                restaurant_packages: { restaurant: :translations },
                                package_attr: [:payment_types, :custom_labels, :package_special_menus, :translations]).find(params[:id].presence || params.require(package_id_param))
end

#generate_gyg_package(package) ⇒ Object



629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
# File 'app/controllers/admin/packages/base_controller.rb', line 629

def generate_gyg_package(package)
  gyg_packages_attributes = params[:package][:gyg_packages_attributes]
  package_ids = gyg_packages_attributes.map { |p| p['id'] }.compact

  restaurant_packages = package.restaurant_packages.includes(:getyourguide_package).
    where(id: package_ids).index_by(&:id)

  to_delete = []
  to_save = []

  gyg_packages_attributes.each do |gyg_package_params|
    package_id = gyg_package_params[:id]
    restaurant_package = restaurant_packages[package_id.to_i]

    next unless restaurant_package

    if gyg_package_params[:gyg_option_id].blank?
      to_delete.concat([restaurant_package.getyourguide_package&.id])
    else
      gyg_package = restaurant_package.getyourguide_package.presence || restaurant_package.build_getyourguide_package
      gyg_package.assign_attributes(gyg_package_params.slice(:gyg_option_id).permit!)
      gyg_package.restaurant_id = restaurant_package.restaurant_id
      to_save << gyg_package
    end
  end

  GetyourguidePackage.where(id: to_delete.compact).delete_all if to_delete.any?
  GetyourguidePackage.import(
    to_save, on_duplicate_key_update: [:gyg_option_id]
  )
end

#get_vendors_packagesObject



699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'app/controllers/admin/packages/base_controller.rb', line 699

def get_vendors_packages
  package = load_package_with_dianping_packages

  if package&.vendors_dianping_packages&.any?
    vendors_packages = package.vendors_dianping_packages.map do |dp_package|
      {
        is_allow: dp_package.timeslots.any?,
        package_id: dp_package.package_id,
        package_type: dp_package.package_type,
        timeslots: dp_package.timeslots,
      }
    end

    render json: { data: vendors_packages.first }, status: :ok
  else
    render json: { data: {} }, status: :ok
  end
end

#grid_classObject

Raises:

  • (NotImplementedError)


579
580
581
# File 'app/controllers/admin/packages/base_controller.rb', line 579

def grid_class
  raise NotImplementedError
end

#grid_key_paramObject



583
584
585
# File 'app/controllers/admin/packages/base_controller.rb', line 583

def grid_key_param
  grid_class.to_s.underscore.gsub('/', '_').to_sym
end

#indexObject



193
194
195
196
197
198
199
# File 'app/controllers/admin/packages/base_controller.rb', line 193

def index
  @grid = grid_class.new params[grid_key_param] do |scope|
    scope.page(params[:page])
  end
  set_meta_tags title: "#{title_page} Packages Overview"
  nil unless stale_etag?(@grid.assets)
end

#index_pathObject

Examples:

admin_packages_party_packs_path

Raises:

  • (NotImplementedError)


604
605
606
# File 'app/controllers/admin/packages/base_controller.rb', line 604

def index_path
  raise NotImplementedError
end

#klassObject

Raises:

  • (NotImplementedError)


575
576
577
# File 'app/controllers/admin/packages/base_controller.rb', line 575

def klass
  raise NotImplementedError
end

#newObject



210
# File 'app/controllers/admin/packages/base_controller.rb', line 210

def new; end

#package_id_paramObject

Examples:

party_pack_id

Raises:

  • (NotImplementedError)


609
610
611
# File 'app/controllers/admin/packages/base_controller.rb', line 609

def package_id_param
  raise NotImplementedError
end

#payment_typesObject



613
614
615
616
617
# File 'app/controllers/admin/packages/base_controller.rb', line 613

def payment_types
  payment_types = PaymentType.valid_payment_types.
    map { |pt| { id: pt.id, name: pt.humanize_name } }
  render json: { data: payment_types }
end

#permitted_paramsObject

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength



495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'app/controllers/admin/packages/base_controller.rb', line 495

def permitted_params
  # rubocop:enable Metrics/AbcSize
  # rubocop:enable Metrics/MethodLength
  permitted = params.require(:package).permit!.except(:created_at, :updated_at)
  tmp = {}
  %I[name description charge_policy].each do |key|
    MyLocaleManager.available_locales.each do |locale|
      tmp["#{key}_#{locale}"] = permitted["#{key}_#{locale}"]
    end
  end

  permitted.each do |key, _value|
    permitted.delete(key) if (key.match(/^name/) || key.match(/^charge_policy/) || key.match(/^description/)).present?
  end

  tmp.each do |key, value|
    permitted[key] = value if value.present?
  end

  if permitted.key? :agendas_attributes
    permitted[:agendas_attributes].each do |_key, agenda_param|
      agenda_param[:exception_occurrences] = if agenda_param[:exception_occurrences].present?
                                               agenda_param[:exception_occurrences].values
                                             else
                                               []
                                             end
      agenda_param[:single_occurrences] = if agenda_param[:single_occurrences].present?
                                            agenda_param[:single_occurrences].values
                                          else
                                            []
                                          end
    end
  end

  gyg_packages_params = []
  permitted[:restaurant_packages_attributes]&.each do |_key, restaurant_packages|
    gyg_packages_params << {
      id: restaurant_packages[:id],
      gyg_option_id: restaurant_packages[:gyg_option_id],
    }
    restaurant_packages.delete(:selected)
    restaurant_packages.delete(:gyg_option_id)
    restaurant_packages.delete(:_destroy)
  end

  if gyg_packages_params.present?
    params[:package][:gyg_packages_attributes] = gyg_packages_params
  end

  permitted.fetch(:menu_sections_attributes, []).each do |k, menu_section|
    menu_section[:_destroy] = menu_section[:_destroy].to_s == 'true'
    if menu_section[:id].present? && menu_section[:_destroy] &&
        HhPackage::Package::MenuSection.find_by(id: menu_section[:id]).blank?
      permitted[:menu_sections_attributes].delete k
    end

    menu_section.fetch(:menus_attributes, []).each do |_k, menu|
      menu.delete :total_subsection
      menu.delete :image_url
      menu.delete :message # this is an error message to user
    end
  end

  if params.dig(:package, :package_attr_attributes, :charge_policy_link).present?
    params[:package][:package_attr_attributes].delete :charge_policy_link
  end

  if params[:package][:package_attr_attributes].present? && params.dig(:package, :package_attr_attributes,
                                                                       :custom_label_ids).blank?
    params[:package][:package_attr_attributes][:custom_label_ids] = []
  end

  if params.dig(:package, :package_attr_attributes,
                :special_menu).to_s == 'true' && params[:package][:package_attr_attributes][:package_special_menus_attributes].blank?
    params[:package][:package_attr_attributes][:special_menu] = false
  end

  permitted
end

#refreshObject



181
182
183
# File 'app/controllers/admin/packages/base_controller.rb', line 181

def refresh
  send(:"admin_package_#{params[package_type]}_refresh_opening_hours_path")
end

#refresh_opening_hoursObject



185
186
187
188
189
190
191
# File 'app/controllers/admin/packages/base_controller.rb', line 185

def refresh_opening_hours
  package_id = params[package_id_param].to_i
  klass.find(package_id).restaurant_package_ids.each do |id|
    HhPackage::GenerateOpeningHoursWorker.perform_async id
  end
  redirect_to edit_package_path(package_id), notice: 'Success refresh opening hours package'
end

#serialize_package(package) ⇒ Object

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/MethodLength



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'app/controllers/admin/packages/base_controller.rb', line 388

def serialize_package(package)
  # rubocop:enable Metrics/AbcSize
  # rubocop:enable Metrics/MethodLength
  json = package.attributes
  klass.globalize_attribute_names.each do |attr|
    json[attr] = package.send(attr)
  end

  # Include menu_group_id from package_attr
  json['menu_group_id'] = package.menu_group_id

  restaurant_commision = package.try(:restaurants).presence || []
  restaurant_commision = restaurant_commision.select do |r|
    r.commision.to_i.positive?
  end.map { |r| r.commision.to_i }.last.to_i
  json['restaurant_commision'] = restaurant_commision

  # HH Xperience
  if package.respond_to?(:default_start_time) && package.default_start_time.present?
    json['default_start_time'] = package.default_start_time.strftime('%H:%M').strip
  end

  if package.respond_to?(:pricing_groups)
    json['pricing_groups'] = package&.pricing_groups || []
  end

  json['pricings'] = package.pricings
  json['pricing_spending_tiers'] = package.pricing_spending_tiers

  # Sync pricing menu priorities from hh-menu API before returning
  # This ensures priorities are always up-to-date with the external service
  if package.is_a?(HhPackage::Package::Diy)
    PricingMenuPrioritySyncService.new(package).call
    # Reload pricing_menus to get updated priorities with proper ordering
    package.pricing_menus.reload
  end

  json['pricing_menus'] = package.pricing_menus
  json['agendas'] = package.agendas.map do |agenda|
    Admin::Packages::AgendaSerializer.new(agenda).as_json
  end

  json['restaurant_packages'] = package.restaurant_packages.where(deleted_at: nil).map do |restaurant_package|
    restaurant_package.attributes.merge(
      gyg_option_id: restaurant_package&.getyourguide_package&.gyg_option_id,
    )
  end

  json['tnc_image'] = package.tnc_image_url
  json['cover_image'] = package.cover_image_url

  # TODO remove kids_prices
  kids_prices = package.kids_prices.presence || []
  json['kids_prices_attributes'] = kids_prices

  package_benefits = package.package_benefits.presence || []
  json['package_benefits_attributes'] = package_benefits

  package_attr = package.package_attr.presence || package.build_package_attr
  package_attr.accept_voucher = true if package_attr.accept_voucher.nil?
  package_attr_payment_types = {
    payment_type_ids: package_attr.payment_types.pluck(:id),
  }
  package_attr_custom_labels = {
    custom_label_ids: package_attr.custom_labels.pluck(:id),
  }
  package_attr_price = {}
  if package_attr.original_price.present? && package_attr.original_price.positive?
    package_attr_price['original_price'] = if package_attr.original_price.amount.to_d % 1 == 0
                                             package_attr.original_price.amount.to_i
                                           else
                                             package_attr.original_price.amount.to_d
                                           end
  end
  package_attr_special_menu = {
    package_special_menus_attributes: package_attr.package_special_menus,
  }

  json['package_attr_attributes'] = package_attr.attributes.
    merge(package_attr_price).
    merge(package_attr_payment_types).
    merge(package_attr_special_menu).
    merge(package_attr_custom_labels)
  package_attr.class.globalize_attribute_names.each do |attr|
    json['package_attr_attributes'][attr.to_s] = package_attr.send(attr)
  end

  # H@H package
  if package.respond_to?(:menu_sections)
    json['menu_sections_attributes'] = package.menu_sections.order_by_rank.map do |menu_section|
      Admin::Packages::MenuSectionSerializer.new(menu_section).as_json
    end
  end

  json['delivery_fee'] = package.delivery_fee.amount if package.respond_to?(:delivery_fee)

  json['delivery_fee_per_km'] = package.delivery_fee_per_km.amount if package.respond_to?(:delivery_fee_per_km)

  if package.respond_to?(:free_delivery_fee_threshold)
    json['free_delivery_fee_threshold'] = package.free_delivery_fee_threshold.amount
  end

  json
end

#set_vendors_packagesObject



661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
# File 'app/controllers/admin/packages/base_controller.rb', line 661

def set_vendors_packages
  package = load_package_with_restaurant_packages

  if package.restaurant_packages.blank?
    render json: { error: 'No restaurant packages found for the selected package.' }, status: :unprocessable_entity
    return
  end

  if params[:is_allow] == false || params[:timeslots].empty?
    package.vendors_dianping_packages.delete_all
    return render json: { data: {} }, status: :ok
  end

  success = false
  ActiveRecord::Base.transaction do
    package.restaurant_packages.find_each do |restaurant_package|
      dp_package = Vendors::DianpingPackage.find_or_initialize_by(
        package_id: package.id,
        package_type: package.class.name,
        restaurant_package_id: restaurant_package.id,
        restaurant_id: restaurant_package.restaurant_id,
      )

      dp_package.timeslots = params[:timeslots] if params[:timeslots].present?
      dp_package.save! if dp_package.changed?
      success = true
    end
  end

  if success
    render json: { message: 'Packages saved successfully.' }, status: :ok
  else
    render json: { error: 'Transaction failed silently' }, status: :unprocessable_entity
  end
rescue StandardError => e
  render json: { error: "Failed to save packages: #{e.message}" }, status: :unprocessable_entity
end

#showObject



214
215
216
# File 'app/controllers/admin/packages/base_controller.rb', line 214

def show
  render json: serialize_package(package)
end

#synced_datesObject



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'app/controllers/admin/packages/base_controller.rb', line 360

def synced_dates
  package = klass.find(params[package_id_param])
  rp_dates = package.restaurant_packages.pluck(:start_date, :end_date).compact

  if rp_dates.blank?
    render json: { error: 'No restaurant package dates found' }, status: :not_found
    return
  end

  start_date = rp_dates.map(&:first).compact.min
  end_date   = rp_dates.map(&:last).compact.max

  render json: {
    start_date: start_date,
    end_date: end_date,
  }
end

#title_pageObject

Raises:

  • (NotImplementedError)


587
588
589
# File 'app/controllers/admin/packages/base_controller.rb', line 587

def title_page
  raise NotImplementedError
end

#tncObject



153
154
155
156
# File 'app/controllers/admin/packages/base_controller.rb', line 153

def tnc
  @form_url = tnc_url(package.id)
  render template: 'admin/packages/tnc/index'
end

#tnc_url(package_id) ⇒ Object

Raises:

  • (NotImplementedError)


591
592
593
# File 'app/controllers/admin/packages/base_controller.rb', line 591

def tnc_url(package_id)
  raise NotImplementedError
end

#updateObject



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'app/controllers/admin/packages/base_controller.rb', line 237

def update
  # soft destroy restaurant packages
  if params[:package][:restaurant_packages_attributes].present?
    params[:package][:restaurant_packages_attributes].each do |_key, attrs|
      if ActiveModel::Type::Boolean.new.cast(attrs[:_destroy])
        rp = HhPackage::RestaurantPackage.find_by(id: attrs[:id])
        rp&.soft_destroy
      end
    end
    # need to refresh cache
    package.touch
  end

  # Handle pricing menus for DIY packages with menu_v3
  if diy_menu_v3?(package)
    # Check if menu group ID has changed
    new_menu_group_id = extract_menu_group_id(params)
    current_menu_group_id = package.menu_group_id

    # If menu group ID has changed, mark existing pricing menus for deletion
    if menu_group_changed?(package, new_menu_group_id)
      package.pricing_menus.each do |pricing_menu|
        pricing_menu.mark_for_destruction
      end
    end

    # Handle pricing menus duplication prevention
    if pricing_menus_params_present?
      deduplicate_pricing_menus_params!
    end
  end

  # ignore promotion_badge_display params
  permit_params = permitted_params
  permit_params[:package_attr_attributes]&.delete(:promotion_badge_display)
  if permit_params[:fixed_charge_amount_cents].present?
    permit_params[:fixed_charge_amount_cents] =
      permit_params[:fixed_charge_amount_cents].to_d.round
  end

  errors = []
  errors += Array(validate_min_spending(permit_params[:pricings_attributes]))
  errors += Array(validate_spending_tiers(permit_params))
  if errors.present?
    render json: { success: false, message: errors }
    return
  end

  existing_benefit_type = package.benefit_type

  # Remove gyg_packages_attributes from permit_params as it's handled separately
  permit_params = permit_params.except(:gyg_packages_attributes)

  # Remove pricing_menus_attributes with IDs not found for this package
  if permit_params[:pricing_menus_attributes].present?
    valid_ids = package.pricing_menus.pluck(:id).map(&:to_s)
    attrs = permit_params[:pricing_menus_attributes]
    boolean_type = ActiveModel::Type::Boolean.new
    case attrs
    when Hash
      permit_params[:pricing_menus_attributes] = attrs.reject do |_, v|
        reject_pricing_menu_attr?(v, valid_ids, boolean_type)
      end
    when Array
      permit_params[:pricing_menus_attributes] = attrs.reject do |v|
        reject_pricing_menu_attr?(v, valid_ids, boolean_type)
      end
    end
  end

  package.attributes = permit_params

  # Option to pay now
  if package[:pay_now].to_s == 'true' && package[:require_cc].to_s == 'false'
    package[:relative_charge_percent] = 100
    package[:fixed_charge_amount_cents] = nil
    package[:charge_amount_type] = 'relative'
    package[:charge_type] = HhPackage::Package::CHARGE_TYPE_ON_CHARGE
  # Pay on site
  elsif package[:pay_now].to_s == 'false' && package[:require_cc].to_s == 'false'
    package[:relative_charge_percent] = 100
    package[:fixed_charge_amount_cents] = nil
    package[:charge_amount_type] = 'relative'
    package[:charge_type] = nil
  end

  if package[:price_currency].present?
    package_attr = package.package_attr.presence || package.build_package_attr
    package_attr.price_currency = package[:price_currency]
  end

  # the #pricings data are not saved yet, so it doesn't exist in the DB
  # that's why we can't call package#pricings directly
  # package.validate_seats(package.pricings)

  # if package.errors.blank? && package.valid? && package.save && package_attr.save
  if package.valid? && package.save && package_attr.save
    generate_gyg_package(package) if params[:package][:gyg_packages_attributes].present?
    if permit_params[:benefit_type].present? && existing_benefit_type == HhPackage::PackageBenefit::EXTRA_BENEFIT &&
        permit_params[:benefit_type] != HhPackage::PackageBenefit::EXTRA_BENEFIT && (package.package_benefits.count > 0)
      package.package_benefits.delete_all
    end
    render json: { success: true, data: serialize_package(package) }
  else
    render json: { success: false, message: package.errors.full_messages.to_sentence }
  end
end

#upload_coverObject



172
173
174
175
176
177
178
179
# File 'app/controllers/admin/packages/base_controller.rb', line 172

def upload_cover
  file_param = params[:cover]
  if package.update(cover_image: file_param)
    redirect_to edit_package_path(package.id), notice: 'Cover Image file successfully updated'
  else
    redirect_back fallback_location: back_fallback_location, alert: package.errors.full_messages.to_sentence
  end
end

#upload_tncObject



158
159
160
161
162
163
164
165
# File 'app/controllers/admin/packages/base_controller.rb', line 158

def upload_tnc
  file_param = params[:file]
  if package.update(tnc_image: file_param)
    redirect_to edit_package_path(package.id), notice: 'T&c file successfully updated'
  else
    redirect_back fallback_location: back_fallback_location, alert: package.errors.full_messages.to_sentence
  end
end

#validate_pricingObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'app/controllers/admin/packages/base_controller.rb', line 10

def validate_pricing
  package.attributes = permitted_params
  success = false
  message = ''

  pricing_to_saves = filter_pricing_to_saves(package.pricings,
                                             package.dynamic_price_pricing_model,
                                             package.dynamic_price_dynamic_pricing_type)
  if package.dynamic_price_pricing_model == 'per_person' &&
      package.dynamic_price_dynamic_pricing_type == 'normal' &&
      package.respond_to?(:min_seat) &&
      package.respond_to?(:max_seat)
    if pricing_to_saves.blank?
      package.errors.add(:base, 'At least one pricing is required')
    else
      pricing_min_seat = pricing_to_saves.min_by(&:min_seat)&.min_seat
      if pricing_min_seat.to_i < package.min_seat
        package.errors.add(:min_seat,
                           "is invalid, package min seat is #{package.min_seat}, but on pricing level is #{pricing_min_seat}")
      end

      pricing_max_seat = pricing_to_saves.max_by(&:max_seat)&.max_seat
      if pricing_max_seat != HhPackage::Pricing::MAX_SEAT && pricing_max_seat.to_i > package.max_seat
        package.errors.add(:max_seat,
                           "is invalid, package max seat is #{package.max_seat}, but on pricing level is #{pricing_max_seat}")
      end
    end
  end

  # Validate per_person and by_party_size pricing
  if package.dynamic_price_pricing_model.to_sym == :per_person &&
      package.dynamic_price_dynamic_pricing_type.to_sym == :by_party_size

    if pricing_to_saves.blank?
      package.errors.add(:base, 'At least one pricing is required')
    else
      # find overlap min seat
      min_seat_is_overlap = false
      max_seat_is_overlap = false
      pricing_to_saves.each do |pricing|
        current_pricing = pricing
        pricing_to_saves.each do |other_pricing|
          next if current_pricing == other_pricing

          next if current_pricing.max_seat == other_pricing.max_seat &&
            current_pricing.min_seat != other_pricing.min_seat

          current_pricing_seats = (current_pricing.min_seat..current_pricing.max_seat).to_a
          other_pricing_seats = (other_pricing.min_seat..other_pricing.max_seat).to_a

          min_seat_is_overlap = current_pricing_seats.include?(other_pricing.min_seat) ||
            other_pricing_seats.include?(current_pricing.min_seat)
          break if min_seat_is_overlap

          max_seat_is_overlap = current_pricing_seats.include?(other_pricing.max_seat) ||
            other_pricing_seats.include?(current_pricing.max_seat)
          break if max_seat_is_overlap
        end
      end
      if min_seat_is_overlap
        package.errors.add(:base,
                           'One of pricing min seat is duplicate or overlap with other pricing')
      end
      if max_seat_is_overlap
        package.errors.add(:base,
                           'One of pricing max seat is duplicate or overlap with other pricing')
      end

      # find duplicate min and max seat
      seat_ranges = pricing_to_saves.map { |pricing| [pricing.min_seat, pricing.max_seat] }

      duplicate_seats = seat_ranges.tally.select { |_, count| count > 1 }.keys

      if duplicate_seats.present?
        package.errors.add(:base,
                           'One of pricing min and max seat is duplicate or overlap with other pricing')
      end
    end
  end

  # Validate per_person/per_pack and by_day pricing
  if [:per_person, :per_pack].include?(package.dynamic_price_pricing_model.to_sym) &&
      package.dynamic_price_dynamic_pricing_type.to_sym == :by_day
    if pricing_to_saves.blank?
      package.errors.add(:base, 'At least one pricing is required')
    else
      # validate by_day_category == custom_day
      # can not use `.where` because the `package` is not saved yet
      custom_day_pricings = pricing_to_saves.select do |pricing|
        pricing.by_day_category == 'custom_day'
      end

      if custom_day_pricings.present?
        # find any pricings record that has overlap selected days
        selected_days = custom_day_pricings.map(&:selected_days).flatten

        duplicate_days = selected_days.select do |day|
          selected_days.count(day) > 1
        end

        if duplicate_days.present?
          package.errors.add(:base,
                             'One of pricing selected days is duplicate or overlap with other pricing')
        end
      end

      holiday_pricings = pricing_to_saves.select do |pricing|
        pricing.by_day_category == 'holiday'
      end

      if holiday_pricings.present?
        # prevent holiday pricings that have overlap with other pricings based on start date and end date
        holiday_pricings.each do |holiday_pricing|
          holiday_pricings.each do |other_pricing|
            next if holiday_pricing == other_pricing

            if holiday_pricing.start_date <= other_pricing.end_date &&
                holiday_pricing.end_date >= other_pricing.start_date
              package.errors.add(:base, 'One of pricing holiday date is overlap with other pricing')
              break
            end
          end
        end
      end
    end
  end

  if package.errors.blank?
    success = true
  else
    message = package.errors.full_messages.to_sentence
  end
  render json: {
    message: message,
    success: success,
  }
end