Class: VendorsService::InventorySync::InventoryFetcherService

Inherits:
Object
  • Object
show all
Includes:
CountryEmailHelper, ElasticAPM::SpanHelpers, SupplierConfig
Defined in:
app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb

Overview

Service for fetching inventory availability from external suppliers with fallback strategy.

This service handles the common logic for fetching inventory across different suppliers:

  • Party size fallback strategy (tries multiple party sizes to maximize availability)

  • Missing timeslot tracking and retry logic across different party sizes

  • Zero inventory notification when no timeslots found after all attempts

  • ElasticAPM instrumentation and business logging with JSON format for OpenSearch

  • Common validation, error handling, and HTTP request utilities via execute_parallel_requests

  • Shared error classes for consistent error handling across suppliers

  • Restaurant timeslot generation based on opening hours and time intervals

Examples:

Usage

service = VendorsService::InventorySync::InventoryFetcherService.new(
  restaurant: restaurant_object,
  supplier: :tablecheck
)
inventory_data = service.fetch_availability(["2025-01-15", "2025-01-16"])
# Returns: [{ datetime: Time.object, quantity_available: Integer }]

Defined Under Namespace

Classes: RateLimitExceededError, SupplierApiError

Constant Summary

Constants included from SupplierConfig

SupplierConfig::SUPPLIER_CONFIG

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from CountryEmailHelper

#merchant_email_for_country

Methods included from SupplierConfig

#get_supplier_config

Constructor Details

#initialize(restaurant:, supplier:) ⇒ InventoryFetcherService

Returns a new instance of InventoryFetcherService.



34
35
36
37
38
39
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 34

def initialize(restaurant:, supplier:)
  @restaurant = restaurant
  @supplier = supplier.to_sym
  @config = get_supplier_config(supplier, { restaurant_id: restaurant&.id })
  @restaurant_tz = Time.find_zone(restaurant.time_zone)
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



32
33
34
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 32

def config
  @config
end

#restaurantObject (readonly)

Returns the value of attribute restaurant.



32
33
34
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 32

def restaurant
  @restaurant
end

#restaurant_tzObject (readonly)

Returns the value of attribute restaurant_tz.



32
33
34
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 32

def restaurant_tz
  @restaurant_tz
end

#supplierObject (readonly)

Returns the value of attribute supplier.



32
33
34
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 32

def supplier
  @supplier
end

Instance Method Details

#execute_parallel_requests(dates) {|date_block, hydra, availabilities| ... } ⇒ Array<Hash>

Executes parallel HTTP requests using Typhoeus::Hydra with error handling and retry logic. Provides common functionality for supplier API calls with date batching.

Parameters:

  • dates (Array<String>)

    Array of date strings to fetch in YYYY-MM-DD format

  • block (Proc)

    Block that handles request building and response processing for each date block

Yields:

  • (date_block, hydra, availabilities)

    Gives date block, hydra instance, and availabilities array to the block

Returns:

  • (Array<Hash>)

    Array of inventory data from all successful requests



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
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 432

def execute_parallel_requests(dates, &_block)
  validated_dates = validate_dates(dates)
  max_days_per_request = config[:max_availability_days_per_request]

  availabilities = []
  hydra = Typhoeus::Hydra.new

  date_blocks = validated_dates.each_slice(max_days_per_request).to_a

  # Queue requests for each date block
  date_blocks.each do |date_block|
    yield(date_block, hydra, availabilities) if block_given?
  end

  begin
    hydra.run
  rescue StandardError => e
    report_and_log_error(
      "#{supplier.capitalize} parallel requests failed: #{e.message}",
      dates_count: validated_dates.count,
      exception_class: e.class.name,
      exception_message: e.message,
    )
    raise
  end

  if availabilities.present?
    BUSINESS_LOGGER.info(
      "#{supplier.capitalize} availability retrieved",
      restaurant_id: restaurant.id,
      dates_count: validated_dates.count,
      timeslots_count: availabilities.size,
    )
  end

  availabilities
