Class: User

Inherits:
ApplicationRecord show all
Includes:
CorporateUsers::UserExt, HungryHub::DynamicTime, IdentityCache, TypesOfActor
Defined in:
app/models/user.rb

Constant Summary collapse

PASSWORD_SALT =

DON'T CHANGE THIS KEY

'2alksdj9182398as:asd[]q[we-='
GENDER_MAP =
{ female: 0, male: 1, Mrs: 0, Mr: 1, 'Mrs.': 0, 'Mr.': 1, f: 0, m: 1,
Miss: 0 }.with_indifferent_access
REFERRAL_CODE_PREFIX =

We use this prefix to generate voucher for referral program

'REF-'
MIN_REFERRAL_CODE_LENGTH =
6
DELETED_USER_EMAIL_FLAG =
'archived-user'
DELETED_USER_USERNAME_FLAG =
'(Deleted user)'
PROVIDER_FACEBOOK =

Providers

:facebook
PROVIDER_FIREBASE =
:firebase
PROVIDER_HUNGRYHUB =
:hungryhub

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HungryHub::DynamicTime

#time_zone

Methods included from TypesOfActor

#kinda_like_owner?, #owner?, #restaurant_group?, #staff?, #user?

Methods included from CorporateUsers::UserExt

#corporate_employee?, #fetch_corporate_company

Methods inherited from ApplicationRecord

sync_carrierwave_url

Instance Attribute Details

#multiple_bookingObject

Returns the value of attribute multiple_booking.



25
26
27
# File 'app/models/user.rb', line 25

def multiple_booking
  @multiple_booking
end

#one_bookingObject

used by app/views/admin/reports/_user.html.slim



24
25
26
# File 'app/models/user.rb', line 24

def one_booking
  @one_booking
end

#transaction_unsubscribe_reason_otherObject



460
461
462
# File 'app/models/user.rb', line 460

def transaction_unsubscribe_reason_other
  transaction_unsubscribe_reason
end

Class Method Details

.decode_uri(string) ⇒ Object



401
402
403
404
405
# File 'app/models/user.rb', line 401

def decode_uri(string)
  Base64.urlsafe_decode64 string
rescue ArgumentError
  ''
end

.deletion_reasons(lang) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'app/models/user.rb', line 189

def deletion_reasons(lang)
  reasons = {
    en: [
      'I no longer use Hungry Hub',
      "I couldn't find the deals I like",
      'Deals are too expensive',
      'Difficult to use',
      'I have privacy/security concerns',
    ],
    th: [
      'I no longer use Hungry Hub',
      "I couldn't find the deals I like",
      'Deals are too expensive',
      'Difficult to use',
      'I have privacy/security concerns',
    ],
  }
  reasons[lang]
end

.encode_to_uri(string) ⇒ Object



397
398
399
# File 'app/models/user.rb', line 397

def encode_to_uri(string)
  Base64.urlsafe_encode64 string
end

.find_referrer_based_on_voucher_code(voucher_code) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'app/models/user.rb', line 251

def find_referrer_based_on_voucher_code(voucher_code)
  return nil if voucher_code.blank?

  referrer = match_by_referral_code(voucher_code)
  return referrer if referrer.present?

  # if referrer is not found, we should check if the voucher code is from the referral program
  # example code REF-9RZAWF-LDB
  # we just need to take the middle one
  actual_code = voucher_code.include?('-') ? voucher_code.split('-')[1] : nil
  return match_by_referral_code(actual_code) if actual_code.present?

  nil
end

.generate_short_referral_codeObject



209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'app/models/user.rb', line 209

def generate_short_referral_code
  max_attempts = 1000
  attempts = 0

  loop do
    temp_code = SecureRandom.alphanumeric(MIN_REFERRAL_CODE_LENGTH).upcase
    unless User.exists?(short_my_r_code: temp_code) || Voucher.exists?(voucher_code: temp_code)
      return temp_code
    end

    attempts += 1
    raise 'Max attempts reached for generating unique short referral code' if attempts >= max_attempts
  end
end

.generate_user_reportsObject



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'app/models/user.rb', line 224

def generate_user_reports
  sql = "SELECT MONTH(created_at) AS month, YEAR(created_at) AS year, COUNT(id) AS user_count FROM #{User.table_name} GROUP BY month, year ORDER BY year, month ASC"

  reports = User.find_by_sql(sql)
  reports.each_with_index do |r, index|
    sql = <<~SQL
      SELECT COUNT(*) AS total
      FROM `reservations`
        JOIN `users` ON `reservations`.`user_id` = `users`.`id` AND
        MONTH(`reservations`.`created_at`) = MONTH(`users`.`created_at`) AND
        YEAR(`reservations`.`created_at`) = YEAR(`users`.`created_at`)
      WHERE
        MONTH(`reservations`.`created_at`) = #{r.month}
        AND YEAR(`reservations`.`created_at`) = #{r.year}
        AND `reservations`.`user_id` IS NOT NULL
        AND `reservations`.`active` = 1
        GROUP BY `reservations`.`user_id`
    SQL
    booking = Reservation.find_by_sql(sql).to_a
    one_booking = booking.select { |b| b.total == 1 }.count
    multiple_booking = booking.select { |b| b.total > 1 }.count

    reports[index].one_booking = one_booking
    reports[index].multiple_booking = multiple_booking
  end
