Class: Spree::Address

Inherits:
Object
  • Object
show all
Includes:
HasCustomFields, Metadata, Security::Addresses
Defined in:
app/models/spree/address.rb

Constant Summary collapse

STATES_REQUIRED =

The required states listed below match those used by PayPal and Shopify.

[
  'AU', 'AE', 'BR', 'CA', 'CN', 'ES', 'HK', 'IE', 'IN',
  'IT', 'MY', 'MX', 'NZ', 'PT', 'RO', 'TH', 'US', 'ZA'
].freeze
ADDRESS_FIELDS =

we're not freezing this on purpose so developers can extend and manage those attributes depending of the logic of their applications

%w(first_name last_name company address1 address2 city state postal_code country phone)
DESTINATION_FIELDS =

The columns a delivery quote reads. A change to anything else (a phone number, the recipient's name) leaves the parcel going where it was.

%w(address1 address2 city state_code postal_code country_code).freeze
EXCLUDED_KEYS_FOR_COMPARISON =

Beyond identity and ownership, three groups are excluded because they cannot tell two addresses apart. Latitude and longitude are derived from the address, so an entry whose geocoding has already run would otherwise never match the same address freshly typed in. country_id and state_id are the pre-6.0 foreign keys, which the upgrade task copies into codes and leaves populated: comparing them makes every migrated row differ from every new one. Both are handled the same way by .find_duplicate, which drops the legacy keys through .resolve_geo_params.

%w(
  id updated_at created_at deleted_at label owner_type owner_id metadata
  latitude longitude country_id state_id
)

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Metadata

#private_metadata, #private_metadata=

Class Method Details

.find_duplicate(attributes) ⇒ Spree::Address?

Finds an existing, undeleted address matching the given attributes, so a customer re-entering an address they already have reuses that row rather than accumulating duplicates. Geography is matched by code, and a state given by name is resolved to the codes it could mean.

Parameters:

  • attributes (Hash)

Returns:



202
203
204
205
206
207
208
209
# File 'app/models/spree/address.rb', line 202

def self.find_duplicate(attributes)
  attributes = resolve_geo_params(attributes.except(:id, :updated_at, :created_at))
  state_name = attributes[:state_name]

  scope = not_deleted.where(attributes.except(:state_name))
  scope = scope.by_state_name_or_abbr(state_name) if state_name.present?
  scope.first
end

.normalize_postal_code(value) ⇒ String

The single home for postal-code normalization (delivery-zone matching) — don't scatter postal-code munging elsewhere.

Parameters:

  • value (String, nil)

Returns:

  • (String) —

    value with spaces/dashes stripped, upcased



132
133
134
# File 'app/models/spree/address.rb', line 132

def self.normalize_postal_code(value)
  value.to_s.gsub(/[\s-]/, '').upcase
end

.normalize_zipcode(value) ⇒ Object

Deprecated.

Use normalize_postal_code; removed in 6.3.



137
138
139
140
# File 'app/models/spree/address.rb', line 137

def self.normalize_zipcode(value)
  Spree::Deprecation.warn('Spree::Address.normalize_zipcode is deprecated and will be removed in Spree 6.3. Use .normalize_postal_code instead.')
  normalize_postal_code(value)
end

.required_fields ⇒ Object



214
215
216
217
218
# File 'app/models/spree/address.rb', line 214

def self.required_fields
  Spree::Address.validators.map do |v|
    v.is_a?(ActiveModel::Validations::PresenceValidator) ? v.attributes : []
  end.flatten
end

.resolve_geo_params(params) ⇒ Hash

Normalizes a params hash for query builders like find_or_create_by, which match on exactly the keys they are given. Codes are upcased so a lookup finds the row a save would have written, the redundant foreign keys are dropped, and a state_name that names a real subdivision becomes the code that a saved address would hold.

Assignment does not need this — the writers and their before_validation callbacks resolve both halves.

Parameters:

  • params (Hash)

Returns:

  • (Hash)


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
# File 'app/models/spree/address.rb', line 166

def self.resolve_geo_params(params)
  params = params.to_h.symbolize_keys
  params.delete(:country_id)
  params.delete(:state_id)

  # Legacy write names accepted until 6.5; the columns are country_code
  # and state_code. The renamed name and postal-code columns need no entry
  # here — alias_attribute resolves those inside `where` too, while these
  # two are not attribute aliases.
  params[:state_code] = params.delete(:state_abbr) if params.key?(:state_abbr)
  params[:country_code] = params.delete(:country_iso) if params.key?(:country_iso)

  country_code = params[:country_code].presence&.to_s&.upcase
  params[:country_code] = country_code if country_code

  if params[:state_code].present?
    params[:state_code] = params[:state_code].to_s.upcase
  elsif country_code && params[:state_name].present?
    matched = Spree::IsoData.subdivision_code(country_code, params[:state_name])

    if matched
      params[:state_code] = matched
      params.delete(:state_name)
    end
  end

  params
end

Instance Method Details

#==(other) ⇒ Object



397
398
399
400
401
# File 'app/models/spree/address.rb', line 397

def ==(other)
  return false unless other&.respond_to?(:value_attributes)

  value_attributes == other.value_attributes
end

#address_validators ⇒ Object



114
115
116
117
118
# File 'app/models/spree/address.rb', line 114

def address_validators
  Spree.validators.addresses.each do |validator|
    validates_with validator
  end
end

#async_geocode ⇒ Object



502
503
504
# File 'app/models/spree/address.rb', line 502

def async_geocode
  Spree::Addresses::GeocodeAddressJob.perform_later(id) if should_geocode?
end

#business_owned? ⇒ Boolean

A company node's or a seller's address: nobody is named on it, and the business is the part that cannot be left out.

Returns:

  • (Boolean)


276
277
278
# File 'app/models/spree/address.rb', line 276

def business_owned?
  owner_type == 'Spree::Company' || owner_type == 'Spree::Seller'
end

#can_be_deleted? ⇒ Boolean

Returns:

  • (Boolean)


487
488
489
# File 'app/models/spree/address.rb', line 487

def can_be_deleted?
  shipments.empty? && Order.complete.where('bill_address_id = ? OR ship_address_id = ?', id, id).none?
end

#clone ⇒ Object

Deprecated.

Overriding Ruby's Object#clone was a mistake: this returns a value copy with the owner, label and metadata stripped, which is not what clone means anywhere else in Ruby. The override is removed in Spree 6.3 and clone becomes the standard shallow copy. Use #snapshot for the ownerless copy a purchase keeps.



341
342
343
344
345
346
347
348
# File 'app/models/spree/address.rb', line 341

def clone
  Spree::Deprecation.warn(
    'Spree::Address#clone is deprecated. From Spree 6.3 it behaves as the standard Ruby Object#clone — ' \
    'a shallow copy keeping the owner and every other attribute. Use #snapshot for the ownerless copy a purchase keeps.'
  )

  self.class.new(value_attributes)
end

#company ⇒ String?

The company line. A stored value wins, so an order's copied address keeps what it was sent with even after the node is renamed, and a member can override the line for one site. An owned book entry with nothing stored tracks its node's current name.

Returns:

  • (String, nil)


286
287
288
289
290
291
# File 'app/models/spree/address.rb', line 286

def company
  stored = super
  return stored if stored.present?

  owner&.name if owner_type == 'Spree::Company'
end

#customer_owned? ⇒ Boolean

Returns:

  • (Boolean)


230
231
232
# File 'app/models/spree/address.rb', line 230

def customer_owned?
  owner_type == Spree.customer_class.to_s
end

#customer_owner ⇒ Object?

The owner when it is a customer, so customer-specific behaviour (the address book defaults, the profile back-fill) reads nil for a company's or a seller's row and simply does not apply.

Returns:

  • (Object, nil)


225
226
227
# File 'app/models/spree/address.rb', line 225

def customer_owner
  owner if customer_owned?
end

#default_address_id(kind) ⇒ Integer?

Returns the owner's chosen address of that kind.

Parameters:

  • kind (Symbol) —

    :bill or :ship

Returns:

  • (Integer, nil) —

    the owner's chosen address of that kind



236
237
238
239
240
# File 'app/models/spree/address.rb', line 236

def default_address_id(kind)
  return nil unless owner.respond_to?(:default_address_id)

  owner.default_address_id(kind)
end

#destroy ⇒ Object



491
492
493
494
495
496
497
498
499
500
# File 'app/models/spree/address.rb', line 491

def destroy
  assign_new_default_address_to_user

  if can_be_deleted?
    unassign_from_incomplete_orders
    super
  else
    update_column :deleted_at, Time.current
  end
end

#duplicate_in_address_book ⇒ Spree::Address?

The entry the owner's book already holds for this, if there is one, so someone re-entering an address they already saved gets the entry they have back instead of a near-copy filed beside it.

An entry is more than a place. Two rows match only when they mean the same place (#==) and agree on the things the owner attached to the entry itself — its label and its metadata. A company filing "Dock A" and "Dock B" at one site keeps two entries, and neither request silently loses the name it was filed under.

Owners that keep no book, including no owner at all, have nothing to match against.

Returns:



386
387
388
389
390
391
392
393
394
395
# File 'app/models/spree/address.rb', line 386

def duplicate_in_address_book
  return nil unless owner.respond_to?(:addresses)

  owner.addresses.not_deleted.detect do |existing|
    existing.id != id &&
      existing == self &&
      existing.label == label &&
      existing..to_h == .to_h
  end
end

#editable? ⇒ Boolean

Returns:

  • (Boolean)


483
484
485
# File 'app/models/spree/address.rb', line 483

def editable?
  new_record? || Order.complete.where('bill_address_id = ? OR ship_address_id = ?', id, id).none?
end

#empty? ⇒ Boolean

A country alone doesn't make an address — a new one is pre-filled with the store's default, so both the code and the association are ignored here.

Returns:

  • (Boolean)


415
416
417
# File 'app/models/spree/address.rb', line 415

def empty?
  attributes.except('id', 'created_at', 'updated_at', 'country_id', 'country_code').all? { |_, v| v.nil? }
end

#full_name ⇒ Object

first_name / last_name aliases are defined via alias_attribute above



309
310
311
# File 'app/models/spree/address.rb', line 309

def full_name
  "#{first_name} #{last_name}".strip
end

#gateway_hash ⇒ Object Also known as: active_merchant_hash

Generates an address hash for payment gateway options



420
421
422
423
424
425
426
427
428
429
430
431
# File 'app/models/spree/address.rb', line 420

def gateway_hash
  {
    name: full_name,
    address1: address1,
    address2: address2,
    city: city,
    state: state_text,
    zip: postal_code,
    country: country.try(:iso),
    phone: phone
  }
end

#geocoder_address ⇒ Object



506
507
508
# File 'app/models/spree/address.rb', line 506

def geocoder_address
  @geocoder_address ||= [street, city, state_text, country.to_s].compact.map(&:strip).join(', ')
end

#is_default_billing? ⇒ Boolean Also known as: is_default_billing

Whether the owner prefills with this address. Every owner keeps the pointer itself — a customer on bill_address_id / ship_address_id, a company node on its own two columns — so the answer is the same question asked of whichever one owns the row.

Returns:

  • (Boolean)


297
298
299
# File 'app/models/spree/address.rb', line 297

def is_default_billing?
  default_address_id(:bill) == id
end

#is_default_shipping? ⇒ Boolean Also known as: is_default_shipping

Returns:

  • (Boolean)


302
303
304
# File 'app/models/spree/address.rb', line 302

def is_default_shipping?
  default_address_id(:ship) == id
end

#normalized_postal_code ⇒ String

Returns this address's postal code, normalized via normalize_postal_code.

Returns:



143
144
145
# File 'app/models/spree/address.rb', line 143

def normalized_postal_code
  self.class.normalize_postal_code(postal_code)
end

#normalized_zipcode ⇒ Object

Deprecated.

Use #normalized_postal_code; removed in 6.3.



148
149
150
151
152
153
# File 'app/models/spree/address.rb', line 148

def normalized_zipcode
  Spree::Deprecation.warn(
    'Spree::Address#normalized_zipcode is deprecated and will be removed in Spree 6.3. Use #normalized_postal_code instead.'
  )
  normalized_postal_code
end

#require_company? ⇒ Boolean

Returns:

  • (Boolean)


461
462
463
464
465
466
467
468
469
470
471
# File 'app/models/spree/address.rb', line 461

def require_company?
  return false if quick_checkout
  # A company node names itself, so the line is always answerable; a
  # seller's billing address is what a commission invoice is addressed to,
  # and that is the part which cannot be left out.
  return true if business_owned?

  # Only meaningful when the field is on the form at all — requiring a
  # value the customer is never shown would make checkout unfinishable.
  show_company_address_field? && store_preference(:address_requires_company, false)
end

#require_name? ⇒ Boolean

A business address names no person: a company site or a seller's billing address has no contact to insist on, which is why the owner decides this rather than a subclass.

Returns:

  • (Boolean)


457
458
459
# File 'app/models/spree/address.rb', line 457

def require_name?
  !quick_checkout && !business_owned?
end

#require_phone? ⇒ Boolean

Returns:

  • (Boolean)


434
435
436
437
438
# File 'app/models/spree/address.rb', line 434

def require_phone?
  # We want to collect phone number for quick checkout but not to validate it
  # as it's not available before payment by browser.
  !quick_checkout && store_preference(:address_requires_phone, false)
end

#require_postal_code? ⇒ Boolean

A host app that overrode the pre-6.0 require_zipcode? still decides: its override sits ahead of this class in the ancestry, so the shell below never runs and the answer comes from the decorator. Without the indirection that override would stop being called silently, and addresses that used to save would start failing validation with nothing in the log.

Returns:

  • (Boolean)


445
446
447
# File 'app/models/spree/address.rb', line 445

def require_postal_code?
  require_zipcode?
end

#require_street? ⇒ Boolean

Returns:

  • (Boolean)


473
474
475
# File 'app/models/spree/address.rb', line 473

def require_street?
  !quick_checkout
end

#require_zipcode? ⇒ Boolean

Deprecated.

Override #require_postal_code?; removed in 6.3.

Returns:

  • (Boolean)


450
451
452
# File 'app/models/spree/address.rb', line 450

def require_zipcode?
  !quick_checkout && (country ? country.zipcode_required? : true)
end

#saved_change_to_destination? ⇒ Boolean

Returns whether the last save moved this address somewhere else, as opposed to correcting who receives the parcel.

Returns:

  • (Boolean) —

    whether the last save moved this address somewhere else, as opposed to correcting who receives the parcel



409
410
411
# File 'app/models/spree/address.rb', line 409

def saved_change_to_destination?
  saved_changes.keys.intersect?(DESTINATION_FIELDS)
end

#show_company_address_field? ⇒ Boolean

Returns:

  • (Boolean)


477
478
479
480
481
# File 'app/models/spree/address.rb', line 477

def show_company_address_field?
  return true if business_owned?

  store_preference(:company_field_enabled, false)
end

#snapshot ⇒ Spree::Address

A copy of this address for a purchase to keep. An order's address records where the parcel actually went, so it belongs to the order and not to anyone's address book — a copy that kept the owner would file a second entry in the buyer's book on every order they place. Having no owner it carries no label either: a label is unique within one book, so every ownerless snapshot would compete for the same one.

Returns:



358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'app/models/spree/address.rb', line 358

def snapshot
  dup.tap do |copy|
    copy.owner = nil

    if business_owned?
      copy.company = company.presence || owner&.name
      copy.owner_type = owner_type
    end

    copy.label = nil
    copy.deleted_at = nil
  end
end

#state_name_text ⇒ Object



317
318
319
# File 'app/models/spree/address.rb', line 317

def state_name_text
  state_name.present? ? state_name : state&.name
end

#state_text ⇒ Object



313
314
315
# File 'app/models/spree/address.rb', line 313

def state_text
  state_code.presence || state.try(:name) || state_name
end

#street ⇒ Object



321
322
323
# File 'app/models/spree/address.rb', line 321

def street
  [address1, address2].join(' ')
end

#to_s ⇒ Object



325
326
327
328
329
330
331
332
333
334
# File 'app/models/spree/address.rb', line 325

def to_s
  [
    full_name,
    company,
    address1,
    address2,
    "#{city}, #{state_text} #{postal_code}",
    country.to_s
  ].reject(&:blank?).map { |attribute| ERB::Util.html_escape(attribute) }.join('<br/>')
end

#user ⇒ Object

Deprecated.

The address's owner may be a customer, a company node or a seller, so #owner replaces the customer-only association. Removed in Spree 6.3.



245
246
247
248
249
250
251
252
# File 'app/models/spree/address.rb', line 245

def user
  if defined?(Spree::Deprecation)
    Spree::Deprecation.warn(
      'Spree::Address#user is deprecated and will be removed in Spree 6.3. Use #owner instead.'
    )
  end
  customer_owner
end

#user=(value) ⇒ Object



254
255
256
257
258
259
260
261
# File 'app/models/spree/address.rb', line 254

def user=(value)
  if defined?(Spree::Deprecation)
    Spree::Deprecation.warn(
      'Spree::Address#user= is deprecated and will be removed in Spree 6.3. Use #owner= instead.'
    )
  end
  self.owner = value
end

#user_id ⇒ Object



263
264
265
266
267
268
269
270
# File 'app/models/spree/address.rb', line 263

def user_id
  if defined?(Spree::Deprecation)
    Spree::Deprecation.warn(
      'Spree::Address#user_id is deprecated and will be removed in Spree 6.3. Use #owner_id instead.'
    )
  end
  owner_id if customer_owned?
end

#value_attributes ⇒ Object



403
404
405
# File 'app/models/spree/address.rb', line 403

def value_attributes
  attributes.except(*EXCLUDED_KEYS_FOR_COMPARISON)
end