end

#fetch_availability(dates_within_range) ⇒ Array<Hash>

Fetches inventory availability from supplier for the given dates using party size fallback strategy.

The method tries different party sizes (largest to smallest) to maximize availability. For each party size, it fetches availability and removes successfully found dates from the missing list. Sends notification for zero inventory scenarios.

Examples:

Return format

[
  { datetime: Time.parse("2025-01-15T11:00:00+07:00"), quantity_available: 5 },
  { datetime: Time.parse("2025-01-15T11:30:00+07:00"), quantity_available: 3 }
]

Parameters:

  • dates_within_range (Array<String>)

    Array of date strings in YYYY-MM-DD format

Returns:

  • (Array<Hash>)

    Array of inventory hashes with :datetime (Time) and :quantity_available (Integer) keys



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
147
148
149
150
151
152
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 55

def fetch_availability(dates_within_range)
  BUSINESS_LOGGER.info("#{self.class}: Fetching inventory availability from #{supplier.capitalize}")

  # Generate partysize array using simplified logic
  partysize_array = generate_partysize_array

  BUSINESS_LOGGER.info(
    "#{self.class}: Using partysize array", {
      partysize_array: partysize_array,
      restaurant_id: restaurant.id,
    }
  )

  all_inventory_data = []
  missing_dates = generate_restaurant_open_hours_timeslots(dates_within_range)

  # Try each party size in the array, starting from largest
  partysize_array.each_with_index do |party_size, index|
    break if missing_dates.empty?

    BUSINESS_LOGGER.info(
      "#{self.class}: Attempting party size #{party_size}", {
        party_size: party_size,
        attempt_number: index + 1,
        missing_dates_count: missing_dates.size,
        is_fallback: index > 0,
      }
    )

    begin
      # Fetch inventory availability for current party size and remaining dates
      inventory_data = config[:inv_service].new(restaurant, dates_within_range,
                                                party_size).fetch_timeslots_with_availability
      if inventory_data.present?
        # Extract dates that have available inventory from the array of hashes
        available_dates = inventory_data.filter_map { |slot| slot[:datetime] if slot.is_a?(Hash) && slot[:datetime] }

        # Add only new inventory data that doesn't already exist (based on datetime)
        existing_datetimes = all_inventory_data.pluck(:datetime).to_set
        new_inventory_data = inventory_data.reject { |slot| existing_datetimes.include?(slot[:datetime]) }

        all_inventory_data.concat(new_inventory_data)

        # Remove successfully fetched dates from missing_dates
        missing_dates = missing_dates - available_dates
        dates_within_range = extract_unique_dates_from_timeslots(missing_dates)

        BUSINESS_LOGGER.info(
          "#{self.class}: Found inventory for party size #{party_size}", {
            party_size: party_size,
            found_inventory_count: inventory_data.size,
            available_dates_count: available_dates.size,
            remaining_missing_dates: missing_dates.size,
          }
        )

      else
        BUSINESS_LOGGER.info(
          "#{self.class}: No inventory found for party size #{party_size}", {
            party_size: party_size,
            attempt_number: index + 1,
          }
        )

      end
    rescue StandardError => e
      report_and_log_error(
        "Error fetching inventory for party size #{party_size}: #{e.message}",
        party_size: party_size,
        missing_dates_count: missing_dates.size,
        exception_class: e.class.name,
        exception_message: e.message,
      )

      BUSINESS_LOGGER.error(
        "#{self.class}: Error fetching for party size #{party_size}", {
          party_size: party_size,
          exception: e.class.name,
          message: e.message,
          restaurant_id: restaurant.id,
        }
      )

      # Continue to next party size on error
      next
    end
  end

  # Log final results
  log_final_results(missing_dates, all_inventory_data, partysize_array)

  # Check if no inventory was found after all attempts and send notification
  if all_inventory_data.blank? && dates_within_range.count > 1
    send_zero_inventory_notification(dates_within_range, partysize_array)
  end

  all_inventory_data
