Delete a coupon from cart

REST: DELETE /order/cart/{cartId}/coupon
@param cartId [required] Cart identifier
@param coupon [required] Coupon identifier
979065
public void cart_cartId_coupon_DELETE(String cartId, String coupon) throws IOException {
		String qPath = "/order/cart/{cartId}/coupon";
		StringBuilder sb = path(qPath, cartId);
		query(sb, "coupon", coupon);
		execN(qPath, "DELETE", sb.toString(), null);
	}
1228212
public function getCouponAbsoluteValue(
        CartInterface $cart,
        CouponInterface $coupon
    ) {
        $currency = $this
            ->currencyWrapper
            ->get();

        $couponPrice = Money::create(
            0,
            $currency
        );

        $value = $coupon->getValue();
        preg_match($this->regexp(), $value, $match);
        $m = (int) $match[1];
        $n = (int) $match[2];
        $expressionValue = isset($match[3]) ? $match[3] : '';
        $modifiers = isset($match[4]) ? $match[4] : '';

        $totalElements = 0;
        $moneys = [];
        $freePerGroup = $m - $n;
        $freePerGroup = max($freePerGroup, 0);

        foreach ($cart->getCartLines() as $cartLine) {
            $purchasable = $cartLine->getPurchasable();
            $expressionEvaluator = $this->getExpressionLanguageInstance();
            $expressionResult =
                (
                    empty($expressionValue) ||
                    $expressionEvaluator->evaluate($expressionValue, [
                        'purchasable' => $purchasable,
                    ])
                ) &&
                $this->evaluatePurchasableType($purchasable, $modifiers);

            if (true === $expressionResult) {
                $partialElements = $cartLine->getQuantity();
                $totalElements += $partialElements;
                for ($i = 0; $i < $partialElements; ++$i) {
                    $partialPurchasable = $cartLine->getPurchasable();
                    $moneys[] = $partialPurchasable->getReducedPrice()->getAmount() > 0
                        ? $partialPurchasable->getReducedPrice()
                        : $partialPurchasable->getPrice();
                }
            }
        }

        usort($moneys, function (MoneyInterface $a, MoneyInterface $b) {
            $aCurrency = $a->getCurrency();
            $bPriceInACurrency = $this
                ->currencyConverter
                ->convertMoney(
                    $b,
                    $aCurrency
                );

            return $a->isGreaterThan($bPriceInACurrency)
                ? 1
                : -1;
        });
        $groups = floor($totalElements / $m);
        if ($groups > 0) {
            $nbMoneys = $groups * $freePerGroup;
            $moneysToDiscount = array_slice($moneys, 0, $nbMoneys);

            foreach ($moneysToDiscount as $moneyToDiscount) {
                $couponPrice = $couponPrice->add(
                    $this
                        ->currencyConverter
                        ->convertMoney(
                            $moneyToDiscount,
                            $currency
                        )
                );
            }
        }

        return $couponPrice;
    }
419264
@Override
	public void removeByCommerceWarehouseId(long commerceWarehouseId) {
		for (CommerceWarehouseItem commerceWarehouseItem : findByCommerceWarehouseId(
				commerceWarehouseId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(commerceWarehouseItem);
		}
	}
167626
public OvhCart cart_cartId_PUT(String cartId, String description, Date expire) throws IOException {
		String qPath = "/order/cart/{cartId}";
		StringBuilder sb = path(qPath, cartId);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "description", description);
		addBody(o, "expire", expire);
		String resp = execN(qPath, "PUT", sb.toString(), o);
		return convertTo(resp, OvhCart.class);
	}
