updateLineItemQuantityById method

Order updateLineItemQuantityById(
  1. String lineItemId,
  2. int quantity
)

Updates LineItem quantity for for given lineItemId of the order.

Implementation

Order updateLineItemQuantityById(String lineItemId, int quantity) {
  if (quantity < 0) {
    throw StokedError('LineItem quantity shouldn\'t be less than 0.');
  }
  if (_orderDetails.orderLines == null || _orderDetails.orderLines!.isEmpty) {
    throw StokedError('orderLines shouldn\'t be empty');
  }
  int index = _orderDetails.orderLines!
      .indexWhere((element) => element.id == lineItemId);
  if (index != -1) {
    if (quantity == 0) {
      _orderDetails.orderLines?.removeAt(index);
    } else {
      ItemAmount itemAmount = _orderDetails.orderLines![index].itemAmount;

      int regular = quantity * itemAmount.regular;
      int campaign = quantity * (itemAmount.campaign ?? 0);
      int shipping = quantity * (itemAmount.shipping ?? 0);
      int total = regular + campaign + shipping;
      List<Tax> taxes = _orderDetails.orderLines![index].itemAmount.tax;
      for (var i = 0; i < taxes.length; i++) {
        int amount = total ~/ taxes[i].percentage;
        taxes[i] = taxes[i].copyWith(amount: amount);
      }
      _orderDetails.orderLines![index] = _orderDetails.orderLines![index]
          .copyWith(
              quantity: quantity,
              itemAmount: ItemAmount(
                  regular: regular,
                  total: total,
                  currency: Currency.sek,
                  tax: taxes));
    }
  } else {
    throw StokedError('No LineItem found for this given lineItem Id');
  }
  return this;
}