end

.is_valid_hash_email?(hash_email, uri_email) ⇒ Boolean

Returns:

  • (Boolean)


407
408
409
410
# File 'app/models/user.rb', line 407

def is_valid_hash_email?(hash_email, uri_email)
  email = decode_uri(uri_email)
  valid_safe_hash?(hash_email, email)
end

.match_by_referral_code(code) ⇒ Object

custom method to find referral code it will try to match with the long and short referral code we add short referral code feature to make it easier for user to share their referral code added at end of May 2024 we don't use `find_by_referral_code` for the method name because it is similar to Rails built-in method `find_by` and it could cause confusion

Parameters:

  • code (String)


183
184
185
186
187
# File 'app/models/user.rb', line 183

def match_by_referral_code(code)
  return nil if code.blank?

  with_referral_code(code).first
end

.to_safe_hash(email) ⇒ Object



378
379
380
381
382
383
384
# File 'app/models/user.rb', line 378

def to_safe_hash(email)
  user = User.find_by email: email
  return false if user.blank?

  hash = BCrypt::Password.create email + User::PASSWORD_SALT, cost: 7
  Base64.urlsafe_encode64 hash
end

.total_at_month_and_year(month, year) ⇒ Object



434
435
436
# File 'app/models/user.rb', line 434

def total_at_month_and_year(month, year)
  where("MONTH(created_at) = #{month} AND YEAR(created_at) = #{year}").count
end

.update_password(data) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'app/models/user.rb', line 412

def update_password(data)
  hash_email = data[:hash_email]
  original_email = data[:original_email]
  password = data[:password]
  password_confirmation = data[:password_confirmation]
  if is_valid_hash_email?(hash_email, original_email)
    user = User.find_by email: decode_uri(original_email)
    user.password = password
    user.password_confirmation = password_confirmation
    return true if user.save

    @update_password_errors = user.errors.full_messages
  end
  false
end

.update_password_errorsObject



428
429
430
431
432
# File 'app/models/user.rb', line 428

def update_password_errors
  return @update_password_errors if @update_password_errors.present?

  []
end

.valid_safe_hash?(hash_email, original_email) ⇒ Boolean

Returns:

  • (Boolean)


386
387
388
389
390
391
392
393
394
395
# File 'app/models/user.rb', line 386

def valid_safe_hash?(hash_email, original_email)
  hash_email = Base64.urlsafe_decode64 hash_email

  email = BCrypt::Password.new hash_email
  email == original_email + User::PASSWORD_SALT
rescue ArgumentError # for base64 decode
  false
rescue BCrypt::Errors::InvalidHash
  false
end

Instance Method Details

#active_reservations_countObject



316
317
318
319
320
321
# File 'app/models/user.rb', line 316

def active_reservations_count
  Rails.cache.fetch("User:#{id}:active_reservations_count:#{reservations.latest_timestamp_cache_key}",
                    expires_in: CACHEFLOW.generate_expiry) do
    reservations.reached_goal_scope.count
  end
end

#ageObject



267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'app/models/user.rb', line 267

def age
  Rails.cache.fetch("User:#{id}:age:#{birthday}", expires_in: CACHEFLOW.generate_expiry) do
    birthday = self.birthday if birthday.nil?
    if birthday.blank? || birthday.nil?
      0
    else
      now = Date.current_date

      birthday -= 543.years if birthday.year > 2500
      now.year - birthday.year - (now.month > birthday.month || (now.month == birthday.month && now.day >= birthday.day) ? 0 : 1)
    end
  end
end

#all_reservations_countObject



309
310
311
312
313
314
# File 'app/models/user.rb', line 309

def all_reservations_count
  Rails.cache.fetch("User:#{id}:all_reservations_count:#{reservations.latest_timestamp_cache_key}",
                    expires_in: CACHEFLOW.generate_expiry) do
    reservations.exclude_modified_scope.count
  end
end

#cancel_reservations_countObject



330
331
332
333
334
335
# File 'app/models/user.rb', line 330

def cancel_reservations_count
  Rails.cache.fetch("User:#{id}:cancel_reservations_count:#{reservations.latest_timestamp_cache_key}",
                    expires_in: CACHEFLOW.generate_expiry) do
    reservations.cancel_scope.count
  end