end

#generate_partysize_arrayArray<Integer>

Generates a partysize array using restaurant's largest_table and supplier's min_seat configuration. Creates a descending array of party sizes to try, with fallback values if configuration is invalid.

Examples:

Logic

# If largest_table=10, min_seat=2:
# candidates = [10, 10, 6, 4, 2] -> unique & sorted desc -> [10, 6, 4, 2]

Returns:

  • (Array<Integer>)

    Array of party sizes in descending order (e.g., [15, 10, 6, 4, 2])



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
189
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
216
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 163

def generate_partysize_array
  # Get supplier config for min_seat_method
  min_seat = config[:min_seat_method].call(restaurant)
  largest_table = restaurant&.largest_table.to_i

  # Set defaults if values are invalid
  min_seat = 2 if min_seat <= 0
  largest_table = 10 if largest_table <= 0

  partysize_candidates = [
    largest_table,
    min_seat + 8,
    min_seat + 4,
    min_seat + 2,
    min_seat,
  ]

  # Remove values greater than largest_table and take unique values
  final_array = partysize_candidates.
    select { |size| size <= largest_table }.
    uniq.
    sort.
    reverse

  BUSINESS_LOGGER.info(
    "#{self.class}: Generated partysize array", {
      restaurant_id: restaurant&.id,
      largest_table: largest_table,
      min_seat: min_seat,
      candidates: partysize_candidates,
      final_array: final_array,
    }
  )

  final_array
rescue StandardError => e
  report_and_log_error(
    "Error generating partysize array: #{e.message}",
    largest_table: restaurant&.largest_table,
    exception_class: e.class.name,
    exception_message: e.message,
  )

  # Return fallback array
  fallback_array = [15, 10, 6, 4, 2]
  BUSINESS_LOGGER.warn(
    "#{self.class}: Using fallback partysize array", {
      fallback_array: fallback_array,
      error: e.message,
    }
  )

  fallback_array
end

#generate_restaurant_open_hours_timeslots(dates_within_range) ⇒ Array<String>

Generates all possible restaurant timeslots based on opening hours and time intervals.

Creates a comprehensive list of potential reservation timeslots by:

  • Finding valid restaurant packages (valid_to_have_agendas)

  • Getting opening hours from HhPackage::OpeningHour

  • Using broadest opening window (minimum open, maximum close)

  • Applying restaurant's time interval (15min or 30min from start_time_interval)

  • Converting from restaurant timezone to UTC ISO8601 format

Examples:

Return format

["2025-01-20T04:00:00.000Z", "2025-01-20T04:30:00.000Z", "2025-01-20T05:00:00.000Z"]
# Empty array if no opening hours or packages found

Parameters:

  • dates_within_range (Array<String>)

    Array of date strings in YYYY-MM-DD format

Returns:

  • (Array<String>)

    Array of generated timeslot strings in UTC ISO8601 format with milliseconds



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
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
369
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
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 306

