callStockDeliveryOrdersApi method

Future<void> callStockDeliveryOrdersApi()

Implementation

Future<void> callStockDeliveryOrdersApi() async {
  try {
    BuildContext context = Get.context!;
    String tempIds = storage.read("PARTNER_IDs") ?? "";
    var partnerIds = [];
    if (tempIds.isNotEmpty) {
      partnerIds = jsonDecode(tempIds);
    }
    String relatedParties = partnerIds.join(',');
    Helper.progressDialog(context, "Please wait..");
    var body = {
      "hsQuery": [
        StockDeliveryOrderRequest(
                action: null, query: "category", value: "sell-thru")
            .toJson(),
        StockDeliveryOrderRequest(
                action: null,
                query: "relatedParty",
                value: "ToDistributorId:$relatedParties")
            .toJson(),
        StockDeliveryOrderRequest(
                action: null,
                query: "relatedParty",
                value: "stockAllocation:pending")
            .toJson(),
      ]
    };
    await ApiClient(baseUrl: ApiConstant.romBaseUrl)
        .getProductOrder(
            body: body,
            sortBy: "ASC",
            fieldName: "orderDate",
            xUserId: storage.read("XUSER_ID") ?? "",
            offset: 0,
            limit: 100)
        // dio
        //     .get("https://run.mocky.io/v3/f6f21eed-9801-41ae-a248-c91de75b02cf")
        .then((response) async {
      Get.back();
      if (response != null && response.toString().trim().isNotEmpty) {
        print(response);
        List<dynamic> jsonList = response;
        List<StockDeliveryOrderModel> tempModel = jsonList
            .map((json) => StockDeliveryOrderModel.fromJson(json))
            .toList();
        List<StockDeliveryOrderModel> myModels = [];
        tempModel.forEach((element) {
          if (element.additionalInfo != null &&
              element.additionalInfo!.stockAllocation != null &&
              element.additionalInfo!.stockAllocationMilestoneStatus !=
                  null &&
              element.additionalInfo!.stockAllocationMilestoneStatus !=
                  "STOCK_ALLOCATION_DONE_REMINDER_SUCCESS") {
            myModels.add(element);
          }
          // myModels.add(element);
        });
        // var tempOrders = <SellThruProductDataModel>[];
        List<ProductContentModel> productList =
            <ProductContentModel>[]; //add all the products in all the orders
        myModels.forEach((model) {
          // SellThruProductDataModel stockOrder = SellThruProductDataModel();
          // model.orderTotalPrice!.forEach((orderTotalPrice) {
          //   stockOrder.dateTime = model.orderDate!;
          //   stockOrder.transactionId = model.Id!;
          //   stockOrder.invoiceId = model.additionalInfo!.invoiceId!;
          //   stockOrder.externalId = model.externalId;
          //   if (orderTotalPrice.priceType == "sellingPrice") {
          //     var t = "{\"unit\":\"PHP\",\"value\":1000.0}";
          //     Map<String, dynamic> mapPrice =
          //         json.decode(orderTotalPrice.price!.dutyFreeAmount!);
          //     var totalAmount = 0.0;
          //     var totalPaidAmount = 0.0;
          //     Map<String, dynamic> mapTaxPrice =
          //         json.decode(orderTotalPrice.price!.taxIncludedAmount!);
          //     mapPrice.forEach((key, value) {
          //       if (key == "value") {
          //         totalAmount = value;
          //       }
          //     });
          //     mapTaxPrice.forEach((key, value) {
          //       if (key == "value") {
          //         totalPaidAmount = value;
          //       }
          //     });

          //     stockOrder.totalAmount = totalAmount;
          //     stockOrder.totalAmountPaid = totalPaidAmount;
          //     stockOrder.totalTax = totalPaidAmount - totalAmount;
          //   }
          // });

          model.productOrderItem!.forEach((productOrderItem) {
            ProductContentModel product = ProductContentModel();
            product.totalOrderedQuantity = productOrderItem.quantity!;
            productOrderItem.itemPrice!.forEach((itemPrice) {
              if (itemPrice.priceType == "sellingPrice") {
                Map<String, dynamic> mapPrice =
                    json.decode(itemPrice.price!.dutyFreeAmount!);
                var totalAmount = 0.0;
                var totalPaidAmount = 0.0;
                Map<String, dynamic> mapTaxPrice =
                    json.decode(itemPrice.price!.taxIncludedAmount!);
                mapPrice.forEach((key, value) {
                  if (key == "value") {
                    totalAmount = value;
                  }
                });
                mapTaxPrice.forEach((key, value) {
                  if (key == "value") {
                    totalPaidAmount = value;
                  }
                });
                product.itemAmount = totalAmount;
                product.itemTax = totalPaidAmount - totalAmount;
              }
            });
            product.productName = productOrderItem.productRefOrValue!.name;
            product.productDescription =
                productOrderItem.productRefOrValue!.description;
            product.productCode =
                productOrderItem.productRefOrValue!.productSerialNumber;
            product.scannedQty = 0;
            if (productOrderItem.productRefOrValue != null &&
                productOrderItem.productRefOrValue!.productCharacteristic !=
                    null) {
              productOrderItem.productRefOrValue!.productCharacteristic!
                  .forEach((productCharacteristic) {
                if (productCharacteristic.name == "productImageUrl") {
                  product.productImage = productCharacteristic.value!;
                }
              });
            }

            product.iccidList = [];
            product.rangeList = [];
            product.scannedserialNums = [];
            var isSameProduct = false;
            productList.forEach((element) {
              if (element.productCode == product.productCode) {
                var totalQty = element.totalOrderedQuantity! +
                    product.totalOrderedQuantity!;
                element.totalOrderedQuantity =
                    totalQty; // updating the totalOrderedQty for same
                //product in different order
                element.totalOrderedQuantity;
                isSameProduct = true;
              }
            });
            if (!isSameProduct) {
              productList
                  .add(product); // adding only if unique product to list
            }
          });
          // stockOrder.content = productList;
          // tempOrders.add(stockOrder);
        });
        final ScanModel scanModel = Get.put(ScanModel());
        await scanModel.initModel(context);
        scanModel.setCurrentScanType(ScanType.collectStock);
        scanModel.productDataScannedList.value = productList;
        scanModel.searchedScannedList.value = productList;
        scanModel.originalProductList.value = productList;
        scanModel.productDataList.value = productList;
        scanModel.availableCreditBalance = availableCreditBalance;
        scanModel.usedCreditBalance = usedCreditBalance;
        scanModel.totalCreditBalance = totalCreditBalance;
        scanModel.creditLimit = creditLimit;
        scanModel.percentageCreditBalance = percentageCreditBalance;

        Get.to(() => Scan(model: scanModel));
      } else {
        Get.back();
        final ScanModel scanModel = Get.put(ScanModel());
        await scanModel.initModel(context);
        scanModel.setCurrentScanType(ScanType.collectStock);
        scanModel.availableCreditBalance = availableCreditBalance;
        scanModel.usedCreditBalance = usedCreditBalance;
        scanModel.totalCreditBalance = totalCreditBalance;
        scanModel.creditLimit = creditLimit;
        scanModel.percentageCreditBalance = percentageCreditBalance;
        Get.to(() => Scan(model: scanModel));
      }
    }).catchError((error) {
      print(error.toString());
      Get.back();
      MainController mainController = Get.put(MainController());
      mainController.showErrorPopup();
    });
  } catch (e) {
    print(e.toString());
    Get.back();
  }
}