end

#company_logo_urlObject



475
476
477
# File 'app/models/user.rb', line 475

def company_logo_url
  corporate_company&.logo_url&.presence || ''
end

#favoritesObject



369
370
371
# File 'app/models/user.rb', line 369

def favorites
  favs.distinct
end

#fb_uid=(id) ⇒ Object



451
452
453
454
# File 'app/models/user.rb', line 451

def fb_uid=(id)
  self['fb_uid'] = id
  self.uid = id
end

#fetch_omise_customer_id(country_code) ⇒ Object



479
480
481
482
483
484
485
486
487
488
# File 'app/models/user.rb', line 479

def fetch_omise_customer_id(country_code)
  case country_code
  when ApiV5::Constants::COUNTRY_CODE_SG
    omise_customer_id_sg
  when ApiV5::Constants::COUNTRY_CODE_MY
    omise_customer_id_my
  else
    omise_customer_id
  end
end

#formatted_booking_summary(restaurant_id = nil) ⇒ Object



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'app/models/user.rb', line 512

def formatted_booking_summary(restaurant_id = nil)
  @user_booking_summaries = booking_summaries
  {
    restaurant_booking: {
      booking: @user_booking_summaries.select { |bs| bs.restaurant_id == restaurant_id }.first&.booking_count || 0,
      cancel: @user_booking_summaries.select { |bs| bs.restaurant_id == restaurant_id }.first&.cancel_count || 0,
      no_show: @user_booking_summaries.select { |bs| bs.restaurant_id == restaurant_id }.first&.no_show_count || 0,
    },
    all_restaurant_booking: {
      booking: @user_booking_summaries.select { |bs| bs.restaurant_id.nil? }.first&.booking_count || 0,
      cancel: @user_booking_summaries.select { |bs| bs.restaurant_id.nil? }.first&.cancel_count || 0,
      no_show: @user_booking_summaries.select { |bs| bs.restaurant_id.nil? }.first&.no_show_count || 0,
    },
  }
end

#genderObject



439
440
441
442
443
444
# File 'app/models/user.rb', line 439

def gender
  g = read_attribute(:gender)
  return GENDER_MAP.key(g) unless g.nil?

  nil
end

#gender=(g) ⇒ Object



446
447
448
449
# File 'app/models/user.rb', line 446

def gender=(g)
  write_attribute(:gender, GENDER_MAP[g]) unless g.nil?
  nil
end

#get_credits(country_id = nil) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'app/models/user.rb', line 281

def get_credits(country_id = nil)
  Rails.cache.fetch("User:#{id}:get_credits:#{rewards.latest_timestamp_cache_key}:#{country_id}",
                    expires_in: CACHEFLOW.generate_expiry) do
    reward = nil

    begin
      reward = Reward.count_credits(id, country_id)

      if readonly?
        User.find(id).update(reward_points: reward)
      else
        update(reward_points: reward)
      end
    rescue ActiveModel::RangeError => e
      APMErrorHandler.report("#{self.class} #{e.message}", user_id: id)
    end

    reward
  end
end

#get_credits_by_countryObject



302
303
304
305
306
307
# File 'app/models/user.rb', line 302

def get_credits_by_country
  Rails.cache.fetch("User:#{id}:get_credits_by_country:#{rewards.latest_timestamp_cache_key}",
                    expires_in: CACHEFLOW.generate_expiry) do
    Reward.user_points_by_country(id)
  end
end

#languageObject



344
345
346
# File 'app/models/user.rb', line 344

def language
  self[:language] || MyLanguageManager::DEFAULT_LANGUAGE
end

#language=(lang) ⇒ Object



348
349
350
# File 'app/models/user.rb', line 348

def language=(lang)
  self[:language] = MyLanguageManager.recognize(lang)
end

#malaysia_phone_number?Boolean

Checks if the user's phone number is a valid Malaysian phone number.

This method parses the user's full phone number (including country code) and verifies if it is valid and specifically valid for Malaysia.

Examples:

user = User.find(1)
user.phone_v2_full = '60123456789'
user.malaysia_phone_number? #=> true or false

Returns:

  • (Boolean)

    true if the phone number is valid and belongs to Malaysia, false otherwise. Returns false if the phone number is blank or invalid. If a parsing error occurs, the error is reported to APM and false is returned.



587
588
589
590
591
592
593
594
595
# File 'app/models/user.rb', line 587

def malaysia_phone_number?
  return false if phone_v2_full.blank?

  parsed_phone = Phonelib.parse(phone_v2_full)
  parsed_phone.valid? && parsed_phone.valid_for_country?(Country.find_malaysia.alpha2)
