Class: Pdf::Document::PackingSlip

Inherits:
BaseService
  • Object
show all
Includes:
Base
Defined in:
app/services/pdf/document/packing_slip.rb

Defined Under Namespace

Classes: Result

Constant Summary collapse

MARGINS =
[95, 40, 50, 40].freeze

Constants included from Base

Base::FONT, Base::NIMBUS_SANS_PATH, Base::NIMBUS_SANS_PATH_BOLD, Base::WY_LOGO_PATH

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(delivery, options = {}) ⇒ PackingSlip

Returns a new instance of PackingSlip.



10
11
12
13
14
15
16
17
18
19
# File 'app/services/pdf/document/packing_slip.rb', line 10

def initialize(delivery, options = {})
  @delivery = delivery
  @order = delivery.order
  @customer = @delivery.customer
  @store = @customer.store
  @split_kits = options[:split_kits].to_b
  @skip_plans = options[:skip_plans].to_b
  @line_items_hsh = @delivery.pick_slip_line_items(split_kits: @split_kits)
  @shipment_ids = @line_items_hsh.values.flat_map { |li_props| li_props[:packed_shipments]&.keys || [] }.compact.uniq.sort
end

Instance Attribute Details

#customerObject (readonly)

Returns the value of attribute customer.



8
9
10
# File 'app/services/pdf/document/packing_slip.rb', line 8

def customer
  @customer
end

#deliveryObject (readonly)

Returns the value of attribute delivery.



8
9
10
# File 'app/services/pdf/document/packing_slip.rb', line 8

def delivery
  @delivery
end

#orderObject (readonly)

Returns the value of attribute order.



8
9
10
# File 'app/services/pdf/document/packing_slip.rb', line 8

def order
  @order
end

#skip_plansObject (readonly)

Returns the value of attribute skip_plans.



8
9
10
# File 'app/services/pdf/document/packing_slip.rb', line 8

def skip_plans
  @skip_plans
end

#split_kitsObject (readonly)

Returns the value of attribute split_kits.



8
9
10
# File 'app/services/pdf/document/packing_slip.rb', line 8

def split_kits
  @split_kits
end

#storeObject (readonly)

Returns the value of attribute store.



8
9
10
# File 'app/services/pdf/document/packing_slip.rb', line 8

def store
  @store
end

Instance Method Details

#append_plans(combined_pdf) ⇒ Object



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'app/services/pdf/document/packing_slip.rb', line 413

def append_plans(combined_pdf)
  plan_pdfs = []
  if (master_rooms = order.room_configurations.map { |rc| rc.controlled_by }.compact.uniq).any?
    master_rooms.each_with_index do |rc, _i|
      multizone_plan = rc.get_or_generate_multizone_plan_pdf
      plan_pdfs << multizone_plan if multizone_plan&.attachment
    end
  end
  order.room_configurations.order(:name).each do |rc|
    plan_pdfs << rc.get_or_generate_installation_plan_pdf
    plan_pdfs << rc.get_or_generate_electrical_plan_pdf
  end
  plan_pdfs.compact.each do |pdf|
    combined_pdf << PdfCombinator.load(pdf.to_file)
  end
end

#callObject



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
# File 'app/services/pdf/document/packing_slip.rb', line 370