700008
public function isCouponRemovingPostage(Order $order)
    {
        $coupons = $this->facade->getCurrentCoupons();

        if (\count($coupons) == 0) {
            return false;
        }

        $couponsKept = $this->sortCoupons($coupons);

        /** @var CouponInterface $coupon */
        foreach ($couponsKept as $coupon) {
            if ($coupon->isRemovingPostage()) {
                // Check if delivery country is on the list of countries for which delivery is free
                // If the list is empty, the shipping is free for all countries.
                $couponCountries = $coupon->getFreeShippingForCountries();

                if (! $couponCountries->isEmpty()) {
                    if (null === $deliveryAddress = AddressQuery::create()->findPk($order->getChoosenDeliveryAddress())) {
                        continue;
                    }

                    $countryValid = false;

                    $deliveryCountryId = $deliveryAddress->getCountryId();

                    /** @var CouponCountry $couponCountry */
                    foreach ($couponCountries as $couponCountry) {
                        if ($deliveryCountryId == $couponCountry->getCountryId()) {
                            $countryValid = true;
                            break;
                        }
                    }

                    if (! $countryValid) {
                        continue;
                    }
                }

                // Check if shipping method is on the list of methods for which delivery is free
                // If the list is empty, the shipping is free for all methods.
                $couponModules = $coupon->getFreeShippingForModules();

                if (! $couponModules->isEmpty()) {
                    $moduleValid = false;

                    $shippingModuleId = $order->getDeliveryModuleId();

                    /** @var CouponModule $couponModule */
                    foreach ($couponModules as $couponModule) {
                        if ($shippingModuleId == $couponModule->getModuleId()) {
                            $moduleValid = true;
                            break;
                        }
                    }

                    if (! $moduleValid) {
                        continue;
                    }
                }

                // All conditions are met, the shipping is free !
                return true;
            }
        }

        return false;
    }
