Class: Spree::NumberGenerators::Sequential

Inherits:
Base
  • Object
show all
Defined in:
app/models/spree/number_generators/sequential.rb

Overview

The 6.0 default: prefix + a counter that advances by one per document, producing the invoice-like numbers merchants expect (R1001, R1002).

The counter lives in Spree::NumberSequence rather than being derived from the number column, because the column cannot answer "what comes next": upgraded stores are full of 5.x random values that poison any MAX-and-parse, string columns sort R999 above R1000, concurrent writers computing MAX+1 collide by construction, and a merchant-chosen starting value is not a fact about any existing row.

Numbering is mostly-gapless, never guaranteed gapless — a collision or a rolled-back transaction consumes a value. Never present this as legal invoice numbering.

Constant Summary collapse

SCAN_BATCH_SIZE =

Candidate values checked per query when jumping a stretch of numbers another store already owns.

100

Instance Method Summary collapse

Instance Method Details

#generate(record) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/models/spree/number_generators/sequential.rb', line 21

def generate(record)
  store = record.number_store
  raise_missing_store(record) if store.nil?

  resource_type = record.number_key.to_s
  value = Spree::NumberSequence.next_value(
    store: store,
    resource_type: resource_type,
    start_at: start_at_for(record)
  )

  candidate = compose(record, value)
  return candidate unless taken?(record, candidate)

  # The unique index is global, so a sibling store with the same format
  # can own a whole stretch of numbers — and stepping through it one
  # save attempt at a time would exhaust the concern's retry budget and
  # fail the save. Find the first free value in batches and jump the
  # counter past the stretch in one move instead.
  free_value = next_free_value(record, value)
  Spree::NumberSequence.advance_to(store: store, resource_type: resource_type, value: free_value)

  compose(record, free_value)
end