def call
  combined_pdf = PdfCombinator.new
  # Determine packing list status
  packing_list_status = @customer&.customer_record&.packing_list_status || 'auto_packing_list'
  case packing_list_status
  when 'never_packing_list'
    skip_pack_list = true
    print_custom_pack_list = false
  when 'always_custom_packing_list'
    if @delivery.custom_pack_list.present?
      skip_pack_list = true
      print_custom_pack_list = true
    else
      skip_pack_list = false
      print_custom_pack_list = false
    end
  when 'auto_custom_only_packing_list'
    skip_pack_list = true
    print_custom_pack_list = @delivery.custom_pack_list.present?.to_b
  else
    print_custom_pack_list = skip_pack_list = @delivery.custom_pack_list.present?
  end

  show_packaging = @delivery.show_packaging_on_pick_slip?
  # Write pick slip PDF content to a temporary file and load into combined_pdf
  pick_slip_content = generate_hexapdf_slip(:pick, show_packaging)
  pick_slip_temp_path = write_temp_file(pick_slip_content)
  combined_pdf << PdfCombinator.load(pick_slip_temp_path)

  unless skip_pack_list
    pack_slip_content = generate_hexapdf_slip(:pack, show_packaging)
    pack_slip_temp_path = write_temp_file(pack_slip_content)
    combined_pdf << PdfCombinator.load(pack_slip_temp_path)
  end

  combined_pdf << PdfCombinator.load(@delivery.custom_pack_list.to_file) if print_custom_pack_list
  append_plans(combined_pdf) unless skip_plans

  combined_pdf.pages.each { |p| p.orientation :portrait }

  combined_pdf
end

#configure_document(document) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'app/services/pdf/document/packing_slip.rb', line 49

def configure_document(document)
  super
  dejavu = document.fonts.add('data/fonts/DejaVuSans.ttf')
  document.config['font.fallback'] = [dejavu]
  document.config['font.on_missing_glyph'] = proc do |char, font_wrapper|
    HexaPDF::Font::InvalidGlyph.new(font_wrapper, char)
  end
  document.config['font.on_invalid_glyph'] = lambda do |codepoint, _glyph|
    [dejavu.decode_codepoint(codepoint)]
  end
end

#generate_hexapdf_slip(type, show_packaging) ⇒ Object

Raises:

  • (ArgumentError)


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/services/pdf/document/packing_slip.rb', line 21

def generate_hexapdf_slip(type, show_packaging)
  raise ArgumentError, "#{type} can only be :pick or :pack" unless type.in?(%i[pick pack])

  pick = (type == :pick)
  composer = build_composer(margin: MARGINS)

  composer.style(:ppSlipContact, font: FONT, font_size: 12, margin: 2, text_align: :right, line_height: 15)
  composer.style(:ppSlipContactBold, font: "#{FONT} bold", font_size: 12, margin: 2, text_align: :right, line_height: 15)
  composer.style(:ppSlipOrderNumber, font: FONT, font_size: 20, text_align: :left)
  composer.style(:ppSlipFooter, font: FONT, font_size: 10, text_align: :center)
  composer.style(:regularNimbus, font: FONT, font_size: 10.5, character_spacing: -0.1, word_spacing: -0.2)
  composer.style(:regularNimbusBold, font: "#{FONT} bold", font_size: 10.5, character_spacing: -0.1, word_spacing: -1)

  composer.text("#{pick ? 'Picking' : 'Packing'} List #{@order.name}", style: :ppSlipOrderNumber)

  insert_shipping_info(composer, show_packaging)

  insert_line_items(composer, type, show_packaging)

  insert_headers(composer)

  io = StringIO.new

  composer.write(io, optimize: true)
  io.rewind
  io.read
end

#insert_headers(composer) ⇒ Object



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
# File 'app/services/pdf/document/packing_slip.rb', line 343

def insert_headers(composer)
  logo_url = Pdf::Config::LOGO_PATH
  show_tax_info = false if show_tax_info.nil?
  composer.document.pages.each do |page|
    canvas = page.canvas

    page.box(:media).width
    page_height = page.box(:media).height

    canvas.image(logo_url, at: [35, page_height - 80], width: 210)
    if @store.present?
      formatted_text = [
        { text: "#{@store.mailing_address.full_address(false, ', ', nil, true, true)}\n", style: :ppSlipContact },
        { text: 'Phone #: ', style: :ppSlipContactBold },
        { text: "#{@store.contact_number}\n", style: :ppSlipContact },
        { text: 'Fax #: ', style: :ppSlipContactBold },
        { text: "#{@store.fax_number}\n", style: :ppSlipContact }
      ]
      formatted_text << { text: "\n#{@store.company.tax_info}\n", style: :ppSlipContact } if show_tax_info == true

      canvas.composer.formatted_text(formatted_text, align: :right, style: { text_align: :right }, padding: [35, 40])
    end

    canvas.composer.formatted_text([{ text: 'WarmlyYours.com, Inc. | 24/7 Technical Support | (800) 875-5285 | https://www.WarmlyYours.com/support', style: :ppSlipFooter }], align: :center, valign: :bottom, padding: [0, 0, 25, 0])
  end
