Class: Spree::NumberSequence

Inherits:
Object
  • Object
show all
Defined in:
app/models/spree/number_sequence.rb

Overview

Per-store, per-resource counter behind sequential document numbering (docs/plans/6.0-document-numbers.md). One row per numbered resource type a store actually uses; nothing outside Spree::NumberGenerators::Sequential reads them.

This exists because the number column cannot say what comes next — see the generator for why deriving it from data is not an option. Postgres has native sequences, MySQL and SQLite do not, so a locked counter row is the portable equivalent.

Constant Summary collapse

DEFAULT_START =
1001

Class Method Summary collapse

Class Method Details

.advance_to(store:, resource_type:, value:) ⇒ Object

Moves the counter forward to value — never backward — so numbering continues past a stretch of numbers that turned out to be taken.

Parameters:

  • store (Spree::Store)
  • resource_type (String)
  • value (Integer) —

    the value the counter should stand at



49
50
51
52
53
54
55
# File 'app/models/spree/number_sequence.rb', line 49

def advance_to(store:, resource_type:, value:)
  sequence = find_or_create_sequence(store, resource_type, value)

  sequence.with_lock do
    sequence.update!(value: value) if sequence.value < value
  end
end

.next_value(store:, resource_type:, start_at: DEFAULT_START) ⇒ Object



57
58
59
60
61
62
63
64
# File 'app/models/spree/number_sequence.rb', line 57

def next_value(store:, resource_type:, start_at: DEFAULT_START)
  sequence = find_or_create_sequence(store, resource_type, start_at)

  sequence.with_lock do
    sequence.increment!(:value)
    sequence.value
  end
end

.started?(store:, resource_type: 'order') ⇒ Integer, Boolean

Advances the counter and returns the value to use. The row is locked for the increment, so concurrent checkouts hand out distinct numbers instead of racing on the same one.

Whether a counter has already handed out a number, which is what makes the store's starting-value setting inert from then on. The dashboard reads this to say so rather than letting a merchant set a value that silently does nothing.

Parameters:

  • store (Spree::Store)
  • resource_type (String) (defaults to: 'order') —

    e.g. 'order'

  • start_at (Integer) —

    first value handed out for a fresh counter

  • store (Spree::Store)
  • resource_type (String) (defaults to: 'order')

Returns:

  • (Integer)
  • (Boolean)


37
38
39
40
41
# File 'app/models/spree/number_sequence.rb', line 37

def started?(store:, resource_type: 'order')
  return false if store.nil?

  exists?(store: store, resource_type: resource_type)
end