PageRenderTime 58ms CodeModel.GetById 3ms app.highlight 44ms RepoModel.GetById 1ms app.codeStats 1ms

/testwebapi/Controllers/OrdersController.cs

https://bitbucket.org/chmuniprasad/api
C# | 1271 lines | 1136 code | 103 blank | 32 comment | 134 complexity | 0dbb8acbea18b2c34495fc497e3a3be8 MD5 | raw file
   1using CompLibrary;
   2using DBLibrary;
   3using Newtonsoft.Json;
   4using System;
   5using System.Collections.Generic;
   6using System.ComponentModel.DataAnnotations;
   7using System.Data;
   8using System.IO;
   9using System.Linq;
  10using System.Net;
  11using System.Net.Http;
  12using System.Text;
  13using System.Web.Http;
  14using Pay2CartAPI.Models;
  15using Pay2CartAPI.Response;
  16using System.Xml.Linq;
  17using Pay2CartAPI.Classes;
  18using Pay2CartAPI.WalletService;
  19using System.Configuration;
  20using Newtonsoft.Json.Linq;
  21using System.Text.RegularExpressions;
  22
  23namespace Pay2CartAPI.Controllers
  24{
  25   
  26    public class OrdersController : ApiController
  27    {
  28        public string response = "";
  29        public DataTable MaxQty;
  30        public decimal result = decimal.Zero;
  31        public string MyIPAddress = "";
  32        public DataTable dt;
  33        public DataTable dt2;
  34        public decimal ProductInitialPrice = decimal.Zero;
  35        public decimal ProductAdjPrice = decimal.Zero;
  36        public decimal ProductFinalCost = decimal.Zero;
  37        public decimal ProductFinalCostInclTax = decimal.Zero;
  38        public decimal ProductFinalCostExclTax = decimal.Zero;
  39        public decimal CartSubTotal = decimal.Zero;
  40        public decimal CartSubTotalInclTax = decimal.Zero;
  41        public decimal CartSubTotalExclTax = decimal.Zero;
  42        public decimal taxrate = decimal.Zero;
  43        public decimal ProductTierPrice = decimal.Zero;
  44
  45        [HttpPost]
  46        [Authorize]
  47        public HttpResponseMessage Summary([FromBody]Summary summary)
  48        {
  49
  50            SummaryResponseObj ResponseObj = new SummaryResponseObj();
  51            string response = "";
  52            try
  53            {
  54                if (ModelState.IsValid)
  55                {
  56                    DataTable priceDet = new DataTable();
  57                    priceDet.Columns.Add("value",typeof(System.Int32));
  58                    priceDet.Columns.Add("name");
  59                    DataTable dtr = OrdersComp.CheckBundleIteminCart(summary.id_customer);
  60                    DataTable paymentmethods = OrdersComp.Paymentmethods(summary.id_customer);
  61                    DataTable paymentMethod = new DataTable();
  62                    paymentMethod.Columns.Add("value");
  63                    paymentMethod.Columns.Add("name");
  64
  65                    if (paymentmethods.Rows.Count>0)
  66                    {
  67                        for(int i=0;i<= paymentmethods.Rows.Count-1;i++)
  68                        {
  69                            if(paymentmethods.Rows[i]["name"].ToString().Contains("OnlinePayment"))
  70                            {
  71                                paymentMethod.Rows.Add("ccavenue", "Online Payment");
  72                            }
  73                            if (paymentmethods.Rows[i]["name"].ToString().Contains("CashOnDelivery"))
  74                            {
  75                                paymentMethod.Rows.Add("cod", "Cash On Delivery");
  76                            }
  77                        }
  78                    }
  79
  80
  81                    DataTable pricingDetails = OrdersComp.Pricedetails(summary.id_customer);
  82                    pricingDetails.Columns.Add("Total");
  83                    int sumAmount = 0;
  84                    if(pricingDetails.Rows.Count>0)
  85                    {
  86                        int sum = Convert.ToInt32(pricingDetails.Compute("SUM(shipping)", string.Empty));
  87                        priceDet.Rows.Add(0, "Shipping Total");
  88                        //sumAmount = sum;
  89                        sumAmount = 0;
  90                    }
  91                    
  92                    
  93
  94                     
  95                    if (pricingDetails.Rows.Count>0)
  96                    {
  97                        for (int i=0;i<= pricingDetails.Rows.Count-1;i++)
  98                        {
  99                            decimal price = decimal.Zero;
 100                            price = decimal.Multiply((Int32)pricingDetails.Rows[i]["Quantity"], (decimal)pricingDetails.Rows[i]["Price"]);
 101                            pricingDetails.Rows[i]["Total"] = price;
 102                        }
 103                    }
 104                   
 105                    float balance = Wallet.getCustomerCurrentWalletBalance(summary.id_customer);
 106                    ResponseObj.userWalletAmount = balance;
 107
 108                    bool bundleitem = false;
 109                    if (dtr.Rows.Count > 0)
 110                    {
 111                        for (int i = 0; i <= dtr.Rows.Count - 1; i++)
 112                        {
 113                            bundleitem = (bool)dtr.Rows[i][0];
 114                            MaxQty = OrdersComp.GetCartItemsBeforeOrder(summary.id_customer, bundleitem);
 115                            if (MaxQty.Rows.Count > 0)
 116                            {
 117                                foreach (DataRow dr in MaxQty.Rows)
 118                                {
 119                                    if ((Int32)(dr["StockQuantity"]) < (Int32)(dr["Quantity"]))
 120                                    {
 121                                        ResponseObj.message = "Product Qty is not Available in Stock.";
 122                                        ResponseObj.status = 0;
 123                                    }
 124                                    else
 125                                    {
 126                                        GetCartSubTotal(dr);
 127                                    }
 128                                    CartSubTotal += ProductFinalCost;
 129                                    CartSubTotalInclTax += ProductFinalCostInclTax;
 130                                    CartSubTotalExclTax += ProductFinalCostExclTax;
 131                                }
 132                            }
 133                        }
 134                        priceDet.Rows.Add(CartSubTotal, "Subtotal");
 135                        decimal pp = decimal.Add(CartSubTotal, sumAmount);
 136                        priceDet.Rows.Add(pp, "Total");
 137                        ResponseObj.status = 1;
 138                        ResponseObj.paymentmethods = paymentMethod;
 139                        ResponseObj.pricingDetails = priceDet;
 140                        ResponseObj.deliverDays = "2-5 working days";
 141                        ResponseObj.message = "Order Summary";
 142                    }
 143                    
 144                    else
 145                    {
 146                        ResponseObj.status = 0;
 147                        ResponseObj.message = Common.NoRecordsExists;
 148                    }
 149                }
 150                else
 151                {
 152                    ResponseObj.status = 0;
 153                    ResponseObj.message = "Customer ID Required.";
 154                }
 155            }
 156            catch (Exception Err)
 157            {
 158
 159            }
 160            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
 161            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
 162            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
 163            return HttpResponseMessage;
 164        }
 165
 166        [HttpPost]
 167        [Authorize]
 168        public HttpResponseMessage reOder([FromBody]ReOrder reorder)
 169        {
 170
 171            reOrderResponseObj ResponseObj = new reOrderResponseObj();
 172            string response = "";
 173            try
 174            {
 175                if (ModelState.IsValid)
 176                {
 177                    DataTable OrderProducts = OrdersComp.GetOrderProducts(reorder.customerID,reorder.orderID);
 178                    if(OrderProducts.Rows.Count>0)
 179                    {
 180                        for(int i=0;i<= OrderProducts.Rows.Count -1;i++)
 181                        {
 182                            int productid = (Int32)OrderProducts.Rows[i]["ProductId"];
 183                            DataTable MaxQty = ShopingCartComp.GetMaxProductQty(productid);
 184                            if (MaxQty.Rows.Count > 0)
 185                            {
 186                                if (!Convert.IsDBNull(MaxQty.Rows[0]["OrderMaximumQuantity"]))
 187                                {
 188                                    if ((Int32)OrderProducts.Rows[i]["Quantity"] > (Int32)MaxQty.Rows[0]["OrderMaximumQuantity"])
 189                                    {
 190                                        ResponseObj.message = "Max Quantiy Allowed for Purchase is : " + (Int32)MaxQty.Rows[0]["OrderMaximumQuantity"] + ".";
 191                                        ResponseObj.status = 0;
 192                                        return Request.CreateResponse(HttpStatusCode.OK, ResponseObj.message);
 193                                    }
 194                                }
 195                                if (!Convert.IsDBNull(MaxQty.Rows[0]["AllowedQuantities"]))
 196                                {
 197                                    if ((Int32)OrderProducts.Rows[i]["Quantity"] > (Int32)MaxQty.Rows[0]["AllowedQuantities"])
 198                                    {
 199                                        ResponseObj.message = "Allowed Quantiy for Purchase is : " + (Int32)MaxQty.Rows[0]["AllowedQuantities"] + ".";
 200                                        ResponseObj.status = 0;
 201                                        return Request.CreateResponse(HttpStatusCode.OK, ResponseObj.message);
 202                                    }
 203                                }
 204                                if (reorder.customerID != 0)
 205                                {
 206                                    //Checking given customerID is is valid or not
 207                                    DataTable customerIsValid = ShopingCartComp.CheckCustomerIsvalid(reorder.customerID);
 208                                    if (customerIsValid.Rows.Count == 0)
 209                                    {
 210                                        ResponseObj.message = "CustomerId is not valid.. Please provide vaild customerid";
 211                                        ResponseObj.status = 0;
 212                                    }
 213                                    else
 214                                    {
 215                                        // checking product had bundle items or not?
 216                                        DataTable ProdctBudles = ShopingCartComp.CheckProductIncluesBundle((Int32)OrderProducts.Rows[i]["ProductId"]);
 217                                        int? ParentItemId = null; int? BundleItemId = null;
 218                                        if (ProdctBudles.Rows.Count != 0)
 219                                        {
 220                                            int cnt = 0;
 221                                            string AttributesXml = "";
 222                                            DataTable checkprocutinCART = ShopingCartComp.AddShopingCartItem(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"]);
 223                                            if (checkprocutinCART.Rows.Count > 0)
 224                                            {
 225                                                long res = ShopingCartComp.UpdateCartItmes(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"], (Int32)OrderProducts.Rows[i]["Quantity"]);
 226                                            }
 227                                            else
 228                                            {
 229                                                long res = ShopingCartComp.AddShopingCartItem(reorder.customerID, ParentItemId, BundleItemId, (Int32)OrderProducts.Rows[i]["ProductId"], AttributesXml, (Int32)OrderProducts.Rows[i]["Quantity"]);
 230                                            }
 231
 232                                            int parentitem = 0;
 233                                            DataTable bundle = ShopingCartComp.GetParentItemID((Int32)OrderProducts.Rows[i]["ProductId"], reorder.customerID);
 234                                            parentitem = (Int32)bundle.Rows[0][0];
 235                                            for (int ki = 0; ki <= ProdctBudles.Rows.Count - 1; ki++)
 236                                            {
 237                                                //// inserting Product Varinat Combination
 238                                                string AttributesXm = "";
 239                                                long result = ShopingCartComp.AddShopingCartItem(reorder.customerID, parentitem, (Int32)ProdctBudles.Rows[ki]["Id"], (Int32)ProdctBudles.Rows[ki]["ProductId"], AttributesXm, (Int32)ProdctBudles.Rows[ki]["Quantity"]);
 240                                                cnt += 1;
 241                                            }
 242                                            if (cnt == ProdctBudles.Rows.Count)
 243                                            {
 244                                                ResponseObj.status = 1;
 245                                                ResponseObj.message = "Item Added to Cart Successfylly.";
 246                                            }
 247                                            else
 248                                            {
 249                                                ResponseObj.message = Common.OopsSomethingWentWrong;
 250                                                ResponseObj.status = 0;
 251                                            }
 252                                        }
 253                                        else
 254                                        {
 255                                            string AttributesXml = "";
 256                                            DataTable checkprocutinCART = ShopingCartComp.AddShopingCartItem(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"]);
 257                                            long res = 0;
 258                                            if (checkprocutinCART.Rows.Count > 0)
 259                                            {
 260                                                res = ShopingCartComp.UpdateCartItmes(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"], (Int32)OrderProducts.Rows[i]["Quantity"]);
 261                                            }
 262                                            else
 263                                            {
 264                                                res = ShopingCartComp.AddShopingCartItem(reorder.customerID, ParentItemId, BundleItemId, (Int32)OrderProducts.Rows[i]["ProductId"], AttributesXml, (Int32)OrderProducts.Rows[i]["Quantity"]);
 265                                            }
 266
 267                                            DataTable cartTotal = ShopingCartComp.cartTotal(reorder.customerID);
 268                                            if (res == 1)
 269                                            {
 270                                                DataTable productprice = ProductsComp.getProductDetails((Int32)OrderProducts.Rows[i]["ProductId"]);
 271                                                ResponseObj.status = 1;
 272                                                ResponseObj.message = "Item Added to Cart Successfylly.";
 273                                            }
 274                                            else
 275                                            {
 276                                                ResponseObj.message = Common.OopsSomethingWentWrong;
 277                                                ResponseObj.status = 0;
 278                                            }
 279                                        }
 280                                    }
 281                                }
 282                                else
 283                                {
 284                                    ResponseObj.message = "CustomerId is required";
 285                                    ResponseObj.status = 0;
 286                                }
 287                            }
 288                            else
 289                            {
 290                                ResponseObj.status = 1;
 291                                ResponseObj.message = "Poduct is not available.";
 292                            }
 293                        }
 294                    }
 295                   
 296                }
 297                else
 298                {
 299                    ResponseObj.status = 0;
 300                    ResponseObj.message = "Customer ID Required.";
 301                }
 302            }
 303            catch (Exception Err)
 304            {
 305
 306            }
 307            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
 308            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
 309            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
 310            return HttpResponseMessage;
 311        }
 312
 313
 314        [HttpGet]
 315        [Authorize]
 316        public HttpResponseMessage shoppingCartOrders(int id_customer,int start=0)
 317        {
 318            DataTable orders = new DataTable();
 319            ResponseObj ResponseObj = new ResponseObj();
 320            string response = "";
 321            try
 322            {
 323                
 324                if (id_customer > 0)
 325                {
 326                    int PageNumber = start; // Page Number
 327                    int RowsPerPage = 10; // fixed items to display in a page
 328                    orders = OrdersComp.getShopingCartOrders(id_customer, RowsPerPage, PageNumber );
 329                    DataTable orrd = new DataTable();
 330                    if (orders.Rows.Count > 0)
 331                    {
 332                        orrd = orders.Clone();
 333                        orrd.Columns["order_state"].DataType = typeof(System.String);
 334                        foreach (DataRow row in orders.Rows)
 335                        {
 336                            orrd.ImportRow(row);
 337                        }
 338                        for (int i=0;i<= orders.Rows.Count-1;i++)
 339                        {
 340                            if((Int32)orders.Rows[i]["order_state"]==10)
 341                            {
 342                                orrd.Rows[i]["id_order_state"] = 10;
 343                                orrd.Rows[i]["order_state"] = "Order Pending";
 344                                orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderPending"];
 345                            }
 346                            else if ((Int32)orders.Rows[i]["order_state"] == 20)
 347                            {
 348                                orrd.Rows[i]["id_order_state"] = 20;
 349                                orrd.Rows[i]["order_state"] = "Order Processing";
 350                                orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderProcessing"];
 351                            }
 352                            else if ((Int32)orders.Rows[i]["order_state"] == 30)
 353                            {
 354                                orrd.Rows[i]["id_order_state"] = 30;
 355                                orrd.Rows[i]["order_state"] = "Order Complete";
 356                                orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderComplete"];
 357                            }
 358                            
 359                            else
 360                            {
 361                                orrd.Rows[i]["id_order_state"] = 40;
 362                                orrd.Rows[i]["order_state"] = "Order Cancelled";
 363                                orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderCancelled"];
 364                            }
 365
 366                            if (orrd.Rows[i]["payment"].ToString().Contains("Payments.Prepayment"))
 367                            {
 368                                string str = orrd.Rows[i]["payment"].ToString();
 369                                Regex rx = new Regex("Payments.");
 370                                // replace all matches with empty strin
 371                                str = rx.Replace(str, "");
 372                                orrd.Rows[i]["payment"] = "Online Payment";
 373                            }
 374                            else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.CashOnDelivery"))
 375                            {
 376                                string str = orrd.Rows[i]["payment"].ToString();
 377                                Regex rx = new Regex("Payments.");
 378                                // replace all matches with empty strin
 379                                str = rx.Replace(str, "");
 380                                orrd.Rows[i]["payment"] = "Cash On Delivery";
 381                            }
 382                            else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.OnlinePayment"))
 383                            {
 384                                string str = orrd.Rows[i]["payment"].ToString();
 385                                Regex rx = new Regex("Payments.");
 386                                // replace all matches with empty strin
 387                                str = rx.Replace(str, "");
 388                                orrd.Rows[i]["payment"] = "Online Payment";
 389                            }
 390                            else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.PayInStore"))
 391                            {
 392                                string str = orrd.Rows[i]["payment"].ToString();
 393                                Regex rx = new Regex("Payments.");
 394                                // replace all matches with empty strin
 395                                str = rx.Replace(str, "");
 396                                orrd.Rows[i]["payment"] = "Pay In Store";
 397                            }
 398                            else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.PaymentMethod"))
 399                            {
 400                                string str = orrd.Rows[i]["payment"].ToString();
 401                                Regex rx = new Regex("Payments.");
 402                                // replace all matches with empty strin
 403                                str = rx.Replace(str, "");
 404                                orrd.Rows[i]["payment"] = "Online Payment";
 405                            }
 406                        }
 407                         
 408
 409                        ResponseObj.status = 1;
 410                        ResponseObj.message = Common.RecordsExists;
 411                        ResponseObj.result = orrd;
 412                    }
 413                    else
 414                    {
 415                        ResponseObj.status = 0;
 416                        ResponseObj.message = Common.NoRecordsExists;
 417                        ResponseObj.result = orrd;
 418                    }
 419                }
 420                else
 421                {
 422                    ResponseObj.status = 0;
 423                    ResponseObj.message = "orderID Required.";
 424                }
 425            }
 426            catch (Exception Err)
 427            {
 428
 429            }
 430            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
 431            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
 432            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
 433            return HttpResponseMessage;
 434        }
 435
 436
 437        [HttpGet]
 438        [Authorize]
 439        public HttpResponseMessage getOrderDetails(int customerID, int OrderID)
 440        {
 441            DataTable orders = new DataTable();
 442            ResponseObj ResponseObj = new ResponseObj();
 443            string response = "";
 444            try
 445            {
 446                if (OrderID > 0)
 447                {
 448                    orders = OrdersComp.getOrderDetails(customerID , OrderID);
 449
 450                    if (orders.Rows.Count > 0)
 451                    {
 452                        ResponseObj.status = 1;
 453                        ResponseObj.message = Common.RecordsExists;
 454                        ResponseObj.result = orders;
 455                    }
 456                    else
 457                    {
 458                        ResponseObj.status = 0;
 459                        ResponseObj.message = Common.NoRecordsExists;
 460                        ResponseObj.result = orders;
 461                    }
 462                }
 463                else
 464                {
 465                    ResponseObj.status = 0;
 466                    ResponseObj.message = "orderID Required.";
 467                }
 468            }
 469            catch (Exception Err)
 470            {
 471
 472            }
 473            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
 474            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
 475            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
 476            return HttpResponseMessage;
 477        }
 478
 479        [HttpGet]
 480        [Authorize]
 481        public HttpResponseMessage getProductNamesByOrderId(int id_customer, int id_order)
 482        {
 483            DataTable orders = new DataTable();
 484            ResponseObj ResponseObj = new ResponseObj();
 485            string response = "";
 486            try
 487            {
 488                if (id_customer > 0 && id_order >0)
 489                {
 490                    orders = OrdersComp.GetproductsInContactByOrderId(id_customer, id_order);
 491
 492                    if (orders.Rows.Count > 0)
 493                    {
 494                        ResponseObj.status = 1;
 495                        ResponseObj.message = Common.RecordsExists;
 496                        ResponseObj.result = orders;
 497                    }
 498                    else
 499                    {
 500                        ResponseObj.status = 0;
 501                        ResponseObj.message = Common.NoRecordsExists;
 502                        ResponseObj.result = orders;
 503                    }
 504                }
 505                else
 506                {
 507                    ResponseObj.status = 0;
 508                    ResponseObj.message = "OrderId is Required.";
 509                }
 510            }
 511            catch (Exception Err)
 512            {
 513
 514            }
 515            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
 516            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
 517            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
 518            return HttpResponseMessage;
 519        }
 520
 521        [HttpGet]
 522        [Authorize]
 523        public HttpResponseMessage orderReferencesByid(int id_customer)
 524        {
 525            DataTable orders = new DataTable();
 526            ResponseObj ResponseObj = new ResponseObj();
 527            string response = "";
 528            try
 529            {
 530                if (id_customer > 0 )
 531                {
 532                    orders = OrdersComp.orderReferencesByCustomerid(id_customer);
 533
 534                    if (orders.Rows.Count > 0)
 535                    {
 536                        ResponseObj.status = 1;
 537                        ResponseObj.message = Common.RecordsExists;
 538                        ResponseObj.result = orders;
 539                    }
 540                    else
 541                    {
 542                        ResponseObj.status = 0;
 543                        ResponseObj.message = Common.NoRecordsExists;
 544                        ResponseObj.result = orders;
 545                    }
 546                }
 547                else
 548                {
 549                    ResponseObj.status = 0;
 550                    ResponseObj.message = "CustomerId is Required.";
 551                }
 552            }
 553            catch (Exception Err)
 554            {
 555
 556            }
 557            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
 558            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
 559            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
 560            return HttpResponseMessage;
 561        }
 562
 563
 564        [HttpGet]
 565        [Authorize]
 566        public HttpResponseMessage getOrderDetailsByOrderId(int OrderID)
 567        {
 568           // DataTable orders = new DataTable();
 569            OrderDetailsByOrderidResponseObj ResponseObj = new OrderDetailsByOrderidResponseObj();
 570            string response = "";
 571            try
 572            {
 573                if (OrderID > 0)
 574                {
 575                    DataTable orders = OrdersComp.getOrderDetailsbyOrderId(OrderID);
 576                    DataTable deliveryAddress = OrdersComp.GetDeliveryAddressbyOrderID((Int32)orders.Rows[0]["addressid"],OrderID);
 577                    DataTable orrd = new DataTable();
 578                    DataTable OrderDetails = OrdersComp.GetOrderDetailsWithOrderId((Int32)orders.Rows[0]["id_customer"], OrderID);
 579                    if (orders.Rows.Count > 0)
 580                    {
 581                       try
 582                        {
 583                            orrd = orders.Clone();
 584                            orrd.Columns["id_image"].DataType = typeof(System.String);
 585                            orrd.Columns["imageLink"].DataType = typeof(System.String);
 586                            foreach (DataRow row in orders.Rows)
 587                            {
 588                                orrd.ImportRow(row);
 589                            }
 590
 591                            if (orrd.Rows.Count > 0)
 592                            {
 593                                for (int i = 0; i <= orrd.Rows.Count - 1; i++)
 594                                {
 595                                    DataTable storedetails = PasswordComp.StoreInformation();
 596                                    DataTable getImagesLinks = ProductsComp.GetImageFullNames((Int32)orders.Rows[i]["id_image"]);
 597                                    string mimetype = "";
 598
 599                                    var imgurl = storedetails.Rows[0]["Url"].ToString();
 600                                    if ((getImagesLinks.Rows[0]["MimeType"].ToString()).Contains("image/jpeg"))
 601                                    {
 602                                        mimetype = ".jpg";
 603                                    }
 604                                    else if ((getImagesLinks.Rows[0]["MimeType"].ToString()).Contains("image/png"))
 605                                    {
 606                                        mimetype = ".png";
 607                                    }
 608                                    string imgId = getImagesLinks.Rows[0]["Id"].ToString();
 609                                    string imgName = getImagesLinks.Rows[0]["SeoFilename"].ToString();
 610                                    orrd.Rows[i]["imageLink"] = imgurl + "/media/image/" + imgId + "/" + imgName + mimetype + "";
 611                                    //orrd.Rows[i]["imageLink"] = imgurl + "" + imgName;
 612                                    
 613                                    //replacing html strings
 614                                    string str = orrd.Rows[i]["description"].ToString();
 615                                    Regex rx = new Regex("<[^>]*>");
 616                                    // replace all matches with empty strin
 617                                    str = rx.Replace(str, "");
 618                                    RegexOptions options = RegexOptions.None;
 619                                    Regex regex = new Regex("[ ]{2,}", options);
 620                                    str = regex.Replace(str, " ");
 621                                    str = str.Trim();
 622                                    orrd.Rows[i]["description"] = str;
 623                                }
 624                            }
 625                        }
 626                        catch (Exception Err) { }
 627                        DataTable orderDett = new DataTable();
 628                        try
 629                        {
 630                            orderDett = OrderDetails.Clone();
 631                            orderDett.Columns["order_state"].DataType = typeof(System.String);
 632                            orderDett.Columns["date_add"].DataType = typeof(System.String);
 633                            foreach (DataRow row in OrderDetails.Rows)
 634                            {
 635                                orderDett.ImportRow(row);
 636                            }
 637                            for (int i = 0; i <= OrderDetails.Rows.Count - 1; i++)
 638                            {
 639                                DateTime OrderDate = (DateTime)orderDett.Rows[i]["date_add"];
 640                                //DateTime utcTime = walletdate.ToLocalTime();
 641                                var istdate = TimeZoneInfo.ConvertTimeFromUtc(OrderDate, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
 642
 643                                string walletDT = istdate.ToString("yyyy-MM-dd HH:mm:ss");
 644                                orderDett.Rows[i]["date_add"] = walletDT;
 645
 646                                if ((Int32)OrderDetails.Rows[i]["order_state"] == 10)
 647                                {
 648                                    orderDett.Rows[i]["id_order_state"] = 10;
 649                                    orderDett.Rows[i]["order_state"] = "Order Pending";
 650                                    orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderPending"];
 651                                }
 652                                else if ((Int32)OrderDetails.Rows[i]["order_state"] == 20)
 653                                {
 654                                    orderDett.Rows[i]["id_order_state"] = 20;
 655                                    orderDett.Rows[i]["order_state"] = "Order Processing";
 656                                    orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderProcessing"];
 657                                }
 658                                else if ((Int32)OrderDetails.Rows[i]["order_state"] == 30)
 659                                {
 660                                    orderDett.Rows[i]["id_order_state"] = 30;
 661                                    orderDett.Rows[i]["order_state"] = "Order Complete";
 662                                    orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderComplete"];
 663                                }
 664
 665                                else
 666                                {
 667                                    orderDett.Rows[i]["id_order_state"] = 40;
 668                                    orderDett.Rows[i]["order_state"] = "Order Cancelled";
 669                                    orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderCancelled"];
 670                                }
 671
 672                                if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.Prepayment"))
 673                                {
 674                                    string str = orderDett.Rows[i]["payment"].ToString();
 675                                    Regex rx = new Regex("Payments.");
 676                                    // replace all matches with empty strin
 677                                    str = rx.Replace(str, "");
 678                                    orderDett.Rows[i]["payment"] = "Online Payment";
 679                                }
 680                                else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.CashOnDelivery"))
 681                                {
 682                                    string str = orderDett.Rows[i]["payment"].ToString();
 683                                    Regex rx = new Regex("Payments.");
 684                                    // replace all matches with empty strin
 685                                    str = rx.Replace(str, "");
 686                                    orderDett.Rows[i]["payment"] = "Cash On Delivery";
 687                                }
 688                                else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.OnlinePayment"))
 689                                {
 690                                    string str = orderDett.Rows[i]["payment"].ToString();
 691                                    Regex rx = new Regex("Payments.");
 692                                    // replace all matches with empty strin
 693                                    str = rx.Replace(str, "");
 694                                    orderDett.Rows[i]["payment"] = "Online Payment";
 695                                }
 696                                else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.PayInStore"))
 697                                {
 698                                    string str = orderDett.Rows[i]["payment"].ToString();
 699                                    Regex rx = new Regex("Payments.");
 700                                    // replace all matches with empty strin
 701                                    str = rx.Replace(str, "");
 702                                    orderDett.Rows[i]["payment"] = "Pay In Store";
 703                                }
 704                                else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.PaymentMethod"))
 705                                {
 706                                    string str = orderDett.Rows[i]["payment"].ToString();
 707                                    Regex rx = new Regex("Payments.");
 708                                    // replace all matches with empty strin
 709                                    str = rx.Replace(str, "");
 710                                    orderDett.Rows[i]["payment"] = "Online Payment";
 711                                }
 712                            }
 713                        }
 714                        catch (Exception ER)
 715                        {
 716
 717                        }
 718
 719                        if (deliveryAddress.Rows.Count > 0)
 720
 721                        {
 722                            string JSONresult;
 723                            JSONresult = JsonConvert.SerializeObject(deliveryAddress);
 724                            JSONresult = JSONresult.Replace("[", "");
 725                            JSONresult = JSONresult.Replace("]", "");
 726                            JObject jsonObject = JObject.Parse(JSONresult);
 727                            ResponseObj.deliveryAddress = jsonObject;
 728                        }
 729                        ResponseObj.status = 1;
 730                        ResponseObj.message = Common.RecordsExists;
 731                        
 732                        ResponseObj.delivery_days = "2-5 working days";
 733                        //ResponseObj.orderDetails = OrderDetails;
 734                        ResponseObj.orderDetails = orderDett;
 735                        ResponseObj.result = orrd;
 736                    }
 737                    else
 738                    {
 739                        ResponseObj.status = 0;
 740                        ResponseObj.message = Common.NoRecordsExists;
 741                        ResponseObj.result = orrd;
 742                    }
 743                }
 744                else
 745                {
 746                    ResponseObj.status = 0;
 747                    ResponseObj.message = "orderID Required.";
 748                }
 749            }
 750            catch (Exception Err)
 751            {
 752
 753            }
 754            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
 755            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
 756            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
 757            return HttpResponseMessage;
 758        }
 759
 760        [HttpPost]
 761        [Authorize]
 762        public HttpResponseMessage CreateOrder([FromBody][Required]CreateOrder createOrder)
 763        {
 764            CreateOrderResponseObj ResponseObj = new CreateOrderResponseObj();
 765            InsufficientRechargeFundsObj ISRFObj = new InsufficientRechargeFundsObj();
 766            string response = "";
 767            try
 768            {
 769                if (createOrder != null)
 770                {
 771                    if (ModelState.IsValid)
 772                    {
 773                        ConfirmOrder confirmOrder = new ConfirmOrder();
 774                        InsertOrderItems insertOrderItems = new InsertOrderItems();
 775                        DataTable getaddressofcustomer = OrdersComp.getcustomeraddress(createOrder.id_customer, createOrder.id_address_delivery);
 776                        if (getaddressofcustomer.Rows.Count > 0)
 777                        {
 778                            int Customerid = createOrder.id_customer;
 779                            // checking bundle items are available in cart or not
 780                            DataTable dtr = OrdersComp.CheckBundleIteminCart(Customerid);
 781                            bool bundleitem = false;
 782                            if (dtr.Rows.Count > 0)
 783                            {
 784                                for (int i = 0; i <= dtr.Rows.Count - 1; i++)
 785                                {
 786                                    CartSubTotal = decimal.Zero;
 787                                    CartSubTotalInclTax = decimal.Zero;
 788                                    CartSubTotalExclTax = decimal.Zero;
 789                                    bundleitem = (bool)dtr.Rows[i][0];
 790                                    //Checking Product Stock availability before purchase
 791                                    MaxQty = OrdersComp.GetCartItemsBeforeOrder(Customerid, bundleitem);
 792
 793                                    if (MaxQty.Rows.Count > 0)
 794                                    {
 795
 796                                        foreach (DataRow dr in MaxQty.Rows)
 797                                        {
 798                                            if ((Int32)(dr["StockQuantity"]) < (Int32)(dr["Quantity"]))
 799                                            {
 800                                                ResponseObj.message = "Product Qty is not Available in Stock.";
 801                                                ResponseObj.status = 2;
 802                                            }
 803                                            else
 804                                            {
 805                                                GetCartSubTotal(dr);
 806                                            }
 807                                            CartSubTotal += ProductFinalCost;
 808                                            CartSubTotalInclTax += ProductFinalCostInclTax;
 809                                            CartSubTotalExclTax += ProductFinalCostExclTax;
 810                                        }
 811
 812                                        try
 813                                        {
 814                                            // MyIPAddress = new WebClient().DownloadString("http://icanhazip.com");
 815                                            MyIPAddress = Common.IPaddress;
 816                                        }
 817                                        catch (Exception Err) { }
 818
 819
 820                                        #region ORDER Data
 821                                        confirmOrder.StoreId = 1;
 822                                        confirmOrder.CustomerId = createOrder.id_customer;
 823                                        confirmOrder.BillingAddressId = createOrder.id_address_delivery;
 824                                        confirmOrder.ShippingAddressId = createOrder.id_address_delivery;
 825                                        confirmOrder.OrderStatusId = 10;
 826                                        confirmOrder.ShippingStatusId = 20;
 827                                        confirmOrder.PaymentStatusId = 10;
 828                                        confirmOrder.PaymentMethodSystemName = "Cash On Delivery";
 829                                        confirmOrder.CustomerCurrencyCode = "INR";
 830                                        confirmOrder.CurrencyRate = 1;
 831                                        confirmOrder.CustomerTaxDisplayTypeId = 10;
 832                                        confirmOrder.VatNumber = "";
 833                                        confirmOrder.OrderSubtotalInclTax = CartSubTotalInclTax;
 834                                        confirmOrder.OrderSubtotalExclTax = CartSubTotalExclTax;
 835                                        confirmOrder.OrderSubTotalDiscountInclTax = 0;
 836                                        confirmOrder.OrderSubTotalDiscountExclTax = 0;
 837                                        confirmOrder.OrderShippingInclTax = 0;
 838                                        confirmOrder.OrderShippingExclTax = 0;
 839                                        confirmOrder.PaymentMethodAdditionalFeeInclTax = 0;
 840                                        confirmOrder.PaymentMethodAdditionalFeeExclTax = 0;
 841                                        confirmOrder.TaxRates = "0:0;";
 842                                        confirmOrder.OrderTax = 0;
 843                                        confirmOrder.OrderDiscount = 0;
 844                                        confirmOrder.OrderTotal = CartSubTotal;
 845                                        confirmOrder.RefundedAmount = 0;
 846                                        confirmOrder.RewardPointsWereAdded = false;
 847                                        confirmOrder.CheckoutAttributeDescription = "";
 848                                        confirmOrder.CheckoutAttributesXml = "";
 849                                        confirmOrder.CustomerLanguageId = 1;
 850                                        confirmOrder.AffiliateId = 1;
 851                                        confirmOrder.CustomerIp = MyIPAddress;
 852                                        confirmOrder.AllowStoringCreditCardNumber = false;
 853                                        confirmOrder.CardType = "";
 854                                        confirmOrder.CardName = "";
 855                                        confirmOrder.CardNumber = "";
 856                                        confirmOrder.MaskedCreditCardNumber = "";
 857                                        confirmOrder.CardCvv2 = "";
 858                                        confirmOrder.CardExpirationMonth = "";
 859                                        confirmOrder.CardExpirationYear = "";
 860                                        confirmOrder.AllowStoringDirectDebit = false;
 861                                        confirmOrder.DirectDebitAccountHolder = "";
 862                                        confirmOrder.DirectDebitAccountNumber = "";
 863                                        confirmOrder.DirectDebitBankCode = "";
 864                                        confirmOrder.DirectDebitBankName = "";
 865                                        confirmOrder.DirectDebitBIC = "";
 866                                        confirmOrder.DirectDebitCountry = "";
 867                                        confirmOrder.DirectDebitIban = "";
 868                                        confirmOrder.AuthorizationTransactionId = "";
 869                                        confirmOrder.AuthorizationTransactionCode = "";
 870                                        confirmOrder.AuthorizationTransactionResult = "";
 871                                        confirmOrder.CaptureTransactionId = "";
 872                                        confirmOrder.CaptureTransactionResult = "";
 873                                        confirmOrder.SubscriptionTransactionId = "";
 874                                        confirmOrder.PurchaseOrderNumber = "";
 875                                        confirmOrder.PaidDateUtc = DateTime.Now;
 876                                        confirmOrder.ShippingMethod = "By Ground";
 877                                        confirmOrder.ShippingRateComputationMethodSystemName = "FixedRate";
 878                                        confirmOrder.Deleted = false;
 879                                        confirmOrder.CreatedOnUtc = DateTime.Now;
 880                                        confirmOrder.UpdatedOnUtc = DateTime.Now;
 881                                        confirmOrder.RewardPointsRemaining = 0;
 882                                        confirmOrder.CustomerOrderComment = "";
 883                                        confirmOrder.OrderShippingTaxRate = 0;
 884                                        confirmOrder.PaymentMethodAdditionalFeeTaxRate = 0;
 885                                        confirmOrder.HasNewPaymentNotification = false;
 886                                        confirmOrder.AcceptThirdPartyEmailHandOver = false;
 887                                        confirmOrder.OrderTotalRounding = 0;
 888                                        confirmOrder.order_from = createOrder.order_from;
 889                                        #endregion ORDER Data 
 890
 891
 892                                        long res = OrdersComp.ConfirmOrder(confirmOrder.StoreId, confirmOrder.CustomerId, confirmOrder.BillingAddressId, confirmOrder.ShippingAddressId, confirmOrder.OrderStatusId, confirmOrder.ShippingStatusId, confirmOrder.PaymentStatusId, confirmOrder.PaymentMethodSystemName, confirmOrder.CustomerCurrencyCode, confirmOrder.CurrencyRate, confirmOrder.
 893                                                                            CustomerTaxDisplayTypeId, confirmOrder.VatNumber, confirmOrder.OrderSubtotalInclTax, confirmOrder.OrderSubtotalExclTax, confirmOrder.OrderSubTotalDiscountInclTax, confirmOrder.OrderSubTotalDiscountExclTax, confirmOrder.OrderShippingInclTax, confirmOrder.OrderShippingExclTax, confirmOrder.
 894                                                                            PaymentMethodAdditionalFeeInclTax, confirmOrder.PaymentMethodAdditionalFeeExclTax, confirmOrder.TaxRates, confirmOrder.OrderTax, confirmOrder.OrderDiscount, confirmOrder.OrderTotal, confirmOrder.RefundedAmount, confirmOrder.RewardPointsWereAdded, confirmOrder.CheckoutAttributeDescription, confirmOrder.CheckoutAttributesXml, confirmOrder.
 895                                                                            CustomerLanguageId, confirmOrder.AffiliateId, confirmOrder.CustomerIp, confirmOrder.AllowStoringCreditCardNumber, confirmOrder.CardType, confirmOrder.CardName, confirmOrder.CardNumber, confirmOrder.MaskedCreditCardNumber, confirmOrder.CardCvv2, confirmOrder.CardExpirationMonth, confirmOrder.CardExpirationYear, confirmOrder.AllowStoringDirectDebit, confirmOrder.
 896                                                                            DirectDebitAccountHolder, confirmOrder.DirectDebitAccountNumber, confirmOrder.DirectDebitBankCode, confirmOrder.DirectDebitBankName, confirmOrder.DirectDebitBIC, confirmOrder.DirectDebitCountry, confirmOrder.DirectDebitIban, confirmOrder.AuthorizationTransactionId, confirmOrder.AuthorizationTransactionCode, confirmOrder.
 897                                                                            AuthorizationTransactionResult, confirmOrder.CaptureTransactionId, confirmOrder.CaptureTransactionResult, confirmOrder.SubscriptionTransactionId, confirmOrder.PurchaseOrderNumber, confirmOrder.PaidDateUtc, confirmOrder.ShippingMethod, confirmOrder.ShippingRateComputationMethodSystemName, confirmOrder.Deleted, confirmOrder.
 898                                                                            CreatedOnUtc, confirmOrder.UpdatedOnUtc, confirmOrder.RewardPointsRemaining, confirmOrder.CustomerOrderComment, confirmOrder.OrderShippingTaxRate, confirmOrder.PaymentMethodAdditionalFeeTaxRate, confirmOrder.HasNewPaymentNotification, confirmOrder.AcceptThirdPartyEmailHandOver, confirmOrder.OrderTotalRounding, createOrder.order_from);
 899
 900
 901                                        //Insert data in OrderItem table
 902
 903                                        foreach (DataRow dr2 in MaxQty.Rows)
 904                                        {
 905                                            //calculating cart subtotal value
 906                                            GetCartSubTotal(dr2);
 907
 908                                            #region OrderItem Data
 909                                            insertOrderItems.ProductId = (Int32)dr2["ProductId"];
 910                                            insertOrderItems.Quantity = (Int32)dr2["Quantity"];
 911                                            insertOrderItems.UnitPriceInclTax = (decimal)dr2["Price"];
 912                                            insertOrderItems.UnitPriceExclTax = (decimal)dr2["Price"];
 913                                            insertOrderItems.PriceInclTax = ProductFinalCostInclTax;
 914                                            insertOrderItems.PriceExclTax = ProductFinalCostExclTax;
 915                                            insertOrderItems.DiscountAmountInclTax = 0;
 916                                            insertOrderItems.DiscountAmountExclTax = 0;
 917                                            insertOrderItems.AttributeDescription = "";
 918                                            insertOrderItems.AttributesXml = dr2["AttributesXml"].ToString();
 919                                            insertOrderItems.DownloadCount = 0;
 920                                            insertOrderItems.IsDownloadActivated = false;
 921                                            insertOrderItems.LicenseDownloadId = 0;
 922                                            insertOrderItems.ItemWeight = 0;
 923                                            insertOrderItems.BundleData = "";
 924                                            insertOrderItems.ProductCost = 0;
 925                                            insertOrderItems.TaxRate = 0;
 926
 927                                            #endregion OrderItem Data
 928
 929                                            int CustomerId = confirmOrder.CustomerId;
 930                                            long res1 = OrdersComp.InsertOrderItemsData(CustomerId, insertOrderItems.ProductId, insertOrderItems.Quantity, insertOrderItems.UnitPriceInclTax, insertOrderItems.UnitPriceExclTax, insertOrderItems.PriceInclTax, insertOrderItems.PriceExclTax, insertOrderItems.DiscountAmountInclTax, insertOrderItems.DiscountAmountExclTax, insertOrderItems.AttributeDescription,
 931                                                                                       insertOrderItems.AttributesXml, insertOrderItems.DownloadCount, insertOrderItems.IsDownloadActivated, insertOrderItems.LicenseDownloadId, insertOrderItems.ItemWeight, insertOrderItems.BundleData, insertOrderItems.ProductCost, insertOrderItems.TaxRate);
 932                                            RemoveFromCart(Customerid);
 933                                            UpdateProductStock((Int32)dr2["ProductId"], (Int32)dr2["Quantity"]);
 934                                        }
 935
 936
 937                                        if (res > 0)
 938                                        {
 939                                            if (createOrder.useFromWallet == 1)
 940                                            {
 941                                                float currentbal = Wallet.getCustomerCurrentWalletBalance(createOrder.id_customer);
 942                                                if (currentbal >= (Int32)CartSubTotal)
 943                                                {
 944                                                    float PrsntBlnc = currentbal - Convert.ToInt32(CartSubTotal);
 945                                                    //deducting the wallet balance
 946                                                    Wallet.saveWalletBalance(createOrder.id_customer.ToString(), res.ToString(), CartSubTotal.ToString(), PrsntBlnc.ToString(), 2, 2, MyIPAddress, "Place Order Using COD with Wallet ");
 947                                                    ResponseObj.status = 1;
 948                                                    ResponseObj.message = "Order Placed Successfully";
 949                                                    ResponseObj.order_id = res;
 950                                                }
 951                                                else
 952                                                {
 953                                                    float PrsntBlnc = currentbal - Convert.ToInt32(CartSubTotal);
 954                                                    if (PrsntBlnc < 0)
 955                                                    {
 956                                                        PrsntBlnc = 0;
 957                                                    }
 958                                                    //deducting the wallet balance
 959                                                    Wallet.saveWalletBalance(createOrder.id_customer.ToString(), res.ToString(), currentbal.ToString(), PrsntBlnc.ToString(), 2, 2, MyIPAddress, "Place Order Using COD with Wallet ");
 960                                                    ResponseObj.status = 1;
 961                                                    ResponseObj.message = "Order Placed Successfully";
 962                                                    ResponseObj.order_id = res;
 963                                                }
 964                                            }
 965                                            else
 966                                            {
 967                                                ResponseObj.status = 1;
 968                                                ResponseObj.message = "Order Placed Successfully";
 969                                                ResponseObj.order_id = res;
 970                                            }
 971                                        }
 972                                        else
 973                                        {
 974                                            ResponseObj.message = Common.OopsSomethingWentWrong;
 975                                            ResponseObj.status = 0;
 976                                        }
 977                                    }
 978                                    else
 979                                    {
 980                                        ResponseObj.message = "Cart is Empty.. Please add items to cart before place order";
 981                                        ResponseObj.status = 0;
 982
 983                                    }
 984                                }
 985                            }
 986                            else
 987                            {
 988                                ResponseObj.message = "Cart is Empty.. Please add items to cart before place order";
 989                                ResponseObj.status = 0;
 990                            }
 991                        }
 992                        else
 993                        {
 994                            ResponseObj.message = "id_address_delivery does not belogs to the customer";
 995                            ResponseObj.status = 0;
 996                        }
 997                    }
 998                    else
 999                    {
1000                        var error = ModelState.SelectMany(x => x.Value.Errors).First();
1001                        if (error.ErrorMessage != null && error.ErrorMessage != String.Empty)
1002                            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error.ErrorMessage);
1003
1004                        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
1005                    }
1006                }
1007                else
1008                {
1009                    ResponseObj.message = Common.OopsSomethingWentWrong;
1010                    ResponseObj.status = 0;
1011                }
1012            }
1013            catch (Exception Err)
1014            {
1015
1016            }
1017            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
1018            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
1019            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
1020            return HttpResponseMessage;
1021        }
1022        [NonAction]
1023        public Decimal GetOrderTotalInclTax(DataTable dataTable)
1024        {
1025            result = 0;
1026            return result;
1027        }
1028        [NonAction]
1029        public Decimal GetOrderTotalExclTax(DataTable dataTable)
1030        {
1031            result = 0;
1032            return result;
1033        }
1034        [NonAction]
1035        public decimal GetCartSubTotal(DataRow dataRow)
1036        {
1037               result = 0;
1038            try
1039            {
1040                if (dataRow["SpecialPrice"].ToString() == "")
1041                {
1042                    string str = dataRow["AttributesXml"].ToString();
1043                    Product_GetPriceAdjustment(str);
1044                    GetTaxRate((Int32)dataRow["id"]);
1045                    //Checking Tier Price for the product
1046                    if ((bool) dataRow["HasTierPrices"]==true)
1047                    {
1048                        GetTierProdutTierPrice((Int32)dataRow["id"], (Int32)dataRow["Quantity"]);
1049                    }
1050                    if(ProductTierPrice !=decimal.Zero)
1051                    {
1052                        ProductInitialPrice = ProductTierPrice;
1053                    }
1054                    else
1055                    {
1056                        ProductInitialPrice = (decimal)dataRow["Price"];
1057                    }
1058                    ProductFinalCost = decimal.Zero;
1059                    ProductFinalCost = decimal.Multiply((ProductInitialPrice + ProductAdjPrice), (Int32)dataRow["Quantity"]);
1060                    //ProductFinalCost = decimal.Multiply(((decimal)dataRow["Price"] + ProductAdjPrice - (decimal)dataRow["Discount"]), (Int32)dataRow["Quantity"]);
1061                    ProductFinalCostExclTax = ProductFinalCost;
1062                    ProductFinalCostInclTax = ProductFinalCost * (1 + taxrate / 100);
1063                }
1064                else
1065                {
1066                    string str = dataRow["AttributesXml"].ToString();
1067                    Product_GetPriceAdjustment(str);
1068                    GetTaxRate((Int32)dataRow["id"]);
1069                    ProductFinalCost = decimal.Zero;
1070                    //ProductFinalCost = decimal.Multiply(((decimal)dataRow["SpecialPrice"] + ProductAdjPrice - (decimal)dataRow["Discount"]), (Int32)dataRow["Quantity"]);
1071                    ProductFinalCost = decimal.Multiply(((decimal)dataRow["Price"] + ProductAdjPrice ), (Int32)dataRow["Quantity"]);
1072                    ProductFinalCostExclTax = ProductFinalCost;
1073                    ProductFinalCostInclTax = ProductFinalCost * (1 + taxrate / 100);
1074                }
1075            }
1076            catch (Exception Err)
1077            {
1078
1079            }
1080           
1081            return CartSubTotal;
1082        }
1083        
1084        [NonAction]
1085        private decimal Product_GetPriceAdjustment(string  attribute )
1086        {
1087            ProductAdjPrice = decimal.Zero;
1088            try
1089            {
1090                if (attribute != "")
1091                {
1092                    var attributesXml = attribute.ToString();
1093                    var doc = XDocument.Parse(attributesXml);
1094
1095                    // Attributes/ProductVariantAttribute
1096                    foreach (var node1 in doc.Descendants("ProductVariantAttribute"))
1097                    {
1098                        string ID = node1.Attribute("ID").Value;
1099                        int ir = int.Parse(ID);
1100                        // ProductVariantAttributeValue/Value
1101                        foreach (int node2 in node1.Descendants("Value"))
1102                        {
1103                            int Val = node2;
1104                            dt2 = GetPriceAjustments(ir, Val);
1105                            if (dt2.Rows.Count > 0)
1106                            {
1107                                decimal AdditionalPrice = decimal.Zero;
1108                                AdditionalPrice = (decimal)dt2.Rows[0][0];
1109                                ProductAdjPrice += AdditionalPrice;
1110                            }
1111                        }
1112                    }
1113                }
1114            }
1115            catch (Exception Err)
1116            {
1117
1118            }
1119            return result;
1120
1121        }
1122        [NonAction]
1123        private DataTable GetPriceAjustments(int  ID, int Value)
1124        {
1125
1126            dt2 = OrdersComp.GetPriceAdjnustment(ID, Value);
1127           
1128            return dt2;
1129        }
1130
1131        [NonAction ]
1132        private decimal GetTaxRate(int  productID)
1133        {
1134            taxrate = decimal.Zero;
1135            try
1136            {
1137                DataTable dt1 = OrdersComp.GetProductTaxCategory(productID);
1138
1139                if (dt1.Rows.Count > 0 && (bool)dt1.Rows[0]["IsTaxExempt"] == false)
1140                {
1141                    taxrate = (decimal)dt1.Rows[0]["Percentage"];
1142                }
1143                else if (dt1.Rows.Count > 0 && (bool)dt1.Rows[0]["IsTaxExempt"] == true)
1144                {
1145                    taxrate = 0;
1146                }
1147            }
1148            catch (Exception Err)
1149            {
1150
1151            }
1152            return result=taxrate;
1153        }
1154
1155
1156        [NonAction]
1157        private void RemoveFromCart(int CustomerID)
1158        {
1159            try
1160            {
1161                long res = OrdersComp.RemoveFromCart(CustomerID);
1162            }
1163            catch (Exception Err)
1164            {
1165
1166            }
1167           
1168        }
1169
1170
1171        [NonAction]
1172        private void   UpdateProductStock(int ProductId, int Qty)
1173        {
1174           
1175            try
1176            {
1177              long res = OrdersComp.UpdateProductStock(ProductId, Qty);
1178            }
1179            catch (Exception Err)
1180            {
1181
1182            }
1183          
1184        }
1185        [NonAction]
1186        private void GetTierProdutTierPrice(int ProductId, int Qty)
1187        {
1188            try
1189            {
1190                DataTable dt1 = OrdersComp.GetTierPrice(ProductId);
1191                if(dt1.Rows.Count > 0)
1192                {
1193                   for(int i=0;i<=dt1.Rows.Count-1;i++)
1194                    {
1195                        if(Qty >= (Int32) dt1.Rows[i]["Quantity"] )
1196                        {
1197                            ProductTierPrice = (decimal)dt1.Rows[i]["TierPrice"];
1198                        }
1199                    }
1200                }
1201                else
1202                {
1203                    ProductTierPrice = decimal.Zero;
1204                }
1205            }
1206            catch (Exception Err)
1207            {
1208
1209            }
1210        }
1211
1212        [HttpPost]
1213        [Authorize]
1214        public HttpResponseMessage CreateOrderUsingPayment([FromBody][Required]CreateOrderUsingPayment createOrderUsingPayment)
1215        {
1216            CreateOrderPaymentResponseObj ResponseObj = new CreateOrderPaymentResponseObj();
1217            HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
1218            string response = "";
1219            try
1220            {
1221                if (createOrderUsingPayment != null)
1222                {
1223                    if (ModelState.IsValid)
1224                    {
1225                        string orderid = "";
1226                        if (createOrderUsingPayment.order_id != "" && createOrderUsingPayment.order_id != "0" && createOrderUsingPayment.order_id != null)
1227                        {
1228                            string sub = createOrderUsingPayment.order_id.Substring(0, 3);
1229                            if (sub  == "odr")
1230                            {
1231                                orderid = createOrderUsingPayment.order_id.Substring(3);
1232                            }
1233
1234                        }
1235
1236                        response = PlaceOrder.CreateOrderWithPayment(createOrderUsingPayment.id_customer.ToString(), createOrderUsingPayment.id_address_delivery.ToString(), createOrderUsingPayment.useFromWallet.ToString(), createOrderUsingPayment.order_from, orderid);
1237                        HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
1238                        return HttpResponseMessage;
1239                    }
1240                    else
1241                    {
1242                        var error = ModelState.SelectMany(x => x.Value.Errors).First();
1243                        if (error.ErrorMessage != null && error.ErrorMessage != String.Empty)
1244                            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error.ErrorMessage);
1245
1246                        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
1247                    }
1248                }
1249                else
1250                {
1251                    createorderPaymentResult resul = new createorderPaymentResult();
1252                    resul.message= Common.OopsSomethingWentWrong;
1253                    ResponseObj.result = resul;
1254                    ResponseObj.status = 0;
1255                }
1256            }
1257            catch (Exception Err)
1258            {
1259
1260            }
1261            
1262            response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
1263            HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
1264            return HttpResponseMessage;
1265        }
1266
1267
1268        
1269
1270    }
1271}