end

#insert_line_items(composer, type, show_packaging) ⇒ Object



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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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
303
304
305
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
# File 'app/services/pdf/document/packing_slip.rb', line 173

def insert_line_items(composer, type, show_packaging)
  pick = (type == :pick)

  customize_for_customer = pick ? customize_for_customer.to_b : @customer&.is_canadian_tire?
  check_payments = @delivery.payments.all_authorized.where(category: Payment::CHECK)
  cash_payments = @delivery.payments.all_authorized.where(category: Payment::CASH)

  show_supplier_skus = false
  show_locations = false
  show_qty_on_hand = false
  if pick
    show_supplier_skus = true
    show_locations = true
    show_qty_on_hand = true
  end

  show_oj_distributor_note = false

  cells = []
  cells << if customize_for_customer && !pick
             [
               { content: composer.document.layout.text('Consumer Units', style: :regularNimbusBold), col_span: 6 },
               { content: composer.document.layout.text('Vendor Part #', style: :regularNimbusBold), col_span: 4 },
               { content: composer.document.layout.text("#{@customer.abbreviation_for_packing_list} Product #", style: :regularNimbusBold), col_span: 4 },
               { content: composer.document.layout.text("Serial ##{show_locations ? '   /   Location' : ''}", style: :regularNimbusBold), col_span: 4 }
             ]
           else
             [
               { content: composer.document.layout.text('Qty', style: :regularNimbusBold), col_span: 1 },
               { content: composer.document.layout.text('Part #', style: :regularNimbusBold), col_span: 2 },
               { content: composer.document.layout.text("Serial #  #{show_locations ? ' /   Location' : ''}", style: :regularNimbusBold), col_span: 7 }
             ]
           end
  @line_items_hsh.each do |sku, line_props|
    col_span = customize_for_customer && !pick ? 1 : 2
    if customize_for_customer && !pick
      row = [
        { content: composer.document.layout.text(line_props[:quantity].to_s, style: { font: "#{FONT} bold", text_align: :center, font_size: 10.5 }), row_span: 2, col_span: 6 },
        { content: composer.document.layout.text(show_supplier_skus ? [sku, *line_props[:supplier_skus]].uniq.join("\n") : sku, style: :regularNimbus), col_span: 4 }
      ]
      row << { content: composer.document.layout.text(line_props[:third_party_part_number].to_s, style: :regularNimbus), col_span: 4 } unless line_props[:third_party_part_number].nil?
    else
      row = [
        { content: composer.document.layout.text(line_props[:quantity].to_s, style: { font: "#{FONT} bold", text_align: :center, font_size: 10.5 }), row_span: 2, col_span: 1 },
        { content: composer.document.layout.text(show_supplier_skus ? [sku, *line_props[:supplier_skus]].uniq.join("\n") : sku, style: :regularNimbus), col_span: col_span }
      ]
      row << { content: composer.document.layout.text(line_props[:third_party_part_number].to_s, style: :regularNimbus), col_span: 1 } unless line_props[:third_party_part_number].nil?
    end

    row << { content: composer.document.layout.text(
      begin
        location_content = ''
        if show_locations
          if line_props[:locations].present?
            location_content += line_props[:locations].map { |location| "#{location}" }.join(', ') + '  '
          elsif !@split_kits && line_props[:children].present?
            line_props[:children].each do |child_sku, child_line_props|
              location_content += child_line_props[:locations].map { |slr| "#{slr} [#{child_sku}]" }.join(', ') + '  '
            end
          end
        end

        location_content += "On hand: #{line_props[:quantity_on_hand]}, Available: #{line_props[:quantity_available]}\n" if show_qty_on_hand

        if show_packaging
          packaging_content = line_props[:packed_shipments].map do |shipment_id, quantity|
            "Pack #{quantity} in Box #{@shipment_ids.index(shipment_id) + 1}."
          end.join(' ')
          location_content += "#{packaging_content}\n"
        end

        location_content
      end,
      style: :regularNimbus
    ), col_span: (if line_props[:third_party_part_number].nil?
                    7
                  else
                    pick ? 6 : 4
                  end) }

    cells << row

    cells << [
      { content: composer.document.layout.text(
        begin
          name_content = "#{line_props[:name]} "
          name_content += '(KIT)' if line_props[:is_kit]
          show_oj_distributor_note = true if line_props[:oj_wifi_notes]
          name_content += '*' if line_props[:oj_wifi_notes]
          name_content
        end,
        style: :regularNimbus
      ), col_span: customize_for_customer && !pick ? 12 : col_span + 7 }
    ]

    next unless line_props[:children].present? && (@split_kits || line_props[:children].values.any? { |child_line_props| child_line_props[:serial_numbers].present? })

    cells << [
      { content: composer.document.layout.text('Kit Contents:', style: { font: FONT, font_size: 10.5, text_align: :left }), col_span: 9 }
    ]

    line_props[:children].each do |child_sku, child_line_props|
      sku_content = composer.document.layout.text(
        show_supplier_skus ? "#{child_line_props[:quantity]} of #{[child_sku, *child_line_props[:supplier_skus]].uniq.join("\n")}" : child_sku,
        style: :regularNimbus
      )

      third_party_content = if child_line_props[:third_party_part_number].nil?
                              nil
                            else
                              {
                                content: composer.document.layout.text(child_line_props[:third_party_part_number].to_s, style: :regularNimbus), col_span: 1
                              }
                            end

      child_text_content = ''
      child_text_content += child_line_props[:locations].map { |location| "#{location}" }.join(', ') + "\n" if show_locations && child_line_props[:locations].present?
      child_line_props[:serial_numbers].each do |sn_hsh|
        child_text_content += "#{sn_hsh[:serial_number]} - #{sn_hsh[:quantity]}\n"
      end
      child_text_content += "On hand: #{child_line_props[:quantity_on_hand]}, Available: #{child_line_props[:quantity_available]}\n" if show_qty_on_hand

      child_name_content = child_line_props[:name]
      child_name_content += ' *' if child_line_props[:oj_wifi_notes]

      cells << [
        { content: '', col_span: 1 },
        { content: sku_content, col_span: 2 },
        third_party_content,
        { content: composer.document.layout.text(child_text_content.strip, style: :regularNimbus), col_span: 3 },
        { content: composer.document.layout.text(child_name_content.strip, style: :regularNimbus), col_span: 3 }
      ].compact
    end
  end

  composer.table(cells, cell_style: { border: { width: 0.3, color: [0.8, 0.8, 0.8] } }, style: { margin: [5, 0, 15, 0] })

  composer.text('* During the WIFI setup of your thermostat, use Distributor ID: 10266', style: { font: "#{FONT} bold", text_align: :left, font_size: 12.5, padding: [0, 0, 10, 0] }) if show_oj_distributor_note && !pick

  composer.box(:barcode, data: { value: @delivery.order.reference_number.to_s, symbology: :code128 },
               width: 100, style: { align: :center, margin: [0, 0, 10, 0] }) if pick

  composer.formatted_text([{ text: 'Returns:', style: { font: "#{FONT} bold", font_size: 12.5 } }, { text: ' All returns must include an RMA # issued by WarmlyYours Customer Service.', style: { font: "#{FONT}", font_size: 12.5 } }]) unless pick

  if @order.is_warehouse_pickup? && check_payments.any?

    composer.text(
      "Customer is paying for this order by check.\n\nRemember to collect check for #{ActionController::Base.helpers.number_to_currency(@order.total)} from customer when they pick up the order.",
      style:
        {
          font: FONT,
          font_size: 12,
          fill_color: 'red'
        }
    )

  elsif @order.is_warehouse_pickup? && cash_payments.any?

    composer.text(
      "Customer is paying for this order with cash.\n\nRemember to collect #{ActionController::Base.helpers.number_to_currency(@order.total)} in cash from customer when they pick up the order.",
      style:
      {
        font: FONT,
        font_size: 12,
        fill_color: 'red'
      }
    )
  end
