コード例 #1
0
 public function redeem($cart)
 {
     // Check the discount is valid
     if (!$this->is_valid()) {
         throw new Error500('Discount is not valid');
     }
     // Check the cart hasn't been fully discounted already
     if ($cart->has_exclusive_discount()) {
         throw new Error500('This cart cannot have any more discounts');
     }
     if ($this->exclusive && count($cart->discounts()) > 0) {
         throw new Error500('You cannot add this discount while there are other discounts');
     }
     // Grab all cart items referenced by a discount
     $id = mysql_real_escape_string($cart->id);
     $discounts = DiscountRedemption::find_all("carts.id = '{$id}'");
     foreach ($discounts as $discount) {
         if ($discount->discount->id == $this->id) {
             throw new Error500('That discount has already been added');
         }
     }
     if ($this->loyalty) {
         $user_id = mysql_real_escape_string($cart->user_id);
         $id = mysql_real_escape_string($this->id);
         $ld = LoyaltyDiscount::find("users.id = '{$user_id}' AND discount_codes.id = '{$id}'");
         if (!$ld) {
             throw new Error500('You are not allowed to use this discount');
         }
     }
     // If this is a full cart discount, apply it
     if ($this->full_cart_discount) {
         $this->add_for_cart($cart);
         return true;
     }
     // Let's get some sorted discount items
     $services = array();
     foreach ($this->services() as $item) {
         $services[] = $item->item->id;
     }
     $tickets = array();
     foreach ($this->tickets() as $item) {
         $tickets[] = $item->item->id;
     }
     $discounted = false;
     $count = $this->count_redemptions();
     $availableQuantity = $this->quantity - $count;
     foreach ($cart->items() as $item) {
         if ($availableQuantity <= 0) {
             break;
         }
         // We now need to check if the item can be discounted
         if (is_a($item->object, 'EventSignup')) {
             // We need to check the item's EventTicket
             if (!in_array($item->object->event_ticket_id, $tickets)) {
                 continue;
             }
         } elseif (is_a($item->object, 'EventService')) {
             // Check that the Service is allowed
             if (!in_array($item->object->service_id, $services)) {
                 continue;
             }
         }
         $this->add_for_cart($cart, $item);
         $discounted = true;
         $availableQuantity--;
     }
     if (!$discounted) {
         throw new Error500('There is nothing that can be discounted');
     }
     return true;
 }