Class: StandaloneDelivery
Overview
== Schema Information
Table name: standalone_deliveries
Database name: primary
id :bigint not null, primary key
actual_shipping_cost :decimal(5, 2)
billing_postal_code :string
reference_number :string
service_code :string
shipping_account_number :string
shipping_rates :hstore is an Array
state :string default("open"), not null
created_at :datetime not null
updated_at :datetime not null
creator_id :integer
destination_address_id :integer
origin_address_id :integer
store_id :integer not null
updater_id :integer
Indexes
index_standalone_deliveries_on_destination_address_id (destination_address_id)
index_standalone_deliveries_on_origin_address_id (origin_address_id)
index_standalone_deliveries_on_service_code (service_code)
index_standalone_deliveries_on_store_id (store_id)
Constant Summary
Models::Auditable::ALWAYS_IGNORED
Models::Schedulable::SIMPLE_FORM_OPTIONS
#creator, #updater
Delegated Instance Attributes
collapse
Class Method Summary
collapse
Instance Method Summary
collapse
#cartons_total, #crates_total, #pallets_total, #ship_freight_class_from_shipments, #ship_volume_from_shipments, #ship_volume_from_shipments_in_cubic_feet, #ship_weight_from_shipments, #shipment_set, #shipments_for_measure
#all_skipped_columns, #audit_reference_data, #should_not_save_version, #stamp_record
ransackable_associations, ransackable_attributes, ransackable_scopes, ransortable_attributes, #to_relation
config
#after_commit
#publish_event
Class Method Details
A relation of StandaloneDeliveries that are complete. Active Record Scope
47
|
# File 'app/models/standalone_delivery.rb', line 47
scope :complete, -> { where("standalone_deliveries.state = 'complete'") }
|
A relation of StandaloneDeliveries that are open. Active Record Scope
43
|
# File 'app/models/standalone_delivery.rb', line 43
scope :open, -> { where("standalone_deliveries.state = 'open'") }
|
A relation of StandaloneDeliveries that are packaged. Active Record Scope
44
|
# File 'app/models/standalone_delivery.rb', line 44
scope :packaged, -> { where("standalone_deliveries.state = 'packaged'") }
|
.ship_labeled ⇒ ActiveRecord::Relation<StandaloneDelivery>
A relation of StandaloneDeliveries that are ship labeled. Active Record Scope
46
|
# File 'app/models/standalone_delivery.rb', line 46
scope :ship_labeled, -> { where("standalone_deliveries.state = 'ship_labeled'") }
|
.ship_rated ⇒ ActiveRecord::Relation<StandaloneDelivery>
A relation of StandaloneDeliveries that are ship rated. Active Record Scope
45
|
# File 'app/models/standalone_delivery.rb', line 45
scope :ship_rated, -> { where("standalone_deliveries.state = 'ship_rated'") }
|
Instance Method Details
#address ⇒ Object
330
331
332
|
# File 'app/models/standalone_delivery.rb', line 330
def address
destination_address
end
|
#all_labels_pdf ⇒ Object
308
309
310
|
# File 'app/models/standalone_delivery.rb', line 308
def all_labels_pdf
uploads.where(category: 'all_labels_pdf').order(id: :desc).first
end
|
#calculate_declared_value ⇒ Object
Total insured/declared value across all packages (mirrors Delivery#calculate_declared_value intent).
Used by Shipment#compute_shipment_declared_value when splitting value per package for rate/label APIs.
Aggregate via ShipmentContent + includes to avoid N+1 when many packages exist (CodeRabbit PR #571).
142
143
144
145
146
147
148
149
150
151
152
|
# File 'app/models/standalone_delivery.rb', line 142
def calculate_declared_value
ShipmentContent.joins(:shipment)
.where(shipments: { standalone_delivery_id: id })
.includes(line_item: { item: { supplier_items: :supplier_item_prices } })
.sum do |sc|
li = sc.line_item
next 0.0 unless li
(li.unit_value_for_commercial_invoice || 0) * sc.quantity.to_f
end
end
|
#calculate_ship_rates ⇒ Object
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
|
# File 'app/models/standalone_delivery.rb', line 159
def calculate_ship_rates
result = { status_code: :error, status_message: 'no rates returned' }
all_rate_hashes = []
rate_hashes_array = WyShipping.find_standalone_delivery_shipping_rates(self)
rate_hashes_array.each do |res|
rate_hashes = (res[:request_response][:rates] || []).sort_by { |r| r[:total_charges].to_f } if res[:request_response]
next unless (res[:status_code] == :ok) && rate_hashes.any?
result[:status_code] = :ok
result[:status_message] = ''
all_rate_hashes += rate_hashes
end
if all_rate_hashes.any?
all_rate_hashes.uniq! { |h| h[:service_code] }
all_rate_hashes.sort_by! { |r| r[:total_charges].to_f }
self.shipping_rates = all_rate_hashes previous_carrier = shipments.where.not(carrier: [nil, '']).pick(:carrier)
preferred = previous_carrier && shipping_rates.find { |r| r['carrier'] == previous_carrier }
self.service_code = (preferred || shipping_rates.first)['service_code']
ship_rate_standalone_delivery!
reload
end
result
end
|
#carrier ⇒ Object
Also known as:
reported_carrier
154
155
156
|
# File 'app/models/standalone_delivery.rb', line 154
def carrier
@carrier ||= (service_code.present? ? shipping_rates.find { |sr| sr['service_code'] == service_code }&.dig('carrier') : nil)
end
|
#company_name ⇒ Object
89
90
91
92
93
94
95
|
# File 'app/models/standalone_delivery.rb', line 89
def company_name
cn = destination_address&.party&.full_name unless destination_address&.party&.is_person?
cn ||= destination_address&.company_name_override
return unless cn
cn.to_s.gsub(/[^0-9a-z\s]/i, '')[0..34]
end
|
#country ⇒ Object
Alias for Origin_address#country
322
|
# File 'app/models/standalone_delivery.rb', line 322
delegate :country, to: :origin_address
|
#destination_address ⇒ Address
35
|
# File 'app/models/standalone_delivery.rb', line 35
belongs_to :destination_address, class_name: 'Address', validate: true, optional: true
|
324
325
326
327
328
|
# File 'app/models/standalone_delivery.rb', line 324
def formatted_address(separator: '<br>')
return unless (a = address)
a.full_address(true, separator, person_name)
end
|
#generate_all_labels_pdf ⇒ Object
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
|
# File 'app/models/standalone_delivery.rb', line 251
def generate_all_labels_pdf
uploads.destroy_by(category: 'all_labels_pdf')
all_labels = shipments.completed.includes(:uploads).filter_map do |s|
s.uploads.find { |u| u.category == 'ship_label_pdf' }
end
file_name = "#{id}_all_labels_#{Time.current.strftime('%m_%d_%Y_%I_%M%p')}.pdf".downcase
all_labels_path = Rails.application.config.x.temp_storage_path.join(file_name)
Rails.logger.debug { "self.generate_all_labels_pdf: all_labels_path: #{all_labels_path}, all_labels: #{all_labels.inspect}" }
if all_labels.size == 1
FileUtils.cp(all_labels.first.to_file, all_labels_path)
else
PdfTools.combine(all_labels, output_file_path: all_labels_path)
end
upload = Upload.uploadify(all_labels_path, 'all_labels_pdf')
raise 'Combo label was not generated' unless upload
uploads << upload
end
|
#generate_labels ⇒ Object
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
217
218
219
220
221
222
223
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/standalone_delivery.rb', line 184
def generate_labels
shipping_result = WyShipping.ship_standalone_delivery(self)
Rails.logger.info("#{Time.current}: StandaloneDelivery ID #{id}, labels generated START LOG $$$$$$$$$$$$$$$$$$$$$$$$$$$$, status_code: #{shipping_result[:status_code]}")
if shipping_result[:status_code] == :error
Rails.logger.info("#{carrier}, request/response:")
Rails.logger.info("#{begin
shipping_result[:shipment][:ship_reply_xml]
rescue StandardError
nil
end}
")
{ status_code: shipping_result[:status_code], status_message: shipping_result[:status_message] }
else
Rails.logger.debug("Shipping result received", standalone_delivery_id: id)
self.actual_shipping_cost = shipping_result[:shipment][:total_charges]
save reload shipments.awaiting_label.each_with_index do |shipment, i|
ship_result_label = shipping_result.dig(:shipment, :labels, i)
Rails.logger.debug { "shipment: #{shipment.inspect}" }
Rails.logger.debug { "shipping_result[:shipment][:labels][i]: #{ship_result_label.inspect}" }
Rails.logger.debug { "shipping_result[:shipment][:labels][i][:tracking_number]: #{ship_result_label[:tracking_number] || 'not there'}" }
shipment.carrier = carrier
shipment.skip_tracking_number_validation = true
shipment.tracking_number = ship_result_label[:tracking_number]
shipment.shipengine_label_id = ship_result_label[:shipengine_label_id]
shipment.label_generated!
end
Rails.logger.info("#{Time.current}: StandaloneDelivery ID #{id}, labels generated END LOG $$$$$$$$$$$$$$$$$$$$$$$$$$$$")
save
label_exceptions = []
status_code = :ok
shipments.label_complete.each_with_index do |shipment, i|
if carrier == 'SpeedeeDelivery'
label_exceptions << (i + 1) unless shipment.generate_speedee_label_pdf(shipping_result[:shipment][:rate_data])
else
ship_result_label = shipping_result.dig(:shipment, :labels, i)
old_label_path = ship_result_label[:image]&.path
if old_label_path
label_exceptions << (i + 1) unless shipment.generate_ship_label_pdf(old_label_path, carrier)
end
end
end
if label_exceptions.empty? && status_code == :ok
generate_all_labels_pdf
status_message = "Labels generated for #{shipments.completed.length} packages. Actual charge: #{store.catalogs.first.currency_symbol}#{actual_shipping_cost}. #{status_message}"
save
{ status_code: status_code, status_message: status_message }
else
msg = +"Can't generate labels"
msg << ", there was an issue with labels #{label_exceptions.map { |l| l + 1 }.join(', ')}" if label_exceptions.any?
msg << ", status code returned: #{status_code}" unless status_code == :ok
msg << '.'
{ status_code: :error, status_message: msg }
end
end
end
|
#manually_complete? ⇒ Boolean
131
132
133
|
# File 'app/models/standalone_delivery.rb', line 131
def manually_complete?
complete? and !ready_to_print_labels?
end
|
#name ⇒ Object
97
98
99
|
# File 'app/models/standalone_delivery.rb', line 97
def name
"Standalone Delivery, ID: #{id}, from: #{origin_address&.recipient || 'n/a'} to: #{destination_address&.recipient || 'n/a'}"
end
|
#ok_to_delete? ⇒ Boolean
312
313
314
315
316
|
# File 'app/models/standalone_delivery.rb', line 312
def ok_to_delete?
ok = true
ok = false unless open? && shipments.all?(&:ok_to_delete_with_standalone_delivery?)
ok
end
|
#origin_address ⇒ Address
34
|
# File 'app/models/standalone_delivery.rb', line 34
belongs_to :origin_address, class_name: 'Address', validate: true, optional: true
|
#person_name ⇒ Object
destination_address&.person_name_override&.to_s.gsub(/[^0-9a-z\s]/i, '')[0..34]
destination_address&.company_name_override&.to_s.gsub(/[^0-9a-z\s]/i, '')[0..34]
81
82
83
84
85
86
87
|
# File 'app/models/standalone_delivery.rb', line 81
def person_name
pn = destination_address&.party&.full_name if destination_address.party&.is_person?
pn ||= destination_address&.person_name_override
return unless pn
pn.to_s.gsub(/[^0-9a-z\s]/i, '')[0..34]
end
|
#ready_to_complete? ⇒ Boolean
119
120
121
|
# File 'app/models/standalone_delivery.rb', line 119
def ready_to_complete?
shipments.any?(&:label_complete?)
end
|
#ready_to_label? ⇒ Boolean
115
116
117
|
# File 'app/models/standalone_delivery.rb', line 115
def ready_to_label?
shipping_rates&.any? and shipments.any?(&:awaiting_label?)
end
|
#ready_to_manually_complete? ⇒ Boolean
123
124
125
|
# File 'app/models/standalone_delivery.rb', line 123
def ready_to_manually_complete?
shipments.none? { |s| s.label_complete? or s.awaiting_label? }
end
|
#ready_to_print_labels? ⇒ Boolean
127
128
129
|
# File 'app/models/standalone_delivery.rb', line 127
def ready_to_print_labels?
all_labels_pdf.present? and shipments.label_complete.any?
end
|
#ready_to_print_ship_label? ⇒ Boolean
101
102
103
104
105
|
# File 'app/models/standalone_delivery.rb', line 101
def ready_to_print_ship_label?
(ship_labeled? or complete?) and
all_labels_pdf.present? and
shipments.label_complete.any?
end
|
#ready_to_rate? ⇒ Boolean
111
112
113
|
# File 'app/models/standalone_delivery.rb', line 111
def ready_to_rate?
shipments.any?(&:awaiting_label?)
end
|
#ready_to_reset? ⇒ Boolean
107
108
109
|
# File 'app/models/standalone_delivery.rb', line 107
def ready_to_reset?
shipments.all?(&:ok_to_delete_with_standalone_delivery?) && !ready_to_rate?
end
|
#send_canada_post_manual_void_email(tracking_numbers) ⇒ Object
304
305
306
|
# File 'app/models/standalone_delivery.rb', line 304
def send_canada_post_manual_void_email(tracking_numbers)
Mailer.canada_post_manual_void_email_for_standalone_delivery(self, tracking_numbers).deliver
end
|
#ship_natively_key ⇒ Object
318
319
320
|
# File 'app/models/standalone_delivery.rb', line 318
def ship_natively_key
nil
end
|
#shipments ⇒ ActiveRecord::Relation<Shipment>
36
|
# File 'app/models/standalone_delivery.rb', line 36
has_many :shipments, dependent: :destroy
|
33
|
# File 'app/models/standalone_delivery.rb', line 33
belongs_to :store, optional: true
|
#store_country_iso3 ⇒ Object
135
136
137
|
# File 'app/models/standalone_delivery.rb', line 135
def store_country_iso3
store&.mailing_address&.country_iso3
end
|
#uploads ⇒ ActiveRecord::Relation<Upload>
37
|
# File 'app/models/standalone_delivery.rb', line 37
has_many :uploads, as: :resource, dependent: :destroy
|
#void_shipments ⇒ Object
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
|
# File 'app/models/standalone_delivery.rb', line 273
def void_shipments
if shipments.label_complete.any?
SpeedeeManifest.drop_voided_shipments!(shipments)
tracking_numbers = shipments.label_complete.pluck(:tracking_number)
shipping_result = {}
shipping_result[:status_code] = :ok
shipping_result = WyShipping.void_standalone_delivery(self)
if shipping_result[:status_code] != :ok
Mailer.admin_notification("standalone_delivery#void_shipments for standalone_delivery #{id} returned error shipping_result[:status_code]: #{shipping_result[:status_code]}",
"standalone_delivery#void_shipments for standalone_delivery #{id} returned error shipping_result[:status_code]: #{shipping_result[:status_code]}, shipping_result[:status_message]: #{shipping_result[:status_message]}, shipment tracking numbers: #{tracking_numbers.join(', ')}").deliver_now
send_canada_post_manual_void_email(tracking_numbers) if carrier == 'Canadapost'
end
shipments.label_complete.each do |s|
s.label_voided!
s.ready_for_label!
end
self.shipping_rates = []
self.service_code = nil
self[:state] = 'packaged'
save!(validate: false)
{ status_code: shipping_result[:status_code],
status_message: "Please ensure you manually void manual shipments. Shipments voided. #{shipping_result[:status_message]}" }
else
{ status_code: :error, status_message: "Can't void postage label(s) because the standalone delivery has no postage label(s)." }
end
end
|