Class: Admin::RestaurantTagsController
- Inherits:
-
BaseController
- Object
- ActionController::Base
- ApplicationController
- BaseController
- Admin::RestaurantTagsController
- Defined in:
- app/controllers/admin/restaurant_tags_controller.rb
Constant Summary collapse
- CATEGORY_MAP =
{ 'Bts' => 'BtsRoute', 'Mrt' => 'MrtRoute', 'Hashtag' => 'Hashtags', 'Facilities' => 'Facility', 'Shopping Mall' => 'ShoppingMall', 'Popular Zone' => 'PopularZone', 'Dining Style' => 'DiningStyle', 'Award Badge' => 'AwardBadge', 'Award Type' => 'AwardType', }.freeze
Constants inherited from BaseController
BaseController::INTERNAL_SERVER_ERROR_MESSAGE
Instance Method Summary collapse
- #ai_help_all_tags ⇒ Object
- #ai_help_tag ⇒ Object
- #ai_help_tag_status ⇒ Object
- #bulk_ai_translate ⇒ Object
- #bulk_translate_status ⇒ Object
- #check_existing_tag(params, tag_id) ⇒ Object
- #coordinates ⇒ Object
- #count_tags ⇒ Object
- #create ⇒ Object
- #destroy ⇒ Object
- #edit ⇒ Object
- #index ⇒ Object
- #tag_restaurant_location ⇒ Object
- #total_tagged_restaurants ⇒ Object
- #update ⇒ Object
- #update_restaurant_rank ⇒ Object
- #update_restaurant_tag ⇒ Object
- #update_synonyms ⇒ Object
Methods inherited from BaseController
#destroy_session, #identity_cache_memoization, #sign_in_page, #user_developer_session
Methods included from LogrageCustomLogger
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
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 Method Details
#ai_help_all_tags ⇒ Object
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 313 def tag_ids = params[:tags] return render json: { success: false, message: 'No tags provided' }, status: :not_found if tag_ids.blank? if tag_ids.present? begin RestaurantTags::AiHelpTitleAllTagWorker.perform_async(tag_ids) render json: { success: true, message: 'AI help generation started' } rescue StandardError => e render json: { success: false, message: "Failed to enqueue AI help: #{e.}" }, status: :internal_server_error end else render json: { success: true, message: 'All tags title is present' } end rescue StandardError => e render json: { success: false, message: e. }, status: :unprocessable_entity end |
#ai_help_tag ⇒ Object
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 332 def ai_help_tag restaurant_tag = RestaurantTag.find(params[:tag]) if restaurant_tag.title_en.blank? render json: { success: false, message: 'Restaurant tag title (English) is missing' }, status: :unprocessable_entity return end # Generate unique translation ID for tracking translation_id = SecureRandom.uuid BUSINESS_LOGGER.info( 'AI translation requested for restaurant tag', { restaurant_tag_id: restaurant_tag.id, title_en: restaurant_tag.title_en, requested_by: current_user&.email, translation_id: translation_id, }, ) # Enqueue worker with translation ID RestaurantTags::AiHelpTitleTagWorker.perform_async(restaurant_tag.id, translation_id) render json: { success: true, translation_id: translation_id, message: 'AI translation started for all languages.', } rescue ActiveRecord::RecordNotFound render json: { success: false, message: 'Restaurant tag not found' }, status: :not_found rescue StandardError => e APMErrorHandler.report(e, context: { restaurant_tag_id: params[:tag] }) render json: { success: false, message: "Failed to start translation: #{e.}" }, status: :internal_server_error end |
#ai_help_tag_status ⇒ Object
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 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 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 370 def ai_help_tag_status translation_id = params[:translation_id] if translation_id.blank? render json: { success: false, message: 'Translation ID is required' }, status: :unprocessable_entity return end redis_key = "restaurant_tag_translation:#{translation_id}" result_json = $persistent_redis.with { |redis| redis.get(redis_key) } if result_json.nil? # No status yet - worker hasn't started or translation_id is invalid render json: { success: true, status: 'processing', message: 'Translation is being processed...', } return end result = JSON.parse(result_json) if result['status'] == 'completed' render json: { success: true, status: 'completed', message: 'Translation completed successfully!', data: result['data'], } elsif result['status'] == 'failed' render json: { success: false, status: 'failed', error: result['error'] || 'Translation failed', }, status: :unprocessable_entity elsif result['status'] == 'processing' render json: { success: true, status: 'processing', message: result['message'] || 'Translation is being processed...', } else # Unknown status render json: { success: true, status: 'processing', message: 'Translation is being processed...', } end rescue JSON::ParserError => e APMErrorHandler.report(e, context: { translation_id: translation_id, result_json: result_json }) render json: { success: false, status: 'failed', error: 'Failed to parse translation status', }, status: :internal_server_error rescue StandardError => e APMErrorHandler.report(e, context: { translation_id: translation_id }) render json: { success: false, status: 'failed', error: 'Failed to check translation status', }, status: :internal_server_error end |
#bulk_ai_translate ⇒ Object
481 482 483 484 485 486 487 488 489 490 491 492 493 494 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 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 481 def bulk_ai_translate category = params[:category] target_languages = params[:target_languages] || [] only_blank_fields = params[:only_blank_fields] == true if target_languages.empty? render json: { success: false, message: 'Please select at least one target language' }, status: :unprocessable_entity return end # Find tags by category = if category.blank? || category == 'All' RestaurantTag.all else # Use CATEGORY_MAP to convert display names to database format category_key = CATEGORY_MAP[category] || category RestaurantTag.where('title_en LIKE ?', "#{category_key}:%") end if .count.zero? render json: { success: false, message: 'No tags found for the selected category' }, status: :unprocessable_entity return end tag_ids = .pluck(:id) # Enqueue the job and get the job ID job_id = RestaurantTags::BulkAiTranslateWorker.perform_async( tag_ids, target_languages, only_blank_fields, ) # Store initial job status in Redis redis_key = "bulk_translate_job:#{job_id}" $persistent_redis.with do |redis| redis.setex( redis_key, 3600, # Expire after 1 hour { status: 'queued', progress: 0, total: tag_ids.count, processed: 0, message: 'Job queued and waiting to start...', }.to_json, ) end BUSINESS_LOGGER.info('Bulk AI translate job queued', { job_id: job_id, category: category, tag_count: tag_ids.count, target_languages: target_languages, }) render json: { success: true, job_id: job_id, message: "Translation job started for #{tag_ids.count} tag(s)", } rescue StandardError => e APMErrorHandler.report(e, context: { category: category, target_languages: target_languages }) render json: { success: false, message: e. }, status: :internal_server_error end |
#bulk_translate_status ⇒ Object
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 574 575 576 577 578 579 580 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 548 def bulk_translate_status job_id = params[:job_id] if job_id.blank? render json: { success: false, message: 'Job ID is required' }, status: :unprocessable_entity return end redis_key = "bulk_translate_job:#{job_id}" status_json = $persistent_redis.with { |redis| redis.get(redis_key) } if status_json.nil? render json: { success: false, message: 'Job not found or expired', }, status: :not_found return end status_data = JSON.parse(status_json) render json: { success: true, status: status_data['status'], progress: status_data['progress'], total: status_data['total'], processed: status_data['processed'], message: status_data['message'], } rescue StandardError => e APMErrorHandler.report(e, context: { job_id: job_id }) render json: { success: false, message: e. }, status: :internal_server_error end |
#check_existing_tag(params, tag_id) ⇒ Object
93 94 95 96 97 98 99 100 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 93 def check_existing_tag(params, tag_id) title_th = "#{params[:category]}:#{params[:tag_th]}" title_en = "#{params[:category]}:#{params[:tag_en]}" tag = RestaurantTag.where('title_en = ? OR title_th = ?', title_en.to_s, title_th.to_s) tag = tag.where.not(id: tag_id) if tag_id.present? tag.first end |
#coordinates ⇒ Object
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 292 def coordinates restaurant_tag_id = params.require(:restaurant_tag_id).to_i restaurant_tag = RestaurantTag.find(restaurant_tag_id) lat = params[:lat] lng = params[:lng] coordinate_data = { lat: lat, lng: lng, } restaurant_tag.update!(coordinate_data) render json: { success: true, message: 'Coordinates updated successfully' } rescue ActiveRecord::RecordNotFound render json: { success: false, message: 'Restaurant tag not found' }, status: :not_found rescue ActiveRecord::RecordInvalid => e render json: { success: false, message: e. }, status: :unprocessable_entity end |
#count_tags ⇒ Object
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 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 436 def category = params[:category] target_languages = params[:target_languages] || [] = if category.present? category_key = CATEGORY_MAP[category] || category RestaurantTag.where('title_en LIKE ?', "#{category_key}:%").where.not(title_en: [nil, '']) else RestaurantTag.where.not(title_en: [nil, '']) end total_count = .count # Count empty fields for selected languages empty_fields_stats = {} = 0 total_empty_fields = 0 if target_languages.any? target_languages.each do |lang| field_name = "title_#{lang}" empty_count = .where(field_name => [nil, '']).count empty_fields_stats[lang] = empty_count total_empty_fields += empty_count end # Count how many tags have at least one empty field in selected languages .find_each do |tag| has_empty = target_languages.any? { |lang| tag.send("title_#{lang}").blank? } += 1 if has_empty end end render json: { success: true, count: total_count, tags_with_empty_fields: , total_empty_fields: total_empty_fields, empty_fields_by_language: empty_fields_stats, } rescue StandardError => e APMErrorHandler.report(e, context: { category: category, target_languages: target_languages }) render json: { success: false, message: e. }, status: :internal_server_error end |
#create ⇒ Object
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 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 59 def create is_existing = check_existing_tag(restaurant_tag_params.except(:city_id, :country_id, :radius_in_km), nil) if is_existing.nil? operation = RestaurantTagCpt::Operations::Create.call(restaurant_tag_params) if operation.success? # Send event create to kafka EventDrivenWorkers::HhSearch::ProducerWorker.perform_async( EventDrivenClient::Constants::RESTAURANT_TAGS_TOPIC, EventDrivenClient::Constants::CREATE_EVENT, operation['model'].id ) render json: operation['model'], serializer: RestaurantTagCpt::Serializers::FakeModel, adapter: :json_api else = if operation['result.contract.default'].errors.present? operation['result.contract.default'].errors..to_sentence elsif operation['model'].errors.present? operation['model'].errors..to_sentence else 'Sorry, something went wrong' end render json: , status: :unprocessable_entity end else render json: 'The tag name with that category already exists', status: :unprocessable_entity end rescue StandardError => e render json: e., status: :unprocessable_entity end |
#destroy ⇒ Object
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 177 def destroy if @restaurant_tag.destroy # Send event delete to kafka EventDrivenWorkers::HhSearch::ProducerWorker.perform_async( EventDrivenClient::Constants::RESTAURANT_TAGS_TOPIC, EventDrivenClient::Constants::DELETE_EVENT, @restaurant_tag.id, ) render json: { success: true } else render json: @restaurant_tag.errors..to_sentence, status: :unprocessable_entity end end |
#edit ⇒ Object
102 103 104 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 102 def edit render layout: nil end |
#index ⇒ Object
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 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 25 def index @categories = @cities = fetch_existing_cities @countries = fetch_existing_countries category_name = params[:category].present? ? params[:category].to_s.capitalize : 'Cuisine' category = category_name.gsub(/\s+/, '').split(/ |_/).map(&:capitalize).join category = CATEGORY_MAP[category] || category respond_to do |format| format.html format.json do = RestaurantTag.where('LOWER(title_en) LIKE LOWER(?)', "#{category}:%") etag = CityHash.hash32([self.class.to_s, .cache_key, category]) return unless stale?(etag: etag, template: false) if params[:serializer] == 'dropdown' categories = .map do |tag| { label: tag.title_format(params.require(:tag_locale)), value: tag.id, } end render json: categories else render json: .includes(:city, :country), each_serializer: ::RestaurantTagCpt::Serializers::FakeModel, adapter: :json_api end end end end |
#tag_restaurant_location ⇒ Object
257 258 259 260 261 262 263 264 265 266 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 257 def tag_restaurant_location tag = RestaurantTag.find(params[:restaurant_tag_id]) if tag.lat.nil? || tag.lng.nil? render json: { success: false, message: 'Tag does not have lat/lng attribute' } else Tagging::RestaurantTagToRestaurantsWorker.perform_async(params[:restaurant_tag_id]) render json: { success: true, message: 'Restaurants are being tagged' } end end |
#total_tagged_restaurants ⇒ Object
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 235 def total_tagged_restaurants restaurant_tag_id = params.require(:restaurant_tag_id).to_i restaurant_tag_restaurants = RestaurantTagsRestaurant.where(restaurant_tag_id: restaurant_tag_id) today = Time.thai_time.to_date total_active = restaurant_tag_restaurants.joins(:restaurant).where(restaurants: { active: true }).where( 'restaurants.expiry_date >= ?', today ).count total_inactive = restaurant_tag_restaurants.joins(:restaurant).where( 'restaurants.active IS FALSE OR restaurants.expiry_date < ?', today ).count render json: { data: { total_active: total_active, total_inactive: total_inactive }, message: 'Success', success: true } rescue ActionController::ParameterMissing => e render json: { data: nil, message: e., success: false } rescue StandardError => e APMErrorHandler.report e render json: { data: nil, message: 'Something went wrong', success: false } end |
#update ⇒ Object
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 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 106 def update is_existing = check_existing_tag(restaurant_tag_params.except(:city_id, :country_id, :radius_in_km), @restaurant_tag.id) if is_existing.nil? operation = RestaurantTagCpt::Operations::Update.call( restaurant_tag_params, id: @restaurant_tag.id, ) if operation.success? # Send event update to kafka EventDrivenWorkers::HhSearch::ProducerWorker.perform_async( EventDrivenClient::Constants::RESTAURANT_TAGS_TOPIC, EventDrivenClient::Constants::UPDATE_EVENT, operation['model'].id ) render json: operation['model'], serializer: RestaurantTagCpt::Serializers::FakeModel, adapter: :json_api else = if operation['result.contract.default'].errors.present? operation['result.contract.default'].errors..to_sentence elsif operation['model'].errors.present? operation['model'].errors..to_sentence else 'Sorry, something went wrong' end render json: , status: :unprocessable_entity end else render json: 'The tag name with that category already exists', status: :unprocessable_entity end rescue StandardError => e render json: e., status: :unprocessable_entity end |
#update_restaurant_rank ⇒ Object
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 268 def update_restaurant_rank @restaurant_tag_id = params[:restaurant_tag_id].to_i @restaurant_tag = RestaurantTag.fetch @restaurant_tag_id if request.put? restaurant_ids = [] new_data = params[:restaurants].map do |arr| restaurant_id = arr[0] position = arr[3] restaurant = Restaurant.find(restaurant_id) restaurant_ids.push(restaurant_id) restaurant.refresh_view_cache_key RestaurantTagsRestaurant.new(restaurant_tag_id: @restaurant_tag.id, restaurant_id: restaurant_id, position: position) end RestaurantTagsRestaurant.import! new_data, on_duplicate_key_update: %i[restaurant_id restaurant_tag_id position], raise_error: true @restaurant_tag.touch end render json: { success: true } end |
#update_restaurant_tag ⇒ Object
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 193 def update_restaurant_tag @restaurant_tag_id = params[:restaurant_tag_id].to_i @restaurant_tag = RestaurantTag.fetch(@restaurant_tag_id) if params.dig(:report, :commit).present? restaurant_ids = begin params[:restaurants][:ids].select(&:present?).compact.map(&:to_i) rescue StandardError [] end if @restaurant_tag.lat.present? && @restaurant_tag.lng.present? # Send event update to kafka old_rtr_ids = @restaurant_tag.restaurants.pluck(:id) new_rtr_ids = restaurant_ids attr_changes = { add: new_rtr_ids - old_rtr_ids, remove: old_rtr_ids - new_rtr_ids, } EventDrivenWorkers::HhSearch::ProducerWorker.perform_async( EventDrivenClient::Constants::RESTAURANTS_TAGS_TOPIC, EventDrivenClient::Constants::UPDATE_EVENT, @restaurant_tag.id, attr_changes ) Tagging::RestaurantTagToRestaurantsWorker.perform_async(@restaurant_tag_id) else tag_restaurants_to_non_coordinates_restaurant_tag(restaurant_ids, @restaurant_tag) end adjust_restaurant_lists(@restaurant_tag, restaurant_ids) if @restaurant_tag..present? render json: { success: true } else @restaurants = if @restaurant_tag.country_id.present? Restaurant.includes(:translations).active.not_expired.where(country_id: @restaurant_tag.country_id) else Restaurant.includes(:translations).active.not_expired end @restaurant_tag_ids = RestaurantTagsRestaurant.where(restaurant_tag: @restaurant_tag).pluck(:restaurant_id) end end |
#update_synonyms ⇒ Object
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
# File 'app/controllers/admin/restaurant_tags_controller.rb', line 145 def update_synonyms synonym = params.require(:synonym) ActiveRecord::Base.transaction do synonyms = synonym.split(',').reject { |item| item == ' ' } synonym_exclude = Synonym.where(restaurant_tag_id: @restaurant_tag.id).where.not(synonym: synonyms) synonym_exclude.destroy_all if synonym_exclude.present? new_data = synonyms.map do |val| Synonym.new(restaurant_tag_id: @restaurant_tag.id, synonym: val) end Synonym.import! new_data, on_duplicate_key_update: %i[restaurant_tag_id synonym], raise_error: true @restaurant_tag.touch # Send event update to kafka EventDrivenWorkers::HhSearch::ProducerWorker.perform_async( EventDrivenClient::Constants::RESTAURANT_TAGS_TOPIC, EventDrivenClient::Constants::UPDATE_EVENT, @restaurant_tag.id ) render json: { data: nil, message: 'Synonym have been updated successfully', success: true }, status: :accepted rescue StandardError => e APMErrorHandler.report(e) render json: { data: nil, message: e., success: false }, status: :unprocessable_entity end rescue ActionController::ParameterMissing => e render json: { data: nil, message: e., success: false } end |