rescue Phonelib::Error => e
  APMErrorHandler.report("#{self.class} #{e.message}", user_id: id)
  false
end

#nameObject



352
353
354
# File 'app/models/user.rb', line 352

def name
  username
end

#name=(name) ⇒ Object



356
357
358
# File 'app/models/user.rb', line 356

def name=(name)
  self[:username] = name
end

#no_show_reservations_countObject



323
324
325
326
327
328
# File 'app/models/user.rb', line 323

def no_show_reservations_count
  Rails.cache.fetch("User:#{id}:no_show_reservations_count:#{reservations.latest_timestamp_cache_key}",
                    expires_in: CACHEFLOW.generate_expiry) do
    reservations.no_show_scope.count
  end
end

#phone_v2_fullObject



464
465
466
467
468
469
470
471
472
473
# File 'app/models/user.rb', line 464

def phone_v2_full
  if phone_v2.present?
    return "#{calling_code}#{phone_v2}" if calling_code.present?

    return "66#{phone_v2}"
  end
  return phone if phone.present?

  nil
end

#referrals_countObject



337
338
339
340
341
342
# File 'app/models/user.rb', line 337

def referrals_count
  Rails.cache.fetch("User:#{id}:all_reservations_count:#{referrals.latest_timestamp_cache_key}",
                    expires_in: CACHEFLOW.generate_expiry) do
    referrals.count
  end
end

#set_verify_codeObject



360
361
362
# File 'app/models/user.rb', line 360

def set_verify_code
  self.verify_code = rand(10**5).to_i
end

#setup_user_loyaltyObject



373
374
375
# File 'app/models/user.rb', line 373

def setup_user_loyalty
  build_user_loyalty
end

#setup_usernameObject



364
365
366
367
# File 'app/models/user.rb', line 364

def setup_username
  name = username.presence || email.to_s.split('@').first
  self.username = name
end

#singapore_phone_number?Boolean

Checks if the user's phone number is a valid Singaporean phone number.

This method parses the user's full phone number (including country code) and verifies if it is valid and specifically valid for Singapore.

Examples:

user = User.find(1)
user.phone_v2_full = '6591234567'
user.singapore_phone_number? #=> true or false

Returns:

  • (Boolean)

    true if the phone number is valid and belongs to Singapore, false otherwise. Returns false if the phone number is blank or invalid. If a parsing error occurs, the error is reported to APM and false is returned.



564
565
566
567
568
569
570
571
572
# File 'app/models/user.rb', line 564

def singapore_phone_number?
  return false if phone_v2_full.blank?

  parsed_phone = Phonelib.parse(phone_v2_full)
  parsed_phone.valid? && parsed_phone.valid_for_country?(Country.find_singapore.alpha2)
rescue Phonelib::Error => e
  APMErrorHandler.report("#{self.class} #{e.message}", user_id: id)
  false
end

#thai_phone_number?Boolean

Checks if the user's phone number is a valid Thai phone number.

This method parses the user's full phone number (including country code) and verifies if it is valid and specifically valid for Thailand.

Examples:

user = User.find(1)
user.phone_v2_full = '66812345678'
user.thai_phone_number? #=> true or false

Returns:

  • (Boolean)

    true if the phone number is valid and belongs to Thailand, false otherwise. Returns false if the phone number is blank or invalid. If a parsing error occurs, the error is reported to APM and false is returned.



541
542
543
544
545
546
547
548
549
# File 'app/models/user.rb', line 541

def thai_phone_number?
  return false if phone_v2_full.blank?

  parsed_phone = Phonelib.parse(phone_v2_full)
  parsed_phone.valid? && parsed_phone.valid_for_country?(Country.find_thailand.alpha2)
rescue Phonelib::Error => e
  APMErrorHandler.report("#{self.class} #{e.message}", user_id: id)
  false
end

#update_booking_summary(restaurant_id = nil) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'app/models/user.rb', line 490

def update_booking_summary(restaurant_id = nil)
  # Summary for a specific restaurant or all restaurants
  summary = if restaurant_id
              {
                booking_count: reservations.where(restaurant_id: restaurant_id).exclude_temporary.count,
                cancel_count: reservations.where(restaurant_id: restaurant_id).cancel_scope.count,
                no_show_count: reservations.where(restaurant_id: restaurant_id).no_show_scope.count,
              }
            else
              {
                booking_count: reservations.exclude_temporary.count,
                cancel_count: reservations.cancel_scope.count,
                no_show_count: reservations.no_show_scope.count,
              }
            end

  # Find or initialize the summary record
  booking_summary = BookingSummary.find_or_initialize_by(user_id: id, restaurant_id: restaurant_id)
  booking_summary.assign_attributes(summary)
  booking_summary.save!
end