Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When you came to get the license key at the same time, users do not get #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions app/models/spree/license_key.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ class LicenseKey < ActiveRecord::Base
scope :available, where(inventory_unit_id: nil)
scope :used, where('inventory_unit_id IS NOT NULL')

def self.assign_license_keys!(inventory_unit)
# Max count of repeat to assign license key when could not assign.
REPEAT_COUNT_LIMIT = 3

def self.assign_license_keys!(inventory_unit, repeat_count=0)
transaction do
if inventory_unit.variant.license_key_types.empty?
[self.get_available_key(inventory_unit)]
Expand All @@ -19,19 +22,27 @@ def self.assign_license_keys!(inventory_unit)
end
end
end
rescue UnAssignLicenseKeys
if repeat_count == REPEAT_COUNT_LIMIT
raise LicenseKey::UnAssignLicenseKeys, "Order: #{inventory_unit.order.to_param}, Variant: #{inventory_unit.variant.to_param}"
end
# In order to avoid a collision, and repeat in a few seconds
sleep(repeat_count+1)
self.assign_license_keys!(inventory_unit, repeat_count+1)
end

class InsufficientLicenseKeys < ::StandardError; end
class UnAssignLicenseKeys < ::StandardError; end

private

def self.get_available_key(inventory_unit, license_key_type = nil)
license_key = self.where(:variant_id => inventory_unit.variant.id, :inventory_unit_id => nil, :license_key_type_id => license_key_type.try(:id)).first
if license_key.nil?
raise LicenseKey::InsufficientLicenseKeys, "Variant: #{inventory_unit.variant.to_param}, License Key Type: #{license_key_type.try(:id)}"
raise LicenseKey::InsufficientLicenseKeys, "Order: #{inventory_unit.order.to_param}, Variant: #{inventory_unit.variant.to_param}, License Key Type: #{license_key_type.try(:id)}"
end
license_key.inventory_unit = inventory_unit
license_key.save!
updated_count = LicenseKey.where(id: license_key.id, inventory_unit_id: nil).update_all(inventory_unit_id: inventory_unit.id, updated_at: Time.now)
raise UnAssignLicenseKeys if updated_count == 0
license_key
end
end
Expand Down