summaryrefslogtreecommitdiff
path: root/app/services/solidus_subscriptions/line_item_builder.rb
diff options
context:
space:
mode:
authorAlessandro Desantis <desa.alessandro@gmail.com>2020-06-16 16:16:28 +0200
committerAlessandro Desantis <desa.alessandro@gmail.com>2020-06-16 16:16:28 +0200
commit7e08bee50ae1db39ba2f55b36941edc375cc0a56 (patch)
treeb54fb332ed66a3b7a6e87e2b63cba81835623175 /app/services/solidus_subscriptions/line_item_builder.rb
parent2bfffee038c57c5f6f1d03aad434ae9b861bde60 (diff)
Move service objects to `app/services`
Diffstat (limited to 'app/services/solidus_subscriptions/line_item_builder.rb')
-rw-r--r--app/services/solidus_subscriptions/line_item_builder.rb44
1 files changed, 44 insertions, 0 deletions
diff --git a/app/services/solidus_subscriptions/line_item_builder.rb b/app/services/solidus_subscriptions/line_item_builder.rb
new file mode 100644
index 0000000..b288629
--- /dev/null
+++ b/app/services/solidus_subscriptions/line_item_builder.rb
@@ -0,0 +1,44 @@
+# This class is responsible for taking SubscriptionLineItems and building
+# them into Spree::LineItems which can be added to an order
+module SolidusSubscriptions
+ class LineItemBuilder
+ attr_reader :subscription_line_items
+
+ # Get a new instance of a LineItemBuilder
+ #
+ # @param subscription_line_items[Array<SolidusSubscriptions::LineItem>] The
+ # subscription line item to be converted into a Spree::LineItem
+ #
+ # @return [SolidusSubscriptions::LineItemBuilder]
+ def initialize(subscription_line_items)
+ @subscription_line_items = subscription_line_items
+ end
+
+ # Get a new (unpersisted) Spree::LineItem which matches the details of
+ # :subscription_line_item
+ #
+ # @return [Array<Spree::LineItem>]
+ def spree_line_items
+ line_items = subscription_line_items.map do |subscription_line_item|
+ variant = subscribables.fetch(subscription_line_item.subscribable_id)
+
+ raise UnsubscribableError.new(variant) unless variant.subscribable?
+ next unless variant.can_supply?(subscription_line_item.quantity)
+
+ ::Spree::LineItem.new(variant: variant, quantity: subscription_line_item.quantity)
+ end
+
+ # Either all line items for an installment are fulfilled or none are
+ line_items.all? ? line_items : []
+ end
+
+ private
+
+ def subscribables
+ return @subscribables if @subscribables
+
+ ids = subscription_line_items.map(&:subscribable_id)
+ @subscribables ||= ::Spree::Variant.find(ids).index_by(&:id)
+ end
+ end
+end