Module: Spree::HasExternalReferences

Extended by:
ActiveSupport::Concern
Included in:
Category, Company, Fulfillment, LineItem, Media, Order, Product, Return, Seller, StockLevel, StockLocation, Variant
Defined in:
app/models/concerns/spree/has_external_references.rb

Overview

Gives a model identities in external systems (ERP, PIM, DAM, CRM) through ExternalReference. Opt-in per resource rather than on Base: only records a connector actually syncs need the association.

Instance Method Summary collapse

Instance Method Details

#assign_external_references(references) ⇒ void

This method returns an undefined value.

Writes several references at once, leaving systems the payload does not mention untouched — a connector states its own key without disturbing another system's. Accepts the { system => external_id } map the admin serializers render, or a list of { system:, external_id: } entries.

Parameters:

  • references (Hash{String,Symbol=>String}, Array<Hash>)


56
57
58
59
60
61
62
63
64
65
66
# File 'app/models/concerns/spree/has_external_references.rb', line 56

def assign_external_references(references)
  entries = Spree::ExternalReference.normalize_references(references)
  return if entries.empty?

  keys = entries.map { |entry| Spree::ExternalReference.normalize_system(entry[:system]) }
  existing = external_references.where(system: keys).order(:id).group_by(&:system).transform_values(&:first)

  entries.zip(keys).each do |entry, key|
    existing[key] = write_external_reference(key, existing[key], entry[:external_id], entry[:metadata])
  end
end

#external_id_for(system) ⇒ String?

Returns the identifier that system knows this record by.

Parameters:

  • system (String, Symbol) —

    the external system's key

Returns:

  • (String, nil) —

    the identifier that system knows this record by



28
29
30
31
32
33
34
35
36
# File 'app/models/concerns/spree/has_external_references.rb', line 28

def external_id_for(system)
  key = Spree::ExternalReference.normalize_system(system)

  if external_references.loaded?
    external_references.detect { |reference| reference.system == key }&.external_id
  else
    external_references.for_system(key).pick(:external_id)
  end
end

#set_external_id(system, external_id, metadata: nil) ⇒ Spree::ExternalReference?

Creates or updates this record's identity in one external system.

Parameters:

  • system (String, Symbol) —

    the external system's key

  • external_id (String, nil) —

    blank removes the reference

  • metadata (Hash, nil) (defaults to: nil) —

    connector bookkeeping (version, etag, synced at)

Returns:



44
45
46
47
# File 'app/models/concerns/spree/has_external_references.rb', line 44

def set_external_id(system, external_id, metadata: nil)
  key = Spree::ExternalReference.normalize_system(system)
  write_external_reference(key, external_references.for_system(key).first, external_id, )
end