#!/usr/bin/env ruby module Drugstore::Controllers class Index < R '/' def get @cart = 0 unless @state.cart.blank? @state.cart.each do |product_id, quantity| @cart = @cart + quantity.to_i end end @products = Product.all render :index end def post if( ( @input.has_key?( "product_id" ) ) && ( @input.has_key?( "quantity" ) ) ) @state.cart ||= {} if @state.cart.has_key?( @input.product_id ) @state.cart[ @input.product_id.to_i ] = @state.cart[ @input.product_id.to_i ].to_i + @input.quantity.to_i else @state.cart[ @input.product_id.to_i ] = @input.quantity.to_i end @state.cart[ @input.product_id.to_i ] = 10 if @state.cart[ @input.product_id.to_i ] > 10 @state.info = ' <= Product successfully added.' end redirect Index end end class Cart < R '/cart' def get unless @state.cart.blank? @products = [] @sum = 0 @state.cart.each do |product_id, quantity| product = Product.find_by_id( product_id ) subtotal = ( product.price * quantity.to_f ).round(6) line = { "quantity" => quantity, "title" => product.title, "price" => product.price, "subtotal" => subtotal, "id" => product_id } @products << line @sum = ( @sum + subtotal ).round(6) end render :card else redirect Index end end def post if @input.has_key?( "cleanup" ) if @input.cleanup == "all" @state.cart = nil redirect Index elsif @input.cleanup =~ /\A\d+\Z/ @state.cart = @state.cart.select{ |x| x != @input.cleanup.to_i } redirect Cart end end end end class Checkout < R '/checkout' def get unless @state.cart.blank? render :checkout else redirect Index end end def post order = Order.create( :fullname => @input.fullname, :addrline1 => @input.addrline1, :zippostalcode => @input.zippostalcode, :city => @input.city, :country => @input.country, :cart => @state.cart.to_s, :bitcoinaddress => "15zveKrrJWbp3BVpv36VWr1kPq3opNK6xf", :addrline2 => @input.addrline2, :stateprovinceregion => @input.stateprovinceregion, :email => @input.email, :orderdate => Time.now.strftime( "%Y-%m-%dT%H:%M:%S" ) ) if order.errors.any? @error = 'ERROR: Creation of order failed! Please check the form and try again.' render :checkout, @input else @state.order = "done" # We skip autocreation of bitcoin addresses here! redirect Bitcoin end end end class Bitcoin < R '/bitcoin' def get unless @state.cart.blank? if @state.has_key?( "order" ) if @state.order == "done" @state.order = nil @state.cart = nil render :bitcoin end else redirect Checkout end else redirect Index end end end end