/**
* Create or update an order coupon
*
* @since 2.2
* @param \WC_Order $order
* @param array $coupon item data
* @param string $action 'create' to add coupon or 'update' to update it
* @throws WC_API_Exception invalid data, server error
*/
protected function set_coupon($order, $coupon, $action)
{
// coupon amount must be positive float
if (isset($coupon['amount']) && floatval($coupon['amount']) < 0) {
throw new WC_API_Exception('woocommerce_invalid_coupon_total', __('Coupon discount total must be a positive amount', 'woocommerce'), 400);
}
if ('create' === $action) {
// coupon code is required
if (empty($coupon['code'])) {
throw new WC_API_Exception('woocommerce_invalid_coupon_coupon', __('Coupon code is required', 'woocommerce'), 400);
}
$item = new WC_Order_Item_Coupon(array('code' => $coupon['code'], 'discount' => isset($coupon['amount']) ? floatval($coupon['amount']) : 0, 'discount_tax' => 0, 'order_id' => $order->get_id()));
$coupon_id = $item->save();
if (!$coupon_id) {
throw new WC_API_Exception('woocommerce_cannot_create_order_coupon', __('Cannot create coupon, try again', 'woocommerce'), 500);
}
} else {
$item = new WC_Order_Item_Coupon($coupon['id']);
if (isset($coupon['code'])) {
$item->set_code($coupon['code']);
}
if (isset($coupon['amount'])) {
$item->set_discount(floatval($coupon['amount']));
}
$coupon_id = $item->save();
if (!$coupon_id) {
throw new WC_API_Exception('woocommerce_cannot_update_order_coupon', __('Cannot update coupon, try again', 'woocommerce'), 500);
}
}
}