Class: Tcat::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/tcat/query.rb

Overview

Query class handles making requests to the Tcat system

Defined Under Namespace

Classes: DeliveryItem

Instance Method Summary collapse

Constructor Details

#initialize(tracking_number = nil) ⇒ Query

Returns a new instance of Query.

Parameters:

  • tracking_number (String, nil) (defaults to: nil)

    Default tracking number used when the per-call methods are invoked without an explicit argument. Pass nil to construct a stateless client and supply the tracking number on each call (matching Tcat::WorkerClient’s shape).



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/tcat/query.rb', line 18

def initialize(tracking_number = nil)
  @secret_string = Tcat.configuration.secret_string
  @secret_key = Tcat.configuration.secret_key
  validate_secrets!

  @tracking_number = tracking_number
  @http_client = HttpClient.new
  @encryption_service = EncryptionService.new(@secret_key)

  # Initialize session to get cookies
  initialize_session
end

Instance Method Details

#history(tracking_number = nil) ⇒ Array<DeliveryItem>

Get complete delivery history

Parameters:

  • tracking_number (String, nil) (defaults to: nil)

    Overrides the constructor value.

Returns:

  • (Array<DeliveryItem>)

    Array of delivery status items, sorted by time (newest first)



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/tcat/query.rb', line 46

def history(tracking_number = nil)
  tn = resolve_tracking_number(tracking_number)
  response_body = @http_client.post(data(tn))
  if response_body
    result = Ox.load(response_body, mode: :hash, with_cdata: true)
    return [] if result.dig(:Result, :Status) != '0'

    extract_delivery_history(result)
  end
rescue StandardError => e
  warn "Error getting delivery history: #{e.message}" if $DEBUG
  []
end

#latest_status(tracking_number = nil) ⇒ DeliveryItem?

Get latest delivery status with details

Parameters:

  • tracking_number (String, nil) (defaults to: nil)

    Overrides the constructor value.

Returns:

  • (DeliveryItem, nil)

    Latest delivery status or nil if no history



63
64
65
66
67
68
# File 'lib/tcat/query.rb', line 63

def latest_status(tracking_number = nil)
  items = history(tracking_number)
  return nil if items.empty?

  items.first
end

#status_code(tracking_number = nil) ⇒ Symbol

Get current delivery status code

Parameters:

  • tracking_number (String, nil) (defaults to: nil)

    Overrides the constructor value.

Returns:

  • (Symbol)

    Status code (:done, :delivering, :collected, :in_transit, :unknown)



34
35
36
37
38
39
40
41
# File 'lib/tcat/query.rb', line 34

def status_code(tracking_number = nil)
  tn = resolve_tracking_number(tracking_number)
  response_body = @http_client.post(data(tn))
  parse_status_code(response_body) if response_body
rescue HttpClient::RequestError
  # Log error or handle it appropriately
  nil
end