Class: Api::V5::PagesController

Inherits:
BaseController
  • Object
show all
Includes:
Concerns::Authorization, Concerns::GetRestaurantList, ImageHelper
Defined in:
app/controllers/api/v5/pages_controller.rb

Constant Summary

Constants inherited from BaseController

BaseController::CACHE_NAMESPACE, BaseController::INTERNAL_SERVER_ERROR_MESSAGE, BaseController::ResponseSchema

Instance Method Summary collapse

Methods included from ImageHelper

#fix_image_url

Methods inherited from BaseController

#identity_cache_memoization

Methods included from LogrageCustomLogger

#append_info_to_payload

Methods included from ResponseCacheConcern

#my_response_cache

Instance Method Details

#app_configObject



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
# File 'app/controllers/api/v5/pages_controller.rb', line 12

def app_config
  cache_key = "#{self.class}:app_config:#{I18n.locale}:#{AdminSetting.maximum(:updated_at).to_i}"
  config = Rails.cache.fetch(cache_key, expires_in: CACHEFLOW.generate_expiry) do
    image_cdn_url = Figaro.env.CDN_URL.presence || Figaro.env.HH_HOST_URL!
    data = {
      enable_gift_card_feature: AdminSetting.enable_gift_card_feature.to_s == 'true',
      we_travel_together_icon_url: AdminSetting.wtt_image_url.to_s.strip,
      show_distance_on_search_page: AdminSetting.show_distance_on_search_page.to_s == 'true',
      culture_locale: MyLocaleManager.to_culture_name,
      available_locales: MyLocaleManager.available_locales,
      cdn_url: image_cdn_url,
      app_title: AdminSetting.with_lang('default_site_title', I18n.locale),
      app_description: AdminSetting.with_lang('default_site_description', I18n.locale),
      total_restaurant: 800,
      total_covers: 2_000_000,
      support_phone: AdminSetting.support_phone.to_s,
      max_image_file_size_in_mb: AdminSetting.max_image_file_size_in_mb.to_i,
      selected_payment_provider: {
        promptpay: Externals::Omise::Source::GB_PRIMEPAY_SOURCE_ID,
        cc: Externals::Omise::Source::GB_PRIMEPAY_SOURCE_ID,
        promptpay_options: {
          th: AdminSetting.selected_promptpay_payment_provider_for_th,
          sg: AdminSetting.selected_promptpay_payment_provider_for_sg,
        },
        cc_options: {
          th: AdminSetting.selected_cc_payment_provider_for_th,
          sg: AdminSetting.selected_cc_payment_provider_for_sg,
        },
        alipay_options: {
          th: AdminSetting.selected_alipay_payment_provider_for_th,
          sg: AdminSetting.selected_alipay_payment_provider_for_sg,
        },
        wechat_pay_options: {
          th: AdminSetting.selected_wechat_pay_payment_provider_for_th,
          sg: AdminSetting.selected_wechat_pay_payment_provider_for_sg,
        },
      },
      restaurant_price_range: {
        min: 100,
        max: 10_000,
        currency: 'THB',
      },
      promptpay_unsupported_banks: AdminSetting.with_lang('prompt_pay_unsupported_banks', I18n.locale).
        to_s.split(',').map(&:strip),
      promptpay_countdown: AdminSetting.prompt_pay_count_down_in_minute.to_i.minutes.to_i,
      term_condition_big_group: AdminSetting.term_condition_link_big_group.to_s,
      gb_primepay_public_key: Figaro.env.GB_PRIMEPAY_PUBLIC_KEY!.to_s,
      cities: City.filtered_cities.map { |c| [{ id: c.id, name: c.name }] }.flatten,
      dynamic_points: {
        review_reservation: ::GiveReservationRewardWorker::REWARD_POINT,
        new_user_voucher_point: AdminSetting.default_first_time_user_voucher_amount.to_i,
        early_bird: {
          max_reviews: AdminSetting.early_bird_max_reviews.to_i,
          point: AdminSetting.early_bird_rewards_amount.to_i,
        },
        referrer_reward_point: ::Reservation::AMOUNT_REFERRER_REWARD_POINT_TH,
        referrer_reward_point_sg: ::Reservation::AMOUNT_REFERRER_REWARD_POINT_SG,
      },
      package_list: HhPackage::PACKAGE_SHORT_LIST_AND_LONG_NAME,
      package_tag_lines: package_tag_lines,
      use_async_booking: AdminSetting.use_async_booking.to_s == 'true',
      wtt_link_url: AdminSetting.wtt_link_url,
      banner_voucher_url: AdminSetting.with_lang('banner_voucher_url', I18n.locale),
      mobile_banner_voucher_url: AdminSetting.with_lang('mobile_banner_voucher_url', I18n.locale),
      web_v2_host: AdminSetting.web_v2_host,
      # limited_seats_showing is used by FE to show only those packages on restaurant page
      # for which available inventory is greater than this value
      limited_seats_showing: AdminSetting.limited_seats_showing.to_s,
      appfirst_banner_for_desktop: AdminSetting.with_lang('appfirst_banner_for_desktop', I18n.locale),
      appfirst_banner_for_mobile: AdminSetting.with_lang('appfirst_banner_for_mobile', I18n.locale),
      max_api_translation_requests_per_month: AdminSetting.max_api_translation_requests_per_month,
      exchange_rate_buffers: AdminSetting::SUPPORTED_CURRENCIES.each_with_object({}) do |currency, hash|
        hash[currency.to_sym] = AdminSetting.public_send("exchange_rate_buffer_#{currency}").to_f
      end,
    }

    pricing_tier = DeliveryPricingTier.default_tier
    data.merge!(pricing_tier.to_admin_setting)

    %I[min_group_booking_party_size delivery_fee_in_baht].each do |attr|
      data[attr] = AdminSetting.send(attr).to_i
    end

    data
  end
  new_chechout_feature = Flipper.enabled?(:enable_use_new_checkout)

  flipper_config = {
    features: {
      first_app_voucher: Flipper.enabled?(:first_app_voucher),
      voucher_in_marketplace: Flipper.enabled?(:voucher_in_marketplace),
      enable_save_cc: Flipper.enabled?(:enable_save_cc),
      enable_save_address: Flipper.enabled?(:enable_save_address),
      enable_mapbox: Flipper.enabled?(:enable_mapbox),
      enable_preselect_menu: Flipper.enabled?(:enable_preselect_menu),
      enable_store_page: Flipper.enabled?(:enable_store_page),
      enable_use_new_checkout: new_chechout_feature,
      enable_use_new_checkout_with_list: {
        isFullyEnabled: new_chechout_feature,
        data: Flipper[:enable_use_new_checkout].gate_values.actors.to_a,
      },
      enable_group_landing_page: Flipper.enabled?(:enable_group_landing_page),
      enable_omise_th_payment_for_sg_cc: Flipper.enabled?(:enable_omise_th_payment_for_sg_cc),
    },
  }

  data = config.merge(flipper_config)
  expires_in DEFAULT_HTTP_PUBLIC_CACHE_EXPIRATION, public: true
  if stale?(etag: CityHash.hash32(data), template: false)
    render json: { success: true, data: data, message: nil }
  end