end

#insert_shipping_info(composer, show_packaging) ⇒ Object



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
# File 'app/services/pdf/document/packing_slip.rb', line 61

def insert_shipping_info(composer, show_packaging)
  show_packaging = show_packaging.to_b
  shipments = Shipment.where(id: @shipment_ids)
  show_packaging = false if shipments.empty?
  po_number = if @order.is_store_transfer?
                @order.purchase_order&.reference_number
              else
                @order.po_number
              end

  attn = @order.ship_to_attributes[:attention_name].presence
  name = @order.ship_to_attributes[:name].to_s.strip
  phone = @order.ship_to_attributes[:phone].to_s.strip

  address_elements = [attn, name, @order.shipping_address.to_array(include_recipient: false, with_country: false, phone: phone)].compact.reject { |n| n == 'Customer' }.uniq.join("\n")
  billing_address_elements = @order.billing_address.to_array(include_recipient: true, with_country: false).join("\n")

  cells = []

  cells << [
    { content: composer.document.layout.text('Order #: ', style: :regularNimbusBold), col_span: 5 },
    { content: composer.document.layout.text(@order.reference_number.to_s, style: :regularNimbus), col_span: 12 },
    { content: composer.document.layout.text('Order Date:', style: :regularNimbusBold), col_span: 6 },
    { content: composer.document.layout.text(@order.created_at.to_fs(:crm_date_only).to_s, style: :regularNimbus), col_span: 20 }
  ]

  cells << [
    { content: composer.document.layout.text('Job Name:', style: :regularNimbusBold), col_span: 5 },
    { content: composer.document.layout.text(truncate_string(@order.try(:job_name).to_s, 27), style: :regularNimbus), col_span: 12 },
    { content: composer.document.layout.text('Pick Date:', style: :regularNimbusBold), col_span: 6 },
    { content: composer.document.layout.text(Time.current.to_fs(:crm_date_only).to_s, style: :regularNimbus), col_span: 20 }
  ]

  cells << [
    { content: composer.document.layout.text('PO #:', style: :regularNimbusBold), col_span: 5 },
    { content: composer.document.layout.text(po_number, style: :regularNimbus), col_span: 12 },
    { content: composer.document.layout.text('Shipping:', style: :regularNimbusBold), col_span: 6 },
    { content: composer.document.layout.text(@order.friendly_shipping_method(true).to_s, style: :regularNimbus), col_span: 20 }
  ]

  cells << [
    { content: composer.document.layout.formatted_text([{ text: @order.is_warehouse_pickup? ? "Pick Up From:\n" : "Ship To:\n", style: :regularNimbusBold }, address_elements], style: { line_height: 15, font: FONT, font_size: 11 }), col_span: 17 },
    { content: composer.document.layout.formatted_text([{ text: "Bill To:\n", style: :regularNimbusBold }, billing_address_elements], style: { line_height: 15, font: FONT, font_size: 11 }), col_span: 26 }
  ]

  if @delivery.shipment_instructions.present? || @delivery.chosen_shipping_method.cod?
    shipping_instructions = [{ text: "Shipping Instructions:\n", style: :regularNimbusBold }]
    if @delivery.chosen_shipping_method.cod?
      shipping_instructions += [
        { text: "COD (#{begin
          @delivery.cod_collection_type.titleize
        rescue StandardError
          'No Check'
        end}) Amount: ", style: :regularNimbusBold },
        { text: ActionController::Base.helpers.number_to_currency(@order.total, unit: @store&.currency_symbol), style: :regularNimbus }
      ]
    end

    shipping_instructions << { text: "\n#{@delivery.shipment_instructions}", style: :regularNimbus }
    cells << [
      { content: composer.document.layout.formatted_text(shipping_instructions), col_span: 20 }
    ]
  end

  if show_packaging && shipments.present?
    aCells = []

    aCells << [
      { content: composer.document.layout.text('Box #', style: :regularNimbusBold) },
      { content: composer.document.layout.text('L (in)', style: :regularNimbusBold) },
      { content: composer.document.layout.text('W (in)', style: :regularNimbusBold) },
      { content: composer.document.layout.text('H (in)', style: :regularNimbusBold) },
      { content: composer.document.layout.text('Wt (lbs)', style: :regularNimbusBold) },
      { content: composer.document.layout.text('SSCC', style: :regularNimbusBold) }
    ]

    shipments.each_with_index do |shipment, _index|
      aCells << [
        { content: composer.document.layout.text((@shipment_ids.index(shipment.id) + 1).to_s, style: :regularNimbus) },
        { content: composer.document.layout.text(shipment.length.to_s, style: :regularNimbus) },
        { content: composer.document.layout.text(shipment.width.to_s, style: :regularNimbus) },
        { content: composer.document.layout.text(shipment.height.to_s, style: :regularNimbus) },
        { content: composer.document.layout.text(shipment.weight.to_s, style: :regularNimbus) },
        { content: composer.document.layout.text(shipment.container_code.to_s, style: :regularNimbus) }
      ]
    end

    composer.table(aCells, cell_style: { border: { width: 0.3, color: [0.8, 0.8, 0.8] } }, style: { margin: [5, 0, 15, 0] })
  end

  insert_warehouse_pickup_info(composer, cells)

  composer.table(cells, cell_style: { border: { width: 0.3, color: [0.8, 0.8, 0.8] } }, style: { margin: [5, 0, 15, 0] })
