Add a new coupon to cart

REST: POST /order/cart/{cartId}/coupon
@param cartId [required] Cart identifier
@param coupon [required] Coupon identifier
326649
public ArrayList<String> cart_cartId_coupon_POST(String cartId, String coupon) throws IOException {
		String qPath = "/order/cart/{cartId}/coupon";
		StringBuilder sb = path(qPath, cartId);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "coupon", coupon);
		String resp = execN(qPath, "POST", sb.toString(), o);
		return convertTo(resp, t1);
	}
689622
public function dispatchCartCouponOnApplyEvent(
        CartInterface $cart,
        CouponInterface $coupon
    ) {
        $event = new CartCouponOnApplyEvent($cart, $coupon);
        $this->eventDispatcher->dispatch(
            ElcodiCartCouponEvents::CART_COUPON_ONAPPLY,
            $event
        );
    }
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;
    }
628560
def query_coupon(self, coupon_id, user_id,
                     op_user_id=None, device_info=None):
        
        data = {
            'coupon_id': coupon_id,
            'openid': user_id,
            'appid': self.appid,
            'op_user_id': op_user_id,
            'device_info': device_info,
            'version': '1.0',
            'type': 'XML',
        }
        return self._post('promotion/query_coupon', data=data)
997703
public BranchEvent setCoupon(String coupon) {
        return addStandardProperty(Defines.Jsonkey.Coupon.getKey(), coupon);
    }
242751
private function addCouponToOrder($coupons, $new_order)
    {
        $errors = new \Illuminate\Support\MessageBag;
        
        if (count($coupons) > 0) {
            foreach ($coupons as $item) {
                $model = Coupon::find($item);
                if ($model != null) {
                    try {
                        $new_order->addCoupon($model);
                    } catch (Exception $exp) {
                        $errors->add(
                            'couponError',
                            "Coupon " . $model->code . " cannot be added because: " . $exp->getMessage()
                        );
                        
                    }
                }
            }
            
            // Set coupon discount
            $new_order->setDiscounts();
        }
        
        return $errors;
    }
1331367
public static Coupon retrieve(String coupon, RequestOptions options) throws StripeException {
    return retrieve(coupon, (Map<String, Object>) null, options);
  }
750636
func New(params *stripe.CouponParams) (*stripe.Coupon, error) {
	return getC().New(params)
}
75421
public function createOrderCouponsByCartCoupons(
        CartInterface $cart,
        OrderInterface $order
    ) {
        $cartCouponAmount = $cart->getCouponAmount();

        if ($cartCouponAmount instanceof MoneyInterface) {
            $order->setCouponAmount($cartCouponAmount);
        }

        /**
         * @var CouponInterface $coupons
         */
        $coupons = $this
            ->cartCouponManager
            ->getCoupons($cart);

        if (empty($coupons)) {
            return;
        }

        /**
         * Before applying Coupons to Order, we should remove old references
         * if exist.
         */
        $this
            ->orderCouponTruncator
            ->truncateOrderCoupons($order);

        /**
         * An event is dispatched for each convertible coupon.
         */
        foreach ($coupons as $coupon) {
            $this
                ->orderCouponEventDispatcher
                ->dispatchOrderCouponOnApplyEvent(
                    $order,
                    $coupon
                );
        }
    }
81647
public function applyCoupon($coupon, $removeOthers = false)
    {
        if (! $this->active()) {
            throw new InvalidArgumentException('Unable to apply coupon. Subscription not active.');
        }

        BraintreeSubscription::update($this->braintree_id, [
            'discounts' => [
                'add' => [[
                    'inheritedFromId' => $coupon,
                ]],
                'remove' => $removeOthers ? $this->currentDiscounts() : [],
            ],
        ]);
    }
99876
public static MozuUrl removeCouponUrl(String checkoutId, String couponCode)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/coupons/{couponcode}");
		formatter.formatUrl("checkoutId", checkoutId);
		formatter.formatUrl("couponCode", couponCode);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}
1349090
def query_stock(self, stock_id, op_user_id=None, device_info=None):
        
        data = {
            'appid': self.appid,
            'coupon_stock_id': stock_id,
            'op_user_id': op_user_id,
            'device_info': device_info,
            'version': '1.0',
            'type': 'XML',
        }
        return self._post('mmpaymkttransfers/query_coupon_stock', data=data)
548245
public function setCoupon($coupon)
    {
        if ($coupon->value > 0) {
            $this->coupon['value'] = $coupon->value;
        }
        elseif ($coupon->discount > 0) {
            $this->coupon['percent'] = $coupon->discount;
        }
        session(['coupon' => $coupon]);
    }
62984
public function getCouponAbsoluteValue(
        CartInterface $cart,
        CouponInterface $coupon
    ) {
        $currency = $this
            ->currencyWrapper
            ->get();

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

        foreach ($this->cartCouponApplicators as $cartCouponApplicator) {
            if ($cartCouponApplicator->canBeApplied(
                $cart,
                $coupon
            )) {
                return $cartCouponApplicator->getCouponAbsoluteValue(
                    $cart,
                    $coupon
                );
            }
        }

        return $couponPrice;
    }
642132
public Coupons getUniqueCouponCodes(final String couponCode, final QueryParams params) {
        return doGET(Coupon.COUPON_RESOURCE + "/" + couponCode + Coupon.UNIQUE_CODES_RESOURCE,
                Coupons.class, params);
    }
1323989
private function isActive(CouponInterface $coupon, \DateTime $now = null)
    {
        if (!$coupon->isEnabled()) {
            return false;
        }

        $now = $now ?: $this
            ->dateTimeFactory
            ->create();

        if ($coupon->getValidFrom() > $now) {
            return false;
        }

        $validTo = $coupon->getValidTo();
        if ($validTo && $now > $validTo) {
            return false;
        }

        return true;
    }
446282
public static QueryCouponStockResult mmpaymkttransfersQuery_coupon_stock(QueryCouponStock queryCouponStock,String key){
		Map<String,String> map = MapUtil.objectToMap( queryCouponStock);
		String sign = SignatureUtil.generateSign(map,queryCouponStock.getSign_type(),key);
		queryCouponStock.setSign(sign);
		String secapiPayRefundXML = XMLConverUtil.convertToXML( queryCouponStock);
		HttpUriRequest httpUriRequest = RequestBuilder.post()
				.setHeader(xmlHeader)
				.setUri(baseURI()+ "/mmpaymkttransfers/query_coupon_stock")
				.setEntity(new StringEntity(secapiPayRefundXML,Charset.forName("utf-8")))
				.build();
		return LocalHttpClient.executeXmlResult(httpUriRequest,QueryCouponStockResult.class,queryCouponStock.getSign_type(),key);
	}