Class: Shipping::DeliveryMd5Extractor

Inherits:
BaseService show all
Defined in:
app/services/shipping/delivery_md5_extractor.rb

Overview

Takes a delivery, review line items and shipment contents
and create or update records in the Packings table
returns a result object with the packings created if any

Defined Under Namespace

Classes: Result

Instance Attribute Summary collapse

Attributes inherited from BaseService

#options

Instance Method Summary collapse

Methods inherited from BaseService

#log_debug, #log_error, #log_info, #log_warning, #logger, #tagged_logger

Constructor Details

#initialize(options = {}) ⇒ DeliveryMd5Extractor

Returns a new instance of DeliveryMd5Extractor.



19
20
21
22
23
# File 'app/services/shipping/delivery_md5_extractor.rb', line 19

def initialize(options = {})
  @ignore_timestamp = options.delete(:ignore_timestamp).to_b
  @origin = options.delete(:origin)
  super
end

Instance Attribute Details

#ignore_timestampObject (readonly)

Returns the value of attribute ignore_timestamp.



17
18
19
# File 'app/services/shipping/delivery_md5_extractor.rb', line 17

def ignore_timestamp
  @ignore_timestamp
end

Instance Method Details

#process(delivery) ⇒ 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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'app/services/shipping/delivery_md5_extractor.rb', line 25

