class Effective::Order
def add(*items, quantity: 1)
add(Product.first) => returns an Effective::OrderItem
Items can be an Effective::Cart, an Effective::order, a single acts_as_purchasable, or multiple acts_as_purchasables
def add(*items, quantity: 1) raise 'unable to alter a purchased order' if purchased? raise 'unable to alter a declined order' if declined? cart_items = items.flatten.flat_map do |item| if item.kind_of?(Effective::Cart) item.cart_items.to_a elsif item.kind_of?(ActsAsPurchasable) Effective::CartItem.new(quantity: quantity, purchasable: item) elsif item.kind_of?(Effective::Order) # Duplicate an existing order self.note_to_buyer ||= item.note_to_buyer self.note_internal ||= item.note_internal self.cc ||= item.cc item.order_items.select { |oi| oi.purchasable.kind_of?(Effective::Product) }.map do |oi| purchasable = oi.purchasable product = Effective::Product.new(name: purchasable.purchasable_name, price: purchasable.price, tax_exempt: purchasable.tax_exempt) # Copy over any extended attributes that may have been created atts = purchasable.dup.attributes.except('name', 'price', 'tax_exempt', 'purchased_order_id').compact atts.each do |k, v| next unless product.respond_to?("#{k}=") && product.respond_to?(k) product.send("#{k}=", v) if product.send(k).blank? end Effective::CartItem.new(quantity: oi.quantity, purchasable: product) end else raise 'add() expects one or more acts_as_purchasable objects, or an Effective::Cart' end end.compact # Make sure to reset stored aggregates assign_attributes(subtotal: nil, tax_rate: nil, tax: nil, amount_owing: nil, surcharge_percent: nil, surcharge: nil, total: nil) retval = cart_items.map do |item| order_items.build( name: item.name, quantity: item.quantity, price: item.price, tax_exempt: (item.tax_exempt || false), ).tap { |order_item| order_item.purchasable = item.purchasable } end retval.size == 1 ? retval.first : retval end