end

#insert_warehouse_pickup_info(composer, cells) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'app/services/pdf/document/packing_slip.rb', line 156

def insert_warehouse_pickup_info(composer, cells)
  return unless @order.is_warehouse_pickup?

  cells << [
    { content: composer.document.layout.text("I, __________________ (Name), am an authorized representative of __________________ (Company Name) and I have inspected and verified receipt of all items specified in this packing list.
       I authorize WarmlyYours to bill my, or my company's, account for any outstanding charges related to this order.", style: { font: 'Helvetica italic', line_spacing: 1.5 }), col_span: 20 }
  ]
  cells << [
    { content: composer.document.layout.text('Signature:', style: { font: "#{FONT} bold" }), col_span: 3 },
    { content: composer.document.layout.text(''), col_span: 17 }
  ]
  cells << [
    { content: composer.document.layout.text('Date and Time:', style: { font: "#{FONT} bold" }), col_span: 3 },
    { content: composer.document.layout.text(''), col_span: 17 }
  ]
end

#truncate_string(text, length) ⇒ Object



438
439
440
# File 'app/services/pdf/document/packing_slip.rb', line 438

def truncate_string(text, length)
  text.length > length ? "#{text.slice(0, length)}..." : text
end

#write_temp_file(content) ⇒ Object



430
431
432
433
434
435
436
# File 'app/services/pdf/document/packing_slip.rb', line 430

def write_temp_file(content)
  tempfile = Tempfile.new(['pdf', '.pdf'])
  tempfile.binmode
  tempfile.write(content)
  tempfile.rewind
  tempfile.path
end