def generate_restaurant_open_hours_timeslots(dates_within_range)
  restaurant_package_ids = restaurant.restaurant_packages.valid_to_have_agendas.pluck(:id)
  if restaurant_package_ids.empty?
    BUSINESS_LOGGER.warn(
      "#{self.class}: No valid restaurant packages found for timeslot generation",
      {
        restaurant_id: restaurant.id,
        restaurant_name: restaurant.name,
        total_packages: restaurant.restaurant_packages.count,
      },
    )
    return []
  end

  # Fetch opening hours for valid packages
  opening_hours = HhPackage::OpeningHour.where(restaurant_package_id: restaurant_package_ids)

  if opening_hours.empty?
    BUSINESS_LOGGER.warn(
      "#{self.class}: No opening hours found for restaurant packages",
      {
        restaurant_id: restaurant.id,
        package_ids: restaurant_package_ids,
      },
    )
    return []
  end

  # Calculate broadest opening window
  min_open_time = opening_hours.minimum(:open)
  max_close_time = opening_hours.maximum(:close)

  if min_open_time.nil? || max_close_time.nil?
    BUSINESS_LOGGER.error(
      "#{self.class}: Invalid opening hours data",
      {
        restaurant_id: restaurant.id,
        min_open_time: min_open_time,
        max_close_time: max_close_time,
        opening_hours_count: opening_hours.count,
      },
    )
    return []
  end

  # Determine time interval (30min or 15min)
  interval_minutes = restaurant.start_time_interval&.include?('30min') ? 30 : 15

  BUSINESS_LOGGER.info(
    "#{self.class}: Generating timeslots for restaurant",
    {
      restaurant_id: restaurant.id,
      min_open_time: min_open_time,
      max_close_time: max_close_time,
      interval_minutes: interval_minutes,
      timezone: restaurant_tz,
      dates_count: dates_within_range.size,
      package_ids: restaurant_package_ids,
    },
  )

  all_timeslots = []

  # Generate timeslots for each date
  dates_within_range.each do |date_string|
    date_obj = Date.parse(date_string)

    # Parse opening hours (format: "HH:MM")
    open_hour, open_minute = min_open_time.split(':').map(&:to_i)
    close_hour, close_minute = max_close_time.split(':').map(&:to_i)

    # Create opening and closing times in restaurant timezone
    open_time = restaurant_tz.local(date_obj.year, date_obj.month, date_obj.day, open_hour, open_minute)
    close_time = restaurant_tz.local(date_obj.year, date_obj.month, date_obj.day, close_hour, close_minute)

    # Handle overnight restaurants (close time next day)
    if close_time <= open_time
      close_time += 1.day
    end

    # Generate timeslots within opening hours
    current_time = open_time
    date_timeslots = []

    while current_time < close_time
      # Convert to UTC and format as ISO8601
      utc_time = current_time.utc
      formatted_time = utc_time.iso8601(3) # 3 for milliseconds precision
      date_timeslots << formatted_time

      current_time += interval_minutes.minutes
    end

    all_timeslots.concat(date_timeslots)
  end

  BUSINESS_LOGGER.info(
    "#{self.class}: Completed timeslot generation",
    {
      restaurant_id: restaurant.id,
      total_timeslots_generated: all_timeslots.size,
    },
  )

  all_timeslots
rescue StandardError => e
  error_message = "#{self.class}#generate_restaurant_open_hours_timeslots: Error generating timeslots"

  report_and_log_error(
    "#{error_message}: #{e.message}",
    dates_count: dates_within_range&.size,
    exception_class: e.class.name,
    exception_message: e.message,
  )

  []
end

#handle_api_response(response, availabilities, response_parser, context = {}) ⇒ void

This method returns an undefined value.

Handles API response with retry logic for rate limiting using Retriable gem. Provides consistent response handling across all suppliers with APM instrumentation.

Parameters:

  • response (Typhoeus::Response)

    HTTP response object

  • availabilities (Array)

    Array to append successful data

  • response_parser (Proc)

    Block to parse response body on success (receives parsed JSON)

  • context (Hash) (defaults to: {})

    Context for logging and error reporting

Raises:



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
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 507

