Rebuild the Checkout class, no discounts yet

Checkout now stores its items using a quantity and a link back to the
original product instance. It has a reference to the store to make sure
that product IDs added are valid
This commit is contained in:
David Underwood
2026-07-21 10:27:33 -04:00
parent e570783935
commit 882c18b5e6
4 changed files with 91 additions and 58 deletions
+19 -38
View File
@@ -1,62 +1,43 @@
require 'product_in_checkout.rb'
class Checkout
class InvalidItem < StandardError; end
AVAILABLE_ITEMS = {
PI5: 60.00,
ZERO2W: 15.00,
PICO2: 4.00
}
def initialize
def initialize(shop:)
@shop = shop
@items = []
end
def add(item)
raise InvalidItem unless valid_item?(item)
@items.push item
end
def add(product_id:, quantity: 1)
product = @shop.product_by_id(product_id)
def remove(item)
if index = @items.index(item)
@items.delete_at(index)
end
raise InvalidItem unless product
@items
product_in_checkout = new_or_existing_product_in_checkout(product)
product_in_checkout.add_quantity(quantity)
@items.push product_in_checkout
end
def items
@items
end
def total
pre_discount_total - current_discount
def item_quantities
@items.map { |item| [item.product_id, item.quantity] }.to_h
end
def clear
@items = []
end
def total
@items.reduce(0.00) { |running_total, item| running_total + item.total }
end
private
def valid_item?(item)
return AVAILABLE_ITEMS.keys.include?(item)
end
def current_discount
# BOGOF ZERO2W
discount = (@items.count(:ZERO2W) / 2.0).floor * AVAILABLE_ITEMS[:ZERO2W]
# Bulk PICO2
if(items.count(:PICO2) >= 3)
discount += items.count(:PICO2) * 0.50
end
return discount
end
def pre_discount_total
@items.reduce(0.00) do |running_total, item|
running_total + AVAILABLE_ITEMS[item]
end
def new_or_existing_product_in_checkout(product)
@items.find { |item| item.product_id == product.id } || ProductInCheckout.new(product: product)
end
end