def process(delivery)
  result = Result.new(status: :empty)
  return result unless delivery.has_valid_shipments? && delivery.line_items.goods.present?

  logger.tagged("Delivery:#{delivery.id}") do
    shipments = delivery.shipments.packed_or_measured.includes(shipment_contents: :line_item).select(&:has_dimensions?)
    # Load up the goods in the delivery
    item_hash = delivery.packable_item_hash
    # Run these line items through our md5 hasher
    md5_result = Shipping::Md5HashItem.process(item_hash)
    logger.info "delivery md5: #{md5_result.md5}, item string: #{md5_result.items_string}"
    # Store in delivery model (for backward compatibility)
    delivery.update_column(:packaged_items_md5_hash, md5_result.md5)
    result.delivery_md5 = md5_result.md5
    # Create a packing for the entire delivery and all contents
    logger.info "Storing completed delivery to packing model: #{md5_result.md5}"
    # We record packing different for parcel vs ltl
    service_type = Packing.service_types[(delivery.ltl_freight? ? :freight_service : :parcel_service)]
    packing = Packing.where(md5: md5_result.md5, service_type: service_type).first_or_initialize

    incoming_origin = (@origin || :from_delivery).to_s

    # Skip when an existing fresh row outranks the incoming write. The
    # previous check compared `packing.created_at > delivery.created_at`
    # while ALSO overwriting `packing.created_at` to `delivery.created_at`
    # on every save — which broke whenever a re-quote brought an older
    # delivery back through pre-pack with better measurements. The check
    # rejected the warehouse's freshest data because the source delivery
    # happened to be older than whatever delivery had last touched the row.
    # See Packing#authoritative_over? for the new origin+freshness rule.
    skip_packing_storage = packing.persisted? && !ignore_timestamp &&
                           packing.authoritative_over?(incoming_origin)

    # canadian skip! we will only take canadian package data if nothing exists
    origin_country = delivery.origin_address&.country_iso3
    canadian_skip = origin_country == 'CAN' && packing.persisted?

    if skip_packing_storage
      result.message = warn_msg = "Existing #{packing.origin} packing #{packing.id} outranks incoming #{incoming_origin} (last updated #{packing.updated_at}); skip saving"
      logger.warn warn_msg
      result.status = :warning
      return result
    elsif canadian_skip
      result.message = warn_msg = "Packing data already exists and since delivery is from canada we are going to ignore it"
      logger.warn warn_msg
      result.status = :warning
      return result
    else
      # Async handlers re-query the delivery by id but cannot prevent a
      # concurrent destroy (e.g. Itemizable#purge_empty_quoting_deliveries)
      # between the find_by and this INSERT. Treat the resulting FK
      # violation as the same clean no-op the AppSignal #4958 handler
      # design already applies for the destroyed-before-perform case.
      begin
        # Map all our packed_or_measured shipments to pack dimensions
        packing.packdims = shipments.map(&:to_packdims).sort
        # Create a link to the delivery
        packing.delivery = delivery
        packing.origin = @origin || :from_delivery
        # Store the line items and quantities this md5 represents
        packing.contents = md5_result.full_item_id_hash
        if packing.save
          # No duplicates of item ids by using union
          packing.item_ids |= md5_result.kit_item_ids # This allows us to search kit parents in the future
          result.packings << packing
          # Now see if we can also create/update a packing of relevant items, that is when md5 is not equal to relevant_md5
          relevent_items_packing = nil
          if md5_result.relevant_md5 != md5_result.md5
            # Now also find or create a packing of the relevant item md5
            relevent_items_packing = Packing.where(md5: md5_result.relevant_md5, service_type: service_type).first_or_initialize
            relevent_items_packing.packdims = shipments.map(&:to_packdims).sort
            # Create a link to the delivery
            relevent_items_packing.delivery = delivery
            relevent_items_packing.origin = @origin || :from_delivery
            # Store the line items and quantities this md5 represents
            relevent_items_packing.contents = md5_result.relevant_full_item_id_hash
            # No duplicates of item ids by using union
            relevent_items_packing.item_ids |= md5_result.relevant_kit_item_ids # This allows us to search kit parents in the future
            if relevent_items_packing.save && packing.update(relevant_md5: relevent_items_packing.md5)
              result.packings << relevent_items_packing
            else
              result.message = "Ooops, could not save packing or relevent_items_packing: #{packing.errors_to_s}, #{relevent_items_packing.errors_to_s}"
              logger.error
              result.status = :error
              return result
            end
          end
          result.status = :success
        else
          result.message = "Ooops, could not save packing: #{packing.errors_to_s}"
          logger.error
          result.status = :error
          return result
        end
      rescue ActiveRecord::InvalidForeignKey => e
        result.message = warn_msg = "Delivery #{delivery.id} destroyed mid-flight; skip saving packing (#{e.message})"
        logger.warn warn_msg
        result.status = :warning
        return result
      rescue ActiveRecord::RecordNotUnique => e
        # Only swallow the known concurrent insert race on
        # `index_packings_on_md5_and_service_type`. Any other unique
        # violation in this block (relevant_items_packing, item_ids union,
        # …) is a real integrity error and must surface.
        raise unless e.message.include?('index_packings_on_md5_and_service_type')

        # Concurrent labeling can race past the `first_or_initialize` check:
        # two workers both see no row for (md5, service_type) and both
        # attempt the INSERT. The second hits the unique index. Treat as a
        # clean skip — the first writer's data is already persisted, and
        # the two inputs are derived from the same md5, so they describe
        # the same packing.
        result.message = warn_msg = "Packing #{md5_result.md5}/#{service_type} created concurrently; skip saving (#{e.message.truncate(120)})"
        logger.warn warn_msg
        result.status = :warning
        return result
      end
    end

    # Are all our shipment contents defined? in that case we can also
    # record the md5 of individual shipments for their content in the packdim_contents
    defined_shipments = shipments.select { |s| s.shipment_contents.present? }
    if defined_shipments.present? && defined_shipments.length == shipments.length
      packdim_contents = []
      relevant_items_packdim_contents = []
      defined_shipments.each do |shp|
        # Extract the line items contained in this shipment
        shipment_item_hash = shp.shipment_contents.includes(line_item: :item).each_with_object({}) do |sc, hsh|
          item = sc.line_item.item
          hsh[item] ||= 0
          hsh[item] += sc.quantity.abs
        end
        # Run those through our trusty md5 extractor (which looks at item kits as well)
        shp_md5_result = Shipping::Md5HashItem.process(shipment_item_hash)
        shp_md5 = shp_md5_result.md5
        logger.info "Multi shipments delivery with content defined, storing shipment id #{shp.id} to packing with: #{shp_md5}"
        packdim_contents.concat(Packing.format_packdim_contents(md5: shp_md5_result.md5, contents: shp_md5_result.full_item_id_hash, packdims: shp.to_packdims))
        relevant_items_packdim_contents.concat(Packing.format_packdim_contents(md5: shp_md5_result.relevant_md5, contents: shp_md5_result.relevant_full_item_id_hash, packdims: shp.to_packdims)) if relevent_items_packing.present?
      end
      # Pass the native Ruby Array/Hash so Rails casts to JSONB array/object
      # rather than encoding to a JSON string first. The prior `.to_json`
      # form happened to work for arrays (Postgres parsed `'[...]'` back into
      # a JSONB array) but stored empty hashes as the JSON-string scalar
      # `'"{}"'` — see Packing rows 141806/141890/142621 in prod.
      packing.update_column(:packdim_contents, packdim_contents)
      relevent_items_packing.presence&.update_column(:packdim_contents, relevant_items_packdim_contents)
    else
      packing.update_column(:packdim_contents, {})
      relevent_items_packing.presence&.update_column(:packdim_contents, {})
    end
  end
  result
end