def handle_api_response(response, availabilities, response_parser, context = {})
  cooldown_seconds = config[:rate_limit_cooldown_seconds]

  Retriable.retriable(
    on: RateLimitExceededError,
    base_interval: cooldown_seconds,
    tries: 2,
  ) do
    response_body = parse_json_response(response.body)
    case response.code
    when 200
      BUSINESS_LOGGER.debug(
        "#{supplier.capitalize} API response successful",
        context.merge(
          status: response.code,
          restaurant_id: restaurant.id,
        ),
      )

      availability_data = response_parser.call(response_body)
      availabilities.concat(availability_data)

    when 429
      error_message = 'Too many requests, please try again later.'
      BUSINESS_LOGGER.warn(
        "#{supplier.capitalize} rate limit hit, cooling down before retry",
        context.merge(
          restaurant_id: restaurant.id,
          cooldown_seconds: cooldown_seconds,
        ),
      )
      raise RateLimitExceededError, error_message

    else
      error_message = extract_error_message(response_body, supplier)
      report_and_log_error(
        "#{supplier.capitalize} API error: #{error_message}",
        status: response.code,
        error_message: error_message,
        response: response_body,
        **context,
      )
      raise SupplierApiError, error_message
    end
  end
rescue RateLimitExceededError => e
  report_and_log_error(
    "#{supplier.capitalize} API rate limit exceeded: #{e.message}",
    status: response.code,
    response: parse_json_response(response.body),
    exception_class: e.class.name,
    exception_message: e.message,
    **context,
  )
  raise
end

#log_final_results(missing_dates, all_inventory_data, partysize_array) ⇒ void

This method returns an undefined value.

Logs final results of the availability fetching process with comprehensive metrics. Provides summary of successful fetches, missing timeslots, and success rate calculation.

Parameters:

  • missing_dates (Array<String>)

    Array of timeslot datetimes still missing in UTC ISO8601 format

  • all_inventory_data (Array<Hash>)

    Array of successfully fetched inventory hashes

  • partysize_array (Array<Integer>)

    Array of party sizes that were attempted



587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 587

def log_final_results(missing_dates, all_inventory_data, partysize_array)
  BUSINESS_LOGGER.info(
    "#{self.class}: Final availability fetch results",
    {
      restaurant_id: restaurant.id,
      supplier: supplier,
      total_inventory_found: all_inventory_data.size,
      missing_timeslots_count: missing_dates.size,
      party_sizes_attempted: partysize_array,
      fetch_success_rate: missing_dates.empty? ? 100.0 : ((all_inventory_data.size.to_f / (all_inventory_data.size + missing_dates.size)) * 100).round(2),
    },
  )
end

#queue_request_with_error_handling(request, hydra, availabilities, response_parser, context = {}) ⇒ void

This method returns an undefined value.

Queues a single HTTP request with comprehensive error handling and retry logic. Handles rate limiting, API errors, and response parsing consistently across suppliers.

Parameters:

  • request (Typhoeus::Request)

    The HTTP request to queue

  • hydra (Typhoeus::Hydra)

    Hydra instance for parallel execution

  • availabilities (Array)

    Array to collect successful responses

  • response_parser (Proc)

    Block to parse successful response body

  • context (Hash) (defaults to: {})

    Additional context for logging and error reporting (includes span_name, date, etc.)



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 480

def queue_request_with_error_handling(request, hydra, availabilities, response_parser, context = {})
  request.on_complete do |response|
    handle_api_response(response, availabilities, response_parser, context)
  rescue StandardError => e
    report_and_log_error(
      "#{supplier.capitalize} API unknown error: #{e.message}",
      exception_class: e.class.name,
      exception_message: e.message,
      **context,
    )
    raise SupplierApiError, e.message
  end

  hydra.queue(request)
end

#report_and_log_error(message, **context) ⇒ void

This method returns an undefined value.

Helper to report error to APM and log to BUSINESS_LOGGER in one call. Centralizes error reporting with consistent context handling and automatic context building.

Parameters:

  • message (String)

    Error message for both APM and logger

  • context (Hash)

    Additional context beyond default restaurant/supplier info



608
609
610
611
612
613
614
615
616
617
618
619
620
621
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 608