end

#dining_occasionsObject



217
218
219
220
221
222
223
224
225
226
# File 'app/controllers/api/v5/pages_controller.rb', line 217

def dining_occasions
  data = Dimension.occasion_scope.order('order_number asc')
  cache_key = [data.cache_key, :dining_occasions]
  my_response_cache "#{self.class}:dining_occasions:#{cache_key.join(':')}:#{I18n.locale}", :json, public: true do
    JSON.parse(ActiveModelSerializers::SerializableResource.new(data,
                                                                each_serializer: Api::V5::DiningOccasionSerializer,
                                                                adapter: :json_api).to_json)
  end
  set_status_header(true)
end


228
229
230
231
232
233
234
235
236
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
# File 'app/controllers/api/v5/pages_controller.rb', line 228

def featured_reviews
  page = params.fetch(:page, 1)
  per_page = params.fetch(:per_page, 10)
  review_type = params.require(:review_type)
  cache_key = [Date.today, page, per_page, review_type]

  my_response_cache(cache_key, :json, public: true) do
    case review_type
    when 'blogger'
      reviews = Review.includes(:blogger).where.not(blogger_id: nil).
        page(page).per(per_page).order('created_at DESC')

      options = {
        include: 'restaurant,branch',
        adapter: :json_api,
        each_serializer: Api::V5::BloggerReviewSerializer,
        serialization_context: serialization_context,
      }
      result = render_to_string(json: ActiveModelSerializers::SerializableResource.new(reviews, options).as_json.merge(
        success: true, message: nil,
      ))
      JSON.parse result
    when 'user'
      reviews = Review.includes(:user).joins(reservation: :restaurant).where(reviews: { rating: 5 }).
        where("`reviews`.`review` IS NOT NULL AND
      `reviews`.`review_photos_count` >= 4 AND
      trim(coalesce(`reviews`.`review`, '')) <> ''").
        where(restaurants: { active: true }).
        order("reviews.review_photos_count >= 4 AND reviews.review IS NOT NULL AND reviews.review <> '' DESC,
      reviews.review IS NOT NULL AND reviews.review <> '' DESC,
      reviews.rating DESC,
      reviews.created_at DESC").
        page(page).per(per_page)

      options = {
        include: 'restaurant',
        adapter: :json_api,
        each_serializer: Api::V5::ReviewSerializer,
        serialization_context: serialization_context,
      }
      result = render_to_string(json: ActiveModelSerializers::SerializableResource.new(reviews, options).as_json.merge(
        success: true, message: nil,
      ))
      JSON.parse result
    else
      raise NotImplementedError
    end
  end
end

#package_tag_linesObject

rubocop:disable Metrics/MethodLength



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'app/controllers/api/v5/pages_controller.rb', line 126

def package_tag_lines
  # rubocop:enable Metrics/MethodLength
  tag_line = {
    en: {
      pp: 'Value set for your next celebration!. You can mix and match multiple packs',
      ayce: 'Enjoy unlimited dining at your favorite restaurants',
      bfp: 'Unlimited dining with exclusive perks',
      hs: 'All-Inclusive Affordable Lunch Set at NET Price!',
      sm: 'Exclusive Set Menu',
      hah: 'Exclusive deals available for delivery and self pick-up',
      xp: 'Great deals on dining experiences bundled with your favorite activities!',
    },
    th: {
      ayce: 'อิ่มอร่อยกับร้านโปรดของคุณได้แบบบุฟเฟ่ต์ไม่อั้น',
      pp: 'เมนูคุ้มค่าสำหรับการเลี้ยงฉลองครั้งต่อไป!. สามารถเลือกแพ็กหลายๆแบบได้',
      bfp: 'ทานไม่อั้นพร้อมรับสิทธิพิเศษ',
      hs: 'มื้ออาหารกลางวันแบบครบชุดในราคาสุทธิ!',
      sm: 'Exclusive Set Menu',
      hah: 'ดีลสุดพิเศษสำหรับ เดลิเวอรี่ และ รับเองที่ร้าน',
      xp: 'รวมแพ็กเกจดีลสุดคุ้ม ทั้งอาหาร รวมกิจกรรมสนุกๆ อีกมากมาย',
    },
  }

  language = MyLocaleManager.normalize_locale
  language = :en if language.to_sym != :th
  tag_line[language]
end

#queue_infoObject



278
279
280
281
282
283
# File 'app/controllers/api/v5/pages_controller.rb', line 278

def queue_info
  info = Sidekiq::Queue.all.map do |queue|
    [queue.size, queue.latency]
  end
  render json: { total: info.map { |q| q[0] }.sum, latency: info.map { |q| q[1] }.sum }
end

#suggestObject



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'app/controllers/api/v5/pages_controller.rb', line 154

def suggest
  enable_search_with_menu = AdminSetting.enable_search_with_menu.to_s == 'true'
  if enable_search_with_menu
    graphql_query = build_graphql_query
    graphql_response = get_hh_search_suggest(graphql_query)

    unless graphql_response.dig('data', 'SearchSuggestions', 'success')
      render json: { success: false,
                     message: graphql_response[:message] || 'An error occurred while fetching suggestion data' }
      return
    end

    data_array = graphql_response.dig('data', 'SearchSuggestions', 'data')
    render json: data_array
    return
  else
    render json: {
      data: {
        restaurants: [],
        locations: [],
        cuisines: [],
        mrtroutes: [],
        btsroutes: [],
        hashtags: [],
        diningstyles: [],
        facilities: [],
        shoppingmalls: [],
        popularzones: [],
      },
      success: true,
      message: nil,
    }
  end
  set_status_header(true)
end

#suggest_adsObject



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'app/controllers/api/v5/pages_controller.rb', line 190

def suggest_ads
  cache_key = CityHash.hash32([ads_cache_key])
  my_response_cache "#{self.class}:suggest_ads:#{cache_key}", :json do
    advertisement = Advertisement.search_suggest
    formatted_restaurant = advertisement.map do |ads|
      r = ads.advertisable
      image_path = r.decorate.image_cover_url.presence || ''
      if image_path.present? && !image_path.include?('http')
        image_path = "#{Figaro.env.HH_HOST_URL!}#{image_path}"
      end
      attr = r.slice('id', 'name', 'encrypted_id', 'slug')
      cover_image = image_path
      cuisine = r.primary_tag_by_category(RestaurantTag::CUISINE)&.restaurant_tag&.title_format(for_api: true).presence || ''
      location = r.primary_tag_by_category(RestaurantTag::POPULAR_ZONE)&.restaurant_tag&.title_format(for_api: true).presence || ''
      attr.merge(cover_image: cover_image, location: location, cuisine: cuisine, position: ads.position)
    end
    {
      data: {
        restaurants: formatted_restaurant,
      },
      success: true,
      message: nil,
    }
  end
  set_status_header(true)
end

#wtt_imageObject



285
286
287
288
289
# File 'app/controllers/api/v5/pages_controller.rb', line 285

def wtt_image
  render json: {
    url: AdminSetting.wtt_image_url.strip,
  }
end