659160
@Override
	public void removeByG_C(long groupId, String couponCode) {
		for (CommerceDiscount commerceDiscount : findByG_C(groupId, couponCode,
				QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(commerceDiscount);
		}
	}
3764
public function clearAllCoupons(Event $event, $eventName, EventDispatcherInterface $dispatcher)
    {
        // Tell coupons to clear any data they may have stored
        $this->couponManager->clear();

        $this->getSession()->setConsumedCoupons(array());

        $this->updateOrderDiscount($event, $eventName, $dispatcher);
    }
1265176
def cart_clear(self, CartId=None, HMAC=None, **kwargs):
        
        if not CartId or not HMAC:
            raise CartException('CartId required for CartClear call')
        response = self.api.CartClear(CartId=CartId, HMAC=HMAC, **kwargs)
        root = objectify.fromstring(response)

        new_cart = AmazonCart(root)
        self._check_for_cart_error(new_cart)

        return new_cart
119794
static final HllSketchImpl promoteHeapListOrSetToHll(final CouponList src) {
    final HllArray tgtHllArr = HllArray.newHeapHll(src.lgConfigK, src.tgtHllType);
    final PairIterator srcItr = src.iterator();
    tgtHllArr.putKxQ0(1 << src.lgConfigK);
    while (srcItr.nextValid()) {
      tgtHllArr.couponUpdate(srcItr.getPair());
    }
    tgtHllArr.putHipAccum(src.getEstimate());

    tgtHllArr.putOutOfOrderFlag(false);
    return tgtHllArr;
  }
1026062
def remove_from_cart_link(item)
      link_to(mongoid_cart.remove_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do
        (tag :i, class: 'fa fa-cart-plus').concat('Remove from cart')
      end
    end
85313
public function addCoupon(CouponContract $coupon)
    {
        if (!$this->cart->multipleCoupons) {
            $this->cart->coupons = [];
        }

        $this->cart->coupons[$coupon->code] = $coupon;

        $this->update();
    }
1297639
def save(self, force_retrieve=False, *args, **kwargs):
        
        stripe.api_key = stripe_settings.API_KEY
        if self._previous_is_deleted != self.is_deleted and self.is_deleted:
            try:
                stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
                # make sure to delete correct coupon
                if self.created == timestamp_to_timezone_aware_date(stripe_coupon["created"]):
                    stripe_coupon.delete()
            except stripe.error.InvalidRequestError:
                # means that the coupon has already been removed from stripe
                pass

            return super(StripeCoupon, self).save(*args, **kwargs)

        if self.pk or force_retrieve:
            try:
                stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
                if not force_retrieve:
                    stripe_coupon.metadata = self.metadata
                    stripe_coupon.save()

                if force_retrieve:
                    # make sure we are not creating a duplicate
                    coupon_qs = StripeCoupon.objects.filter(coupon_id=self.coupon_id)
                    if coupon_qs.filter(created=timestamp_to_timezone_aware_date(stripe_coupon["created"])).exists():
                        raise StripeCouponAlreadyExists

                    # all old coupons should be deleted
                    for coupon in coupon_qs:
                        coupon.is_deleted = True
                        super(StripeCoupon, coupon).save()  # use super save() to call pre/post save signals
                # update all fields in the local object in case someone tried to change them
                self.update_from_stripe_data(stripe_coupon, exclude_fields=["metadata"] if not force_retrieve else [])
                self.stripe_response = stripe_coupon
            except stripe.error.InvalidRequestError:
                if force_retrieve:
                    raise

                self.is_deleted = True
        else:
            self.stripe_response = stripe.Coupon.create(
                id=self.coupon_id,
                duration=self.duration,
                amount_off=int(self.amount_off * 100) if self.amount_off else None,
                currency=self.currency,
                duration_in_months=self.duration_in_months,
                max_redemptions=self.max_redemptions,
                metadata=self.metadata,
                percent_off=self.percent_off,
                redeem_by=int(dateformat.format(self.redeem_by, "U")) if self.redeem_by else None
            )
            # stripe will generate coupon_id if none was specified in the request
            if not self.coupon_id:
                self.coupon_id = self.stripe_response["id"]

        self.created = timestamp_to_timezone_aware_date(self.stripe_response["created"])
        # for future
        self.is_created_at_stripe = True
        return super(StripeCoupon, self).save(*args, **kwargs)
819783
public function remove(CartId $cartId)
    {
        if (!$this->exists($cartId)) {
            throw CartNotFoundException::byId($cartId);
        }

        unset($this->carts[(string) $cartId]);
    }
424602
public function validateCartCouponRules(
        CartInterface $cart,
        CouponInterface $coupon
    ) {
        $rule = $coupon->getRule();

        if (null === $rule) {
            return;
        }

        try {
            $isValid = $this
                ->ruleManager
                ->evaluate(
                    $rule,
                    [
                        'cart' => $cart,
                        'coupon' => $coupon,
                    ]
                );

            if (!$isValid) {
                throw new CouponRulesNotValidateException();
            }

            return;
        } catch (Exception $e) {
            // Maybe log something in case of exception?
        }

        throw new CouponRulesNotValidateException();
    }
1341798
function collect_posts() {
    global $db, $currencies, $messageStack, $order;
    global $discount_coupon;
    // remove discount coupon by request
    if (isset($_POST['dc_redeem_code']) && strtoupper($_POST['dc_redeem_code']) == 'REMOVE') {
      unset($_POST['dc_redeem_code']);
      unset($_SESSION['cc_id']);
      $messageStack->add_session('checkout_payment', TEXT_REMOVE_REDEEM_COUPON, 'caution');
    }
//    print_r($_SESSION);
    // bof: Discount Coupon zoned always validate coupon for payment address changes
    // eof: Discount Coupon zoned always validate coupon for payment address changes
    if ((isset($_POST['dc_redeem_code']) && $_POST['dc_redeem_code'] != '') || (isset($discount_coupon->fields['coupon_code']) && $discount_coupon->fields['coupon_code'] != '')) {
      // set current Discount Coupon based on current or existing
      if (isset($_POST['dc_redeem_code']) && $discount_coupon->fields['coupon_code'] == '') {
        $dc_check = $_POST['dc_redeem_code'];
      } else {
        $dc_check = $discount_coupon->fields['coupon_code'];
      }



      $sql = "select coupon_id, coupon_amount, coupon_type, coupon_minimum_order, uses_per_coupon, uses_per_user,
              restrict_to_products, restrict_to_categories, coupon_zone_restriction
              from " . TABLE_COUPONS . "
              where coupon_code= :couponCodeEntered
              and coupon_active='Y'
              and coupon_type !='G'";

      $sql = $db->bindVars($sql, ':couponCodeEntered', $dc_check, 'string');

      $coupon_result=$db->Execute($sql);

      if ($coupon_result->fields['coupon_type'] != 'G') {

        if ($coupon_result->RecordCount() < 1 ) {
          $messageStack->add_session('redemptions', TEXT_INVALID_REDEEM_COUPON,'caution');
          $this->clear_posts();
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL',true, false));
        }
        $order_total = $this->get_order_total($coupon_result->fields['coupon_id']);

// left for total order amount vs qualified order amount just switch the commented lines
//        if ($order_total['totalFull'] < $coupon_result->fields['coupon_minimum_order']) {
        if (strval($order_total['orderTotal']) < $coupon_result->fields['coupon_minimum_order']) {

          $messageStack->add_session('redemptions', sprintf(TEXT_INVALID_REDEEM_COUPON_MINIMUM, $currencies->format($coupon_result->fields['coupon_minimum_order'])),'caution');
          $this->clear_posts();
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL',true, false));
        }

        // JTD - added missing code here to handle coupon product restrictions
        // look through the items in the cart to see if this coupon is valid for any item in the cart
        $products = $_SESSION['cart']->get_products();
        $foundvalid = true;

        if ($foundvalid == true) {
          $foundvalid = false;
          for ($i=0; $i<sizeof($products); $i++) {
            if (is_product_valid($products[$i]['id'], $coupon_result->fields['coupon_id'])) {
              $foundvalid = true;
              continue;
            }
          }
        }

        if (!$foundvalid) {
          $this->clear_posts();
        }

        if (!$foundvalid) zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, 'credit_class_error_code=' . $this->code . '&credit_class_error=' . urlencode(TEXT_INVALID_COUPON_PRODUCT . ' ' . $dc_check), 'SSL',true, false));
        // JTD - end of additions of missing code to handle coupon product restrictions

        $date_query=$db->Execute("select coupon_start_date from " . TABLE_COUPONS . "
                                  where coupon_start_date <= now() and
                                  coupon_code='" . zen_db_prepare_input($dc_check) . "'");

        if ($date_query->RecordCount() < 1 ) {
          $messageStack->add_session('redemptions', TEXT_INVALID_STARTDATE_COUPON,'caution');
          $this->clear_posts();
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }

        $date_query=$db->Execute("select coupon_expire_date from " . TABLE_COUPONS . "
                                  where coupon_expire_date >= now() and
                                  coupon_code='" . zen_db_prepare_input($dc_check) . "'");

        if ($date_query->RecordCount() < 1 ) {
          $messageStack->add_session('redemptions', TEXT_INVALID_FINISHDATE_COUPON,'caution');
          $this->clear_posts();
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }

        $coupon_count = $db->Execute("select coupon_id from " . TABLE_COUPON_REDEEM_TRACK . "
                                      where coupon_id = '" . (int)$coupon_result->fields['coupon_id']."'");

        $coupon_count_customer = $db->Execute("select coupon_id from " . TABLE_COUPON_REDEEM_TRACK . "
                                               where coupon_id = '" . $coupon_result->fields['coupon_id']."' and
                                               customer_id = '" . (int)$_SESSION['customer_id'] . "'");

        if ($coupon_count->RecordCount() >= $coupon_result->fields['uses_per_coupon'] && $coupon_result->fields['uses_per_coupon'] > 0) {
          $messageStack->add_session('redemptions', TEXT_INVALID_USES_COUPON . $coupon_result->fields['uses_per_coupon'] . TIMES ,'caution');
          $this->clear_posts();
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }

        if ($coupon_count_customer->RecordCount() >= $coupon_result->fields['uses_per_user'] && $coupon_result->fields['uses_per_user'] > 0) {
          $messageStack->add_session('redemptions', sprintf(TEXT_INVALID_USES_USER_COUPON, $dc_check) . $coupon_result->fields['uses_per_user'] . ($coupon_result->fields['uses_per_user'] == 1 ? TIME : TIMES) ,'caution');
          $this->clear_posts();
          zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
        }

        $_SESSION['cc_id'] = $coupon_result->fields['coupon_id'];
        if ($_SESSION['cc_id'] > 0) {
          $sql = "select coupon_id, coupon_amount, coupon_type, coupon_minimum_order, uses_per_coupon, uses_per_user,
                  restrict_to_products, restrict_to_categories, coupon_zone_restriction, coupon_code
                  from " . TABLE_COUPONS . "
                  where coupon_id= :couponIDEntered
                  and coupon_active='Y'";
          $sql = $db->bindVars($sql, ':couponIDEntered', $_SESSION['cc_id'], 'string');

          $coupon_result=$db->Execute($sql);

          $foundvalid = true;

          $check_flag = false;

          // base restrictions zone restrictions for Delivery or Billing address
          switch($coupon_result->fields['coupon_type']) {
            case 'S': // shipping
              // use delivery address
              $check_zone_country_id = $order->delivery['country']['id'];
              break;
            case 'F': // amount
              // use billing address
              $check_zone_country_id = $order->billing['country']['id'];
              break;
            case 'O': // amount off and free shipping
              // use delivery address
              $check_zone_country_id = $order->delivery['country']['id'];
              break;
            case 'P': // percentage
              // use billing address
              $check_zone_country_id = $order->billing['country']['id'];
              break;
            case 'E': // percentage and Free Shipping
              // use delivery address
              $check_zone_country_id = $order->delivery['country']['id'];
              break;
            default:
              // use billing address
              $check_zone_country_id = $order->billing['country']['id'];
              break;
          }

//          $sql = "select zone_id, zone_country_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . $coupon_result->fields['coupon_zone_restriction'] . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id";
          $sql = "select zone_id, zone_country_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . $coupon_result->fields['coupon_zone_restriction'] . "' and zone_country_id = '" . $check_zone_country_id . "' order by zone_id";
          $check = $db->Execute($sql);

          // base restrictions zone restrictions for Delivery or Billing address
          switch($coupon_result->fields['coupon_type']) {
            case 'S': // shipping
              // use delivery address
              $check_zone_id = $order->delivery['zone_id'];
              break;
            case 'F': // amount
              // use billing address
              $check_zone_id = $order->billing['zone_id'];
              break;
            case 'O': // amount off and free shipping
              // use delivery address
              $check_zone_id = $order->delivery['zone_id'];
              break;
            case 'P': // percentage
              // use billing address
              $check_zone_id = $order->billing['zone_id'];
              break;
            case 'E': // percentage and free shipping
              // use delivery address
              $check_zone_id = $order->delivery['zone_id'];
              break;
            default:
              // use billing address
              $check_zone_id = $order->billing['zone_id'];
              break;
          }

          if ($coupon_result->fields['coupon_zone_restriction'] > 0) {
            while (!$check->EOF) {
              if ($check->fields['zone_id'] < 1) {
                $check_flag = true;
                break;
//              } elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
              } elseif ($check->fields['zone_id'] == $check_zone_id) {
                $check_flag = true;
                break;
              }
              $check->MoveNext();
            }
            $foundvalid = $check_flag;
          }
          // remove if fails address validation
          if (!$foundvalid) {
            $messageStack->add_session('checkout_payment', TEXT_REMOVE_REDEEM_COUPON_ZONE, 'caution');
            $this->clear_posts();
            if (!$foundvalid) zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL',true, false));
          } else {
          //      if ($_POST['submit_redeem_coupon_x'] && !$_POST['gv_redeem_code']) zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, 'credit_class_error_code=' . $this->code . '&credit_class_error=' . urlencode(TEST_NO_REDEEM_CODE), 'SSL', true, false));
            $messageStack->add('checkout', TEXT_VALID_COUPON,'success');
          }
        }
      } else {
        $messageStack->add_session('redemptions', TEXT_INVALID_REDEEM_COUPON,'caution');
        $this->clear_posts();
        zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL',true, false));
      }

    }
  }
238193
public void generateUniqueCodes(final String couponCode, final Coupon coupon) {
        doPOST(Coupon.COUPON_RESOURCE + "/" + couponCode + Coupon.GENERATE_RESOURCE,
                      coupon, null);
    }
380430
public static com.liferay.commerce.model.CommerceOrderNote deleteCommerceOrderNote(
		com.liferay.commerce.model.CommerceOrderNote commerceOrderNote) {
		return getService().deleteCommerceOrderNote(commerceOrderNote);
	}