def report_and_log_error(message, **context)
  # Build base context with restaurant and supplier info
  base_context = {
    restaurant_id: restaurant.id,
    supplier: supplier,
  }.compact

  # Merge with any additional context provided
  full_context = base_context.merge(context)

  # Report to APM and log to BUSINESS_LOGGER with same message and context
  APMErrorHandler.report(message, context: full_context)
  BUSINESS_LOGGER.error(message, context: full_context)
end

#send_staff_notification_email(subject, body, log_message, additional_log_context = {}) ⇒ void

This method returns an undefined value.

Sends staff notification email using StaffMailer with predefined recipients. Centralizes email delivery and business logging for all notification types. Uses country-based email routing for merchant notifications.

Parameters:

  • subject (String)

    Email subject line

  • body (String)

    HTML email body content

  • log_message (String)

    Business log message describing the notification

  • additional_log_context (Hash) (defaults to: {})

    Additional context for business logging



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 272

def send_staff_notification_email(subject, body, log_message, additional_log_context = {})
   = restaurant.user&.email
  merchant_email = merchant_email_for_country(restaurant)
  receivers = [merchant_email, ::VENDOR_TEAM_EMAIL, ].compact.uniq

  StaffMailer.notify_html(subject, body, receivers).deliver_later!

  base_log_context = {
    restaurant_id: restaurant.id,
    supplier: supplier,
    recipients: receivers,
  }

  BUSINESS_LOGGER.info(
    "#{self.class}: #{log_message}",
    base_log_context.merge(additional_log_context),
  )
end

#send_zero_inventory_notification(dates, party_sizes_attempted) ⇒ void

This method returns an undefined value.

Sends notification email when no inventory is available after all party size attempts. Only called when dates.count > 1 and all_inventory_data is blank.

Parameters:

  • dates (Array<String>)

    Array of dates that had no inventory in YYYY-MM-DD format

  • party_sizes_attempted (Array<Integer>)

    Party sizes that were attempted



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
250
251
252
253
254
255
256
257
258
259
260
261
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 225

def send_zero_inventory_notification(dates, party_sizes_attempted)
  APMErrorHandler.report(
    'Supplier inventory is not available',
    context: {
      supplier: supplier,
      restaurant_id: restaurant.id,
      restaurant_name: restaurant.name_en,
      party_sizes_attempted: party_sizes_attempted,
      dates: dates,
      dates_count: dates.count,
    },
  )

  subject = "Zero Inventory for #{supplier} restaurant-#{restaurant.id}"
  body = <<~BODY
    #{supplier} API returns ZERO Inventory after attempting all party sizes for #{dates.count} days for<br><br>

    <strong>Restaurant Details:</strong><br>
    restaurant_name: #{restaurant.name_en}<br>
    restaurant_id: #{restaurant.id}<br>
    supplier: #{supplier}<br><br>

    <strong>Request Details:</strong><br>
    API was called for #{dates.count} days, date ranges from #{dates.first} to #{dates.last}<br><br>
    Party sizes attempted: #{party_sizes_attempted.join(', ')}<br>
  BODY

  send_staff_notification_email(
    subject,
    body,
    'Zero inventory notification sent',
    {
      dates_count: dates.count,
      party_sizes_attempted: party_sizes_attempted,
    },
  )
end

#validate_dates(dates) ⇒ Array<String>

Validates array of dates are all in YYYY-MM-DD string format.

Parameters:

  • dates (Array<String>)

    Array of date strings

Returns:

  • (Array<String>)

    The same validated dates array

Raises:

  • (ArgumentError)

    if any date is not in valid YYYY-MM-DD format



570
571
572
573
574
575
576
577
# File 'app/services/vendors_service/inventory_sync/inventory_fetcher_service.rb', line 570

def validate_dates(dates)
  Array(dates).each do |date|
    unless date.is_a?(String) && date.match?(/\A\d{4}-\d{2}-\d{2}\z/)
      raise ArgumentError, "Invalid date format. Use 'YYYY-MM-DD'."
    end
  end
  dates
end