public ActionResult OrderDelivery(FormCollection collection)
        {
            try
            {
                var  branchId         = Convert.ToInt32(Session["BranchId"]);
                var  user             = (ViewUser)Session["user"];
                var  transport        = collection["ownTransport"];
                bool isOwnTransport   = transport != null;
                int  deliverebyUserId = ((ViewUser)Session["user"]).UserId;
                int  invoiceId        = Convert.ToInt32(collection["InvoiceId"]);
                var  invoice          = _iInvoiceManager.GetInvoicedOrderByInvoiceId(invoiceId);
                IEnumerable <InvoiceDetails> details = _iInvoiceManager.GetInvoicedOrderDetailsByInvoiceId(invoiceId);
                var    client                = _iClientManager.GetById(invoice.ClientId);
                var    deliveredQty          = _iInvoiceManager.GetDeliveredProductsByInvoiceRef(invoice.InvoiceRef).Count;
                var    remainingToDeliverQty = invoice.Quantity - deliveredQty;
                string fileName              = "Scanned_Ordered_Product_List_For_" + user.UserId + "_" + invoiceId;
                var    filePath              = Server.MapPath("~/Files/" + fileName);
                //if the file is exists read the file
                var barcodeList = _iProductManager.GetScannedProductListFromTextFile(filePath).ToList();


                int invoiceStatus = Convert.ToInt32(InvoiceStatus.PartiallyDelivered);
                int orderStatus   = Convert.ToInt32(OrderStatus.PartiallyDelivered);
                if (remainingToDeliverQty == barcodeList.Count)
                {
                    invoiceStatus = Convert.ToInt32(InvoiceStatus.Delivered);
                    orderStatus   = Convert.ToInt32(OrderStatus.Delivered);
                }

                List <InvoiceDetails> deliveredProductList = new List <InvoiceDetails>();
                foreach (ScannedProduct product in barcodeList.DistinctBy(n => n.ProductId))
                {
                    var invoiceDetails = details.ToList().Find(n => n.ProductId.Equals(product.ProductId));
                    var qty            = barcodeList.ToList().FindAll(n => n.ProductId == product.ProductId).Count;
                    invoiceDetails.Quantity = qty;
                    deliveredProductList.Add(invoiceDetails);
                }
                //-----------------Credit sale account code =1001021 ---------------
                //financialModel.InvoiceDiscountCode = "2102011";
                //financialModel.InvoiceDiscountAmount = (invoice.SpecialDiscount/invoice.Quantity)*barcodeList.Count;
                //-----------------Credit vat account code =2102013 ---------------
                //-----------------Credit invoice discount account code =2102012 ---------------

                //var up=   deliveredProductList.Sum(n => n.UnitPrice);
                // var discount = deliveredProductList.Sum(n => n.Discount);


                var grossAmount     = deliveredProductList.Sum(n => (n.UnitPrice + n.Vat) * n.Quantity);
                var tradeDiscount   = deliveredProductList.Sum(n => n.Discount * n.Quantity);
                var invoiceDiscount = (invoice.SpecialDiscount / invoice.Quantity) * barcodeList.Count;
                var grossDiscount   = tradeDiscount + invoiceDiscount;
                var vat             = deliveredProductList.Sum(n => n.Vat * n.Quantity);


                var financialModel =
                    new FinancialTransactionModel
                {
                    //--------Dr -------------------
                    ClientCode          = client.SubSubSubAccountCode,
                    ClientDrAmount      = grossAmount - grossDiscount,
                    GrossDiscountAmount = grossDiscount,
                    GrossDiscountCode   = "2102018",

                    //--------Cr -------------------
                    //SalesRevenueCode = "1001021" old,
                    SalesRevenueCode   = "1001011",
                    SalesRevenueAmount = grossAmount - vat,
                    // VatCode = "2102013 test",
                    VatCode   = "3108011",
                    VatAmount = vat,

                    TradeDiscountCode     = "2102012",
                    TradeDiscountAmount   = tradeDiscount,
                    InvoiceDiscountAmount = invoiceDiscount,
                    InvoiceDiscountCode   = "2102011"
                };


                var aDelivery = new Delivery
                {
                    IsOwnTransport            = isOwnTransport,
                    TransactionRef            = invoice.TransactionRef,
                    InvoiceRef                = invoice.InvoiceRef,
                    DeliveredByUserId         = deliverebyUserId,
                    Transportation            = collection["Transportation"],
                    DriverName                = collection["DriverName"],
                    DriverPhone               = collection["DriverPhone"],
                    TransportationCost        = Convert.ToDecimal(collection["TransportationCost"]),
                    VehicleNo                 = collection["VehicleNo"],
                    DeliveryDate              = Convert.ToDateTime(collection["DeliveryDate"]).Date,
                    CompanyId                 = invoice.CompanyId,
                    ToBranchId                = invoice.BranchId,
                    DistributionPointId       = branchId,
                    InvoiceId                 = invoiceId,
                    FromBranchId              = invoice.BranchId,
                    FinancialTransactionModel = financialModel,
                    SpecialDiscount           = invoiceDiscount
                };

                //----------SMS Buildder Model-----------
                var aModel = new MessageModel
                {
                    PhoneNumber     = client.Phone.Replace("-", "").Trim(),
                    CustomerName    = client.ClientName,
                    TotalQuantity   = deliveredProductList.Sum(n => n.Quantity),
                    Amount          = financialModel.ClientDrAmount,
                    TransactionDate = DateTime.Now,
                };
                aDelivery.MessageModel = aModel;


                if (client.IsConsiderCreditLimit == 1)
                {
                    var netAmount = grossAmount - grossDiscount;
                    if (netAmount <= client.CreditLimit)
                    {
                        string result = _iInventoryManager.SaveDeliveredOrderFromFactory(barcodeList, aDelivery, invoiceStatus, orderStatus);
                        aModel.MessageBody = aModel.GetMessageForDistribution();
                        if (result.StartsWith("S"))
                        {
                            System.IO.File.Create(filePath).Close();

                            //-----------Send SMS after successfull delivery info save------------

                            var res = _iCommonManager.SendSms(aModel);
                            return(RedirectToAction("DeliverableOrderList"));
                        }
                    }
                    else
                    {
                        TempData["CreditLimit"] = "Credit Limit exceed!!";
                        return(View());
                    }
                }
                else
                {
                    string result = _iInventoryManager.SaveDeliveredOrderFromFactory(barcodeList, aDelivery, invoiceStatus, orderStatus);
                    aModel.MessageBody = aModel.GetMessageForDistribution();

                    if (result.StartsWith("S"))
                    {
                        System.IO.File.Create(filePath).Close();
                        //-----------Send SMS after successfull delivery info save------------
                        var res = _iCommonManager.SendSms(aModel);

                        return(RedirectToAction("DeliverableOrderList"));
                    }
                    return(View());
                }


                return(View());
            }
            catch (Exception exception)
            {
                TempData["Error"] = exception.Message;
                Log.WriteErrorLog(exception);
                return(PartialView("_ErrorPartial", exception));
            }
        }