/testwebapi/Controllers/OrdersController.cs
C# | 1271 lines | 1136 code | 103 blank | 32 comment | 134 complexity | 0dbb8acbea18b2c34495fc497e3a3be8 MD5 | raw file
- using CompLibrary;
- using DBLibrary;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Data;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Text;
- using System.Web.Http;
- using Pay2CartAPI.Models;
- using Pay2CartAPI.Response;
- using System.Xml.Linq;
- using Pay2CartAPI.Classes;
- using Pay2CartAPI.WalletService;
- using System.Configuration;
- using Newtonsoft.Json.Linq;
- using System.Text.RegularExpressions;
- namespace Pay2CartAPI.Controllers
- {
-
- public class OrdersController : ApiController
- {
- public string response = "";
- public DataTable MaxQty;
- public decimal result = decimal.Zero;
- public string MyIPAddress = "";
- public DataTable dt;
- public DataTable dt2;
- public decimal ProductInitialPrice = decimal.Zero;
- public decimal ProductAdjPrice = decimal.Zero;
- public decimal ProductFinalCost = decimal.Zero;
- public decimal ProductFinalCostInclTax = decimal.Zero;
- public decimal ProductFinalCostExclTax = decimal.Zero;
- public decimal CartSubTotal = decimal.Zero;
- public decimal CartSubTotalInclTax = decimal.Zero;
- public decimal CartSubTotalExclTax = decimal.Zero;
- public decimal taxrate = decimal.Zero;
- public decimal ProductTierPrice = decimal.Zero;
- [HttpPost]
- [Authorize]
- public HttpResponseMessage Summary([FromBody]Summary summary)
- {
- SummaryResponseObj ResponseObj = new SummaryResponseObj();
- string response = "";
- try
- {
- if (ModelState.IsValid)
- {
- DataTable priceDet = new DataTable();
- priceDet.Columns.Add("value",typeof(System.Int32));
- priceDet.Columns.Add("name");
- DataTable dtr = OrdersComp.CheckBundleIteminCart(summary.id_customer);
- DataTable paymentmethods = OrdersComp.Paymentmethods(summary.id_customer);
- DataTable paymentMethod = new DataTable();
- paymentMethod.Columns.Add("value");
- paymentMethod.Columns.Add("name");
- if (paymentmethods.Rows.Count>0)
- {
- for(int i=0;i<= paymentmethods.Rows.Count-1;i++)
- {
- if(paymentmethods.Rows[i]["name"].ToString().Contains("OnlinePayment"))
- {
- paymentMethod.Rows.Add("ccavenue", "Online Payment");
- }
- if (paymentmethods.Rows[i]["name"].ToString().Contains("CashOnDelivery"))
- {
- paymentMethod.Rows.Add("cod", "Cash On Delivery");
- }
- }
- }
- DataTable pricingDetails = OrdersComp.Pricedetails(summary.id_customer);
- pricingDetails.Columns.Add("Total");
- int sumAmount = 0;
- if(pricingDetails.Rows.Count>0)
- {
- int sum = Convert.ToInt32(pricingDetails.Compute("SUM(shipping)", string.Empty));
- priceDet.Rows.Add(0, "Shipping Total");
- //sumAmount = sum;
- sumAmount = 0;
- }
-
-
-
- if (pricingDetails.Rows.Count>0)
- {
- for (int i=0;i<= pricingDetails.Rows.Count-1;i++)
- {
- decimal price = decimal.Zero;
- price = decimal.Multiply((Int32)pricingDetails.Rows[i]["Quantity"], (decimal)pricingDetails.Rows[i]["Price"]);
- pricingDetails.Rows[i]["Total"] = price;
- }
- }
-
- float balance = Wallet.getCustomerCurrentWalletBalance(summary.id_customer);
- ResponseObj.userWalletAmount = balance;
- bool bundleitem = false;
- if (dtr.Rows.Count > 0)
- {
- for (int i = 0; i <= dtr.Rows.Count - 1; i++)
- {
- bundleitem = (bool)dtr.Rows[i][0];
- MaxQty = OrdersComp.GetCartItemsBeforeOrder(summary.id_customer, bundleitem);
- if (MaxQty.Rows.Count > 0)
- {
- foreach (DataRow dr in MaxQty.Rows)
- {
- if ((Int32)(dr["StockQuantity"]) < (Int32)(dr["Quantity"]))
- {
- ResponseObj.message = "Product Qty is not Available in Stock.";
- ResponseObj.status = 0;
- }
- else
- {
- GetCartSubTotal(dr);
- }
- CartSubTotal += ProductFinalCost;
- CartSubTotalInclTax += ProductFinalCostInclTax;
- CartSubTotalExclTax += ProductFinalCostExclTax;
- }
- }
- }
- priceDet.Rows.Add(CartSubTotal, "Subtotal");
- decimal pp = decimal.Add(CartSubTotal, sumAmount);
- priceDet.Rows.Add(pp, "Total");
- ResponseObj.status = 1;
- ResponseObj.paymentmethods = paymentMethod;
- ResponseObj.pricingDetails = priceDet;
- ResponseObj.deliverDays = "2-5 working days";
- ResponseObj.message = "Order Summary";
- }
-
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = Common.NoRecordsExists;
- }
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = "Customer ID Required.";
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [HttpPost]
- [Authorize]
- public HttpResponseMessage reOder([FromBody]ReOrder reorder)
- {
- reOrderResponseObj ResponseObj = new reOrderResponseObj();
- string response = "";
- try
- {
- if (ModelState.IsValid)
- {
- DataTable OrderProducts = OrdersComp.GetOrderProducts(reorder.customerID,reorder.orderID);
- if(OrderProducts.Rows.Count>0)
- {
- for(int i=0;i<= OrderProducts.Rows.Count -1;i++)
- {
- int productid = (Int32)OrderProducts.Rows[i]["ProductId"];
- DataTable MaxQty = ShopingCartComp.GetMaxProductQty(productid);
- if (MaxQty.Rows.Count > 0)
- {
- if (!Convert.IsDBNull(MaxQty.Rows[0]["OrderMaximumQuantity"]))
- {
- if ((Int32)OrderProducts.Rows[i]["Quantity"] > (Int32)MaxQty.Rows[0]["OrderMaximumQuantity"])
- {
- ResponseObj.message = "Max Quantiy Allowed for Purchase is : " + (Int32)MaxQty.Rows[0]["OrderMaximumQuantity"] + ".";
- ResponseObj.status = 0;
- return Request.CreateResponse(HttpStatusCode.OK, ResponseObj.message);
- }
- }
- if (!Convert.IsDBNull(MaxQty.Rows[0]["AllowedQuantities"]))
- {
- if ((Int32)OrderProducts.Rows[i]["Quantity"] > (Int32)MaxQty.Rows[0]["AllowedQuantities"])
- {
- ResponseObj.message = "Allowed Quantiy for Purchase is : " + (Int32)MaxQty.Rows[0]["AllowedQuantities"] + ".";
- ResponseObj.status = 0;
- return Request.CreateResponse(HttpStatusCode.OK, ResponseObj.message);
- }
- }
- if (reorder.customerID != 0)
- {
- //Checking given customerID is is valid or not
- DataTable customerIsValid = ShopingCartComp.CheckCustomerIsvalid(reorder.customerID);
- if (customerIsValid.Rows.Count == 0)
- {
- ResponseObj.message = "CustomerId is not valid.. Please provide vaild customerid";
- ResponseObj.status = 0;
- }
- else
- {
- // checking product had bundle items or not?
- DataTable ProdctBudles = ShopingCartComp.CheckProductIncluesBundle((Int32)OrderProducts.Rows[i]["ProductId"]);
- int? ParentItemId = null; int? BundleItemId = null;
- if (ProdctBudles.Rows.Count != 0)
- {
- int cnt = 0;
- string AttributesXml = "";
- DataTable checkprocutinCART = ShopingCartComp.AddShopingCartItem(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"]);
- if (checkprocutinCART.Rows.Count > 0)
- {
- long res = ShopingCartComp.UpdateCartItmes(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"], (Int32)OrderProducts.Rows[i]["Quantity"]);
- }
- else
- {
- long res = ShopingCartComp.AddShopingCartItem(reorder.customerID, ParentItemId, BundleItemId, (Int32)OrderProducts.Rows[i]["ProductId"], AttributesXml, (Int32)OrderProducts.Rows[i]["Quantity"]);
- }
- int parentitem = 0;
- DataTable bundle = ShopingCartComp.GetParentItemID((Int32)OrderProducts.Rows[i]["ProductId"], reorder.customerID);
- parentitem = (Int32)bundle.Rows[0][0];
- for (int ki = 0; ki <= ProdctBudles.Rows.Count - 1; ki++)
- {
- //// inserting Product Varinat Combination
- string AttributesXm = "";
- long result = ShopingCartComp.AddShopingCartItem(reorder.customerID, parentitem, (Int32)ProdctBudles.Rows[ki]["Id"], (Int32)ProdctBudles.Rows[ki]["ProductId"], AttributesXm, (Int32)ProdctBudles.Rows[ki]["Quantity"]);
- cnt += 1;
- }
- if (cnt == ProdctBudles.Rows.Count)
- {
- ResponseObj.status = 1;
- ResponseObj.message = "Item Added to Cart Successfylly.";
- }
- else
- {
- ResponseObj.message = Common.OopsSomethingWentWrong;
- ResponseObj.status = 0;
- }
- }
- else
- {
- string AttributesXml = "";
- DataTable checkprocutinCART = ShopingCartComp.AddShopingCartItem(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"]);
- long res = 0;
- if (checkprocutinCART.Rows.Count > 0)
- {
- res = ShopingCartComp.UpdateCartItmes(reorder.customerID, (Int32)OrderProducts.Rows[i]["ProductId"], (Int32)OrderProducts.Rows[i]["Quantity"]);
- }
- else
- {
- res = ShopingCartComp.AddShopingCartItem(reorder.customerID, ParentItemId, BundleItemId, (Int32)OrderProducts.Rows[i]["ProductId"], AttributesXml, (Int32)OrderProducts.Rows[i]["Quantity"]);
- }
- DataTable cartTotal = ShopingCartComp.cartTotal(reorder.customerID);
- if (res == 1)
- {
- DataTable productprice = ProductsComp.getProductDetails((Int32)OrderProducts.Rows[i]["ProductId"]);
- ResponseObj.status = 1;
- ResponseObj.message = "Item Added to Cart Successfylly.";
- }
- else
- {
- ResponseObj.message = Common.OopsSomethingWentWrong;
- ResponseObj.status = 0;
- }
- }
- }
- }
- else
- {
- ResponseObj.message = "CustomerId is required";
- ResponseObj.status = 0;
- }
- }
- else
- {
- ResponseObj.status = 1;
- ResponseObj.message = "Poduct is not available.";
- }
- }
- }
-
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = "Customer ID Required.";
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [HttpGet]
- [Authorize]
- public HttpResponseMessage shoppingCartOrders(int id_customer,int start=0)
- {
- DataTable orders = new DataTable();
- ResponseObj ResponseObj = new ResponseObj();
- string response = "";
- try
- {
-
- if (id_customer > 0)
- {
- int PageNumber = start; // Page Number
- int RowsPerPage = 10; // fixed items to display in a page
- orders = OrdersComp.getShopingCartOrders(id_customer, RowsPerPage, PageNumber );
- DataTable orrd = new DataTable();
- if (orders.Rows.Count > 0)
- {
- orrd = orders.Clone();
- orrd.Columns["order_state"].DataType = typeof(System.String);
- foreach (DataRow row in orders.Rows)
- {
- orrd.ImportRow(row);
- }
- for (int i=0;i<= orders.Rows.Count-1;i++)
- {
- if((Int32)orders.Rows[i]["order_state"]==10)
- {
- orrd.Rows[i]["id_order_state"] = 10;
- orrd.Rows[i]["order_state"] = "Order Pending";
- orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderPending"];
- }
- else if ((Int32)orders.Rows[i]["order_state"] == 20)
- {
- orrd.Rows[i]["id_order_state"] = 20;
- orrd.Rows[i]["order_state"] = "Order Processing";
- orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderProcessing"];
- }
- else if ((Int32)orders.Rows[i]["order_state"] == 30)
- {
- orrd.Rows[i]["id_order_state"] = 30;
- orrd.Rows[i]["order_state"] = "Order Complete";
- orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderComplete"];
- }
-
- else
- {
- orrd.Rows[i]["id_order_state"] = 40;
- orrd.Rows[i]["order_state"] = "Order Cancelled";
- orrd.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderCancelled"];
- }
- if (orrd.Rows[i]["payment"].ToString().Contains("Payments.Prepayment"))
- {
- string str = orrd.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orrd.Rows[i]["payment"] = "Online Payment";
- }
- else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.CashOnDelivery"))
- {
- string str = orrd.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orrd.Rows[i]["payment"] = "Cash On Delivery";
- }
- else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.OnlinePayment"))
- {
- string str = orrd.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orrd.Rows[i]["payment"] = "Online Payment";
- }
- else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.PayInStore"))
- {
- string str = orrd.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orrd.Rows[i]["payment"] = "Pay In Store";
- }
- else if (orrd.Rows[i]["payment"].ToString().Contains("Payments.PaymentMethod"))
- {
- string str = orrd.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orrd.Rows[i]["payment"] = "Online Payment";
- }
- }
-
- ResponseObj.status = 1;
- ResponseObj.message = Common.RecordsExists;
- ResponseObj.result = orrd;
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = Common.NoRecordsExists;
- ResponseObj.result = orrd;
- }
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = "orderID Required.";
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [HttpGet]
- [Authorize]
- public HttpResponseMessage getOrderDetails(int customerID, int OrderID)
- {
- DataTable orders = new DataTable();
- ResponseObj ResponseObj = new ResponseObj();
- string response = "";
- try
- {
- if (OrderID > 0)
- {
- orders = OrdersComp.getOrderDetails(customerID , OrderID);
- if (orders.Rows.Count > 0)
- {
- ResponseObj.status = 1;
- ResponseObj.message = Common.RecordsExists;
- ResponseObj.result = orders;
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = Common.NoRecordsExists;
- ResponseObj.result = orders;
- }
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = "orderID Required.";
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [HttpGet]
- [Authorize]
- public HttpResponseMessage getProductNamesByOrderId(int id_customer, int id_order)
- {
- DataTable orders = new DataTable();
- ResponseObj ResponseObj = new ResponseObj();
- string response = "";
- try
- {
- if (id_customer > 0 && id_order >0)
- {
- orders = OrdersComp.GetproductsInContactByOrderId(id_customer, id_order);
- if (orders.Rows.Count > 0)
- {
- ResponseObj.status = 1;
- ResponseObj.message = Common.RecordsExists;
- ResponseObj.result = orders;
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = Common.NoRecordsExists;
- ResponseObj.result = orders;
- }
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = "OrderId is Required.";
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [HttpGet]
- [Authorize]
- public HttpResponseMessage orderReferencesByid(int id_customer)
- {
- DataTable orders = new DataTable();
- ResponseObj ResponseObj = new ResponseObj();
- string response = "";
- try
- {
- if (id_customer > 0 )
- {
- orders = OrdersComp.orderReferencesByCustomerid(id_customer);
- if (orders.Rows.Count > 0)
- {
- ResponseObj.status = 1;
- ResponseObj.message = Common.RecordsExists;
- ResponseObj.result = orders;
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = Common.NoRecordsExists;
- ResponseObj.result = orders;
- }
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = "CustomerId is Required.";
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [HttpGet]
- [Authorize]
- public HttpResponseMessage getOrderDetailsByOrderId(int OrderID)
- {
- // DataTable orders = new DataTable();
- OrderDetailsByOrderidResponseObj ResponseObj = new OrderDetailsByOrderidResponseObj();
- string response = "";
- try
- {
- if (OrderID > 0)
- {
- DataTable orders = OrdersComp.getOrderDetailsbyOrderId(OrderID);
- DataTable deliveryAddress = OrdersComp.GetDeliveryAddressbyOrderID((Int32)orders.Rows[0]["addressid"],OrderID);
- DataTable orrd = new DataTable();
- DataTable OrderDetails = OrdersComp.GetOrderDetailsWithOrderId((Int32)orders.Rows[0]["id_customer"], OrderID);
- if (orders.Rows.Count > 0)
- {
- try
- {
- orrd = orders.Clone();
- orrd.Columns["id_image"].DataType = typeof(System.String);
- orrd.Columns["imageLink"].DataType = typeof(System.String);
- foreach (DataRow row in orders.Rows)
- {
- orrd.ImportRow(row);
- }
- if (orrd.Rows.Count > 0)
- {
- for (int i = 0; i <= orrd.Rows.Count - 1; i++)
- {
- DataTable storedetails = PasswordComp.StoreInformation();
- DataTable getImagesLinks = ProductsComp.GetImageFullNames((Int32)orders.Rows[i]["id_image"]);
- string mimetype = "";
- var imgurl = storedetails.Rows[0]["Url"].ToString();
- if ((getImagesLinks.Rows[0]["MimeType"].ToString()).Contains("image/jpeg"))
- {
- mimetype = ".jpg";
- }
- else if ((getImagesLinks.Rows[0]["MimeType"].ToString()).Contains("image/png"))
- {
- mimetype = ".png";
- }
- string imgId = getImagesLinks.Rows[0]["Id"].ToString();
- string imgName = getImagesLinks.Rows[0]["SeoFilename"].ToString();
- orrd.Rows[i]["imageLink"] = imgurl + "/media/image/" + imgId + "/" + imgName + mimetype + "";
- //orrd.Rows[i]["imageLink"] = imgurl + "" + imgName;
-
- //replacing html strings
- string str = orrd.Rows[i]["description"].ToString();
- Regex rx = new Regex("<[^>]*>");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- RegexOptions options = RegexOptions.None;
- Regex regex = new Regex("[ ]{2,}", options);
- str = regex.Replace(str, " ");
- str = str.Trim();
- orrd.Rows[i]["description"] = str;
- }
- }
- }
- catch (Exception Err) { }
- DataTable orderDett = new DataTable();
- try
- {
- orderDett = OrderDetails.Clone();
- orderDett.Columns["order_state"].DataType = typeof(System.String);
- orderDett.Columns["date_add"].DataType = typeof(System.String);
- foreach (DataRow row in OrderDetails.Rows)
- {
- orderDett.ImportRow(row);
- }
- for (int i = 0; i <= OrderDetails.Rows.Count - 1; i++)
- {
- DateTime OrderDate = (DateTime)orderDett.Rows[i]["date_add"];
- //DateTime utcTime = walletdate.ToLocalTime();
- var istdate = TimeZoneInfo.ConvertTimeFromUtc(OrderDate, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
- string walletDT = istdate.ToString("yyyy-MM-dd HH:mm:ss");
- orderDett.Rows[i]["date_add"] = walletDT;
- if ((Int32)OrderDetails.Rows[i]["order_state"] == 10)
- {
- orderDett.Rows[i]["id_order_state"] = 10;
- orderDett.Rows[i]["order_state"] = "Order Pending";
- orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderPending"];
- }
- else if ((Int32)OrderDetails.Rows[i]["order_state"] == 20)
- {
- orderDett.Rows[i]["id_order_state"] = 20;
- orderDett.Rows[i]["order_state"] = "Order Processing";
- orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderProcessing"];
- }
- else if ((Int32)OrderDetails.Rows[i]["order_state"] == 30)
- {
- orderDett.Rows[i]["id_order_state"] = 30;
- orderDett.Rows[i]["order_state"] = "Order Complete";
- orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderComplete"];
- }
- else
- {
- orderDett.Rows[i]["id_order_state"] = 40;
- orderDett.Rows[i]["order_state"] = "Order Cancelled";
- orderDett.Rows[i]["order_state_color"] = ConfigurationManager.AppSettings["OrderCancelled"];
- }
- if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.Prepayment"))
- {
- string str = orderDett.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orderDett.Rows[i]["payment"] = "Online Payment";
- }
- else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.CashOnDelivery"))
- {
- string str = orderDett.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orderDett.Rows[i]["payment"] = "Cash On Delivery";
- }
- else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.OnlinePayment"))
- {
- string str = orderDett.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orderDett.Rows[i]["payment"] = "Online Payment";
- }
- else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.PayInStore"))
- {
- string str = orderDett.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orderDett.Rows[i]["payment"] = "Pay In Store";
- }
- else if (orderDett.Rows[i]["payment"].ToString().Contains("Payments.PaymentMethod"))
- {
- string str = orderDett.Rows[i]["payment"].ToString();
- Regex rx = new Regex("Payments.");
- // replace all matches with empty strin
- str = rx.Replace(str, "");
- orderDett.Rows[i]["payment"] = "Online Payment";
- }
- }
- }
- catch (Exception ER)
- {
- }
- if (deliveryAddress.Rows.Count > 0)
- {
- string JSONresult;
- JSONresult = JsonConvert.SerializeObject(deliveryAddress);
- JSONresult = JSONresult.Replace("[", "");
- JSONresult = JSONresult.Replace("]", "");
- JObject jsonObject = JObject.Parse(JSONresult);
- ResponseObj.deliveryAddress = jsonObject;
- }
- ResponseObj.status = 1;
- ResponseObj.message = Common.RecordsExists;
-
- ResponseObj.delivery_days = "2-5 working days";
- //ResponseObj.orderDetails = OrderDetails;
- ResponseObj.orderDetails = orderDett;
- ResponseObj.result = orrd;
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = Common.NoRecordsExists;
- ResponseObj.result = orrd;
- }
- }
- else
- {
- ResponseObj.status = 0;
- ResponseObj.message = "orderID Required.";
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [HttpPost]
- [Authorize]
- public HttpResponseMessage CreateOrder([FromBody][Required]CreateOrder createOrder)
- {
- CreateOrderResponseObj ResponseObj = new CreateOrderResponseObj();
- InsufficientRechargeFundsObj ISRFObj = new InsufficientRechargeFundsObj();
- string response = "";
- try
- {
- if (createOrder != null)
- {
- if (ModelState.IsValid)
- {
- ConfirmOrder confirmOrder = new ConfirmOrder();
- InsertOrderItems insertOrderItems = new InsertOrderItems();
- DataTable getaddressofcustomer = OrdersComp.getcustomeraddress(createOrder.id_customer, createOrder.id_address_delivery);
- if (getaddressofcustomer.Rows.Count > 0)
- {
- int Customerid = createOrder.id_customer;
- // checking bundle items are available in cart or not
- DataTable dtr = OrdersComp.CheckBundleIteminCart(Customerid);
- bool bundleitem = false;
- if (dtr.Rows.Count > 0)
- {
- for (int i = 0; i <= dtr.Rows.Count - 1; i++)
- {
- CartSubTotal = decimal.Zero;
- CartSubTotalInclTax = decimal.Zero;
- CartSubTotalExclTax = decimal.Zero;
- bundleitem = (bool)dtr.Rows[i][0];
- //Checking Product Stock availability before purchase
- MaxQty = OrdersComp.GetCartItemsBeforeOrder(Customerid, bundleitem);
- if (MaxQty.Rows.Count > 0)
- {
- foreach (DataRow dr in MaxQty.Rows)
- {
- if ((Int32)(dr["StockQuantity"]) < (Int32)(dr["Quantity"]))
- {
- ResponseObj.message = "Product Qty is not Available in Stock.";
- ResponseObj.status = 2;
- }
- else
- {
- GetCartSubTotal(dr);
- }
- CartSubTotal += ProductFinalCost;
- CartSubTotalInclTax += ProductFinalCostInclTax;
- CartSubTotalExclTax += ProductFinalCostExclTax;
- }
- try
- {
- // MyIPAddress = new WebClient().DownloadString("http://icanhazip.com");
- MyIPAddress = Common.IPaddress;
- }
- catch (Exception Err) { }
- #region ORDER Data
- confirmOrder.StoreId = 1;
- confirmOrder.CustomerId = createOrder.id_customer;
- confirmOrder.BillingAddressId = createOrder.id_address_delivery;
- confirmOrder.ShippingAddressId = createOrder.id_address_delivery;
- confirmOrder.OrderStatusId = 10;
- confirmOrder.ShippingStatusId = 20;
- confirmOrder.PaymentStatusId = 10;
- confirmOrder.PaymentMethodSystemName = "Cash On Delivery";
- confirmOrder.CustomerCurrencyCode = "INR";
- confirmOrder.CurrencyRate = 1;
- confirmOrder.CustomerTaxDisplayTypeId = 10;
- confirmOrder.VatNumber = "";
- confirmOrder.OrderSubtotalInclTax = CartSubTotalInclTax;
- confirmOrder.OrderSubtotalExclTax = CartSubTotalExclTax;
- confirmOrder.OrderSubTotalDiscountInclTax = 0;
- confirmOrder.OrderSubTotalDiscountExclTax = 0;
- confirmOrder.OrderShippingInclTax = 0;
- confirmOrder.OrderShippingExclTax = 0;
- confirmOrder.PaymentMethodAdditionalFeeInclTax = 0;
- confirmOrder.PaymentMethodAdditionalFeeExclTax = 0;
- confirmOrder.TaxRates = "0:0;";
- confirmOrder.OrderTax = 0;
- confirmOrder.OrderDiscount = 0;
- confirmOrder.OrderTotal = CartSubTotal;
- confirmOrder.RefundedAmount = 0;
- confirmOrder.RewardPointsWereAdded = false;
- confirmOrder.CheckoutAttributeDescription = "";
- confirmOrder.CheckoutAttributesXml = "";
- confirmOrder.CustomerLanguageId = 1;
- confirmOrder.AffiliateId = 1;
- confirmOrder.CustomerIp = MyIPAddress;
- confirmOrder.AllowStoringCreditCardNumber = false;
- confirmOrder.CardType = "";
- confirmOrder.CardName = "";
- confirmOrder.CardNumber = "";
- confirmOrder.MaskedCreditCardNumber = "";
- confirmOrder.CardCvv2 = "";
- confirmOrder.CardExpirationMonth = "";
- confirmOrder.CardExpirationYear = "";
- confirmOrder.AllowStoringDirectDebit = false;
- confirmOrder.DirectDebitAccountHolder = "";
- confirmOrder.DirectDebitAccountNumber = "";
- confirmOrder.DirectDebitBankCode = "";
- confirmOrder.DirectDebitBankName = "";
- confirmOrder.DirectDebitBIC = "";
- confirmOrder.DirectDebitCountry = "";
- confirmOrder.DirectDebitIban = "";
- confirmOrder.AuthorizationTransactionId = "";
- confirmOrder.AuthorizationTransactionCode = "";
- confirmOrder.AuthorizationTransactionResult = "";
- confirmOrder.CaptureTransactionId = "";
- confirmOrder.CaptureTransactionResult = "";
- confirmOrder.SubscriptionTransactionId = "";
- confirmOrder.PurchaseOrderNumber = "";
- confirmOrder.PaidDateUtc = DateTime.Now;
- confirmOrder.ShippingMethod = "By Ground";
- confirmOrder.ShippingRateComputationMethodSystemName = "FixedRate";
- confirmOrder.Deleted = false;
- confirmOrder.CreatedOnUtc = DateTime.Now;
- confirmOrder.UpdatedOnUtc = DateTime.Now;
- confirmOrder.RewardPointsRemaining = 0;
- confirmOrder.CustomerOrderComment = "";
- confirmOrder.OrderShippingTaxRate = 0;
- confirmOrder.PaymentMethodAdditionalFeeTaxRate = 0;
- confirmOrder.HasNewPaymentNotification = false;
- confirmOrder.AcceptThirdPartyEmailHandOver = false;
- confirmOrder.OrderTotalRounding = 0;
- confirmOrder.order_from = createOrder.order_from;
- #endregion ORDER Data
- 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.
- CustomerTaxDisplayTypeId, confirmOrder.VatNumber, confirmOrder.OrderSubtotalInclTax, confirmOrder.OrderSubtotalExclTax, confirmOrder.OrderSubTotalDiscountInclTax, confirmOrder.OrderSubTotalDiscountExclTax, confirmOrder.OrderShippingInclTax, confirmOrder.OrderShippingExclTax, confirmOrder.
- PaymentMethodAdditionalFeeInclTax, confirmOrder.PaymentMethodAdditionalFeeExclTax, confirmOrder.TaxRates, confirmOrder.OrderTax, confirmOrder.OrderDiscount, confirmOrder.OrderTotal, confirmOrder.RefundedAmount, confirmOrder.RewardPointsWereAdded, confirmOrder.CheckoutAttributeDescription, confirmOrder.CheckoutAttributesXml, confirmOrder.
- CustomerLanguageId, confirmOrder.AffiliateId, confirmOrder.CustomerIp, confirmOrder.AllowStoringCreditCardNumber, confirmOrder.CardType, confirmOrder.CardName, confirmOrder.CardNumber, confirmOrder.MaskedCreditCardNumber, confirmOrder.CardCvv2, confirmOrder.CardExpirationMonth, confirmOrder.CardExpirationYear, confirmOrder.AllowStoringDirectDebit, confirmOrder.
- DirectDebitAccountHolder, confirmOrder.DirectDebitAccountNumber, confirmOrder.DirectDebitBankCode, confirmOrder.DirectDebitBankName, confirmOrder.DirectDebitBIC, confirmOrder.DirectDebitCountry, confirmOrder.DirectDebitIban, confirmOrder.AuthorizationTransactionId, confirmOrder.AuthorizationTransactionCode, confirmOrder.
- AuthorizationTransactionResult, confirmOrder.CaptureTransactionId, confirmOrder.CaptureTransactionResult, confirmOrder.SubscriptionTransactionId, confirmOrder.PurchaseOrderNumber, confirmOrder.PaidDateUtc, confirmOrder.ShippingMethod, confirmOrder.ShippingRateComputationMethodSystemName, confirmOrder.Deleted, confirmOrder.
- CreatedOnUtc, confirmOrder.UpdatedOnUtc, confirmOrder.RewardPointsRemaining, confirmOrder.CustomerOrderComment, confirmOrder.OrderShippingTaxRate, confirmOrder.PaymentMethodAdditionalFeeTaxRate, confirmOrder.HasNewPaymentNotification, confirmOrder.AcceptThirdPartyEmailHandOver, confirmOrder.OrderTotalRounding, createOrder.order_from);
- //Insert data in OrderItem table
- foreach (DataRow dr2 in MaxQty.Rows)
- {
- //calculating cart subtotal value
- GetCartSubTotal(dr2);
- #region OrderItem Data
- insertOrderItems.ProductId = (Int32)dr2["ProductId"];
- insertOrderItems.Quantity = (Int32)dr2["Quantity"];
- insertOrderItems.UnitPriceInclTax = (decimal)dr2["Price"];
- insertOrderItems.UnitPriceExclTax = (decimal)dr2["Price"];
- insertOrderItems.PriceInclTax = ProductFinalCostInclTax;
- insertOrderItems.PriceExclTax = ProductFinalCostExclTax;
- insertOrderItems.DiscountAmountInclTax = 0;
- insertOrderItems.DiscountAmountExclTax = 0;
- insertOrderItems.AttributeDescription = "";
- insertOrderItems.AttributesXml = dr2["AttributesXml"].ToString();
- insertOrderItems.DownloadCount = 0;
- insertOrderItems.IsDownloadActivated = false;
- insertOrderItems.LicenseDownloadId = 0;
- insertOrderItems.ItemWeight = 0;
- insertOrderItems.BundleData = "";
- insertOrderItems.ProductCost = 0;
- insertOrderItems.TaxRate = 0;
- #endregion OrderItem Data
- int CustomerId = confirmOrder.CustomerId;
- long res1 = OrdersComp.InsertOrderItemsData(CustomerId, insertOrderItems.ProductId, insertOrderItems.Quantity, insertOrderItems.UnitPriceInclTax, insertOrderItems.UnitPriceExclTax, insertOrderItems.PriceInclTax, insertOrderItems.PriceExclTax, insertOrderItems.DiscountAmountInclTax, insertOrderItems.DiscountAmountExclTax, insertOrderItems.AttributeDescription,
- insertOrderItems.AttributesXml, insertOrderItems.DownloadCount, insertOrderItems.IsDownloadActivated, insertOrderItems.LicenseDownloadId, insertOrderItems.ItemWeight, insertOrderItems.BundleData, insertOrderItems.ProductCost, insertOrderItems.TaxRate);
- RemoveFromCart(Customerid);
- UpdateProductStock((Int32)dr2["ProductId"], (Int32)dr2["Quantity"]);
- }
- if (res > 0)
- {
- if (createOrder.useFromWallet == 1)
- {
- float currentbal = Wallet.getCustomerCurrentWalletBalance(createOrder.id_customer);
- if (currentbal >= (Int32)CartSubTotal)
- {
- float PrsntBlnc = currentbal - Convert.ToInt32(CartSubTotal);
- //deducting the wallet balance
- Wallet.saveWalletBalance(createOrder.id_customer.ToString(), res.ToString(), CartSubTotal.ToString(), PrsntBlnc.ToString(), 2, 2, MyIPAddress, "Place Order Using COD with Wallet ");
- ResponseObj.status = 1;
- ResponseObj.message = "Order Placed Successfully";
- ResponseObj.order_id = res;
- }
- else
- {
- float PrsntBlnc = currentbal - Convert.ToInt32(CartSubTotal);
- if (PrsntBlnc < 0)
- {
- PrsntBlnc = 0;
- }
- //deducting the wallet balance
- Wallet.saveWalletBalance(createOrder.id_customer.ToString(), res.ToString(), currentbal.ToString(), PrsntBlnc.ToString(), 2, 2, MyIPAddress, "Place Order Using COD with Wallet ");
- ResponseObj.status = 1;
- ResponseObj.message = "Order Placed Successfully";
- ResponseObj.order_id = res;
- }
- }
- else
- {
- ResponseObj.status = 1;
- ResponseObj.message = "Order Placed Successfully";
- ResponseObj.order_id = res;
- }
- }
- else
- {
- ResponseObj.message = Common.OopsSomethingWentWrong;
- ResponseObj.status = 0;
- }
- }
- else
- {
- ResponseObj.message = "Cart is Empty.. Please add items to cart before place order";
- ResponseObj.status = 0;
- }
- }
- }
- else
- {
- ResponseObj.message = "Cart is Empty.. Please add items to cart before place order";
- ResponseObj.status = 0;
- }
- }
- else
- {
- ResponseObj.message = "id_address_delivery does not belogs to the customer";
- ResponseObj.status = 0;
- }
- }
- else
- {
- var error = ModelState.SelectMany(x => x.Value.Errors).First();
- if (error.ErrorMessage != null && error.ErrorMessage != String.Empty)
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error.ErrorMessage);
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- }
- else
- {
- ResponseObj.message = Common.OopsSomethingWentWrong;
- ResponseObj.status = 0;
- }
- }
- catch (Exception Err)
- {
- }
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- [NonAction]
- public Decimal GetOrderTotalInclTax(DataTable dataTable)
- {
- result = 0;
- return result;
- }
- [NonAction]
- public Decimal GetOrderTotalExclTax(DataTable dataTable)
- {
- result = 0;
- return result;
- }
- [NonAction]
- public decimal GetCartSubTotal(DataRow dataRow)
- {
- result = 0;
- try
- {
- if (dataRow["SpecialPrice"].ToString() == "")
- {
- string str = dataRow["AttributesXml"].ToString();
- Product_GetPriceAdjustment(str);
- GetTaxRate((Int32)dataRow["id"]);
- //Checking Tier Price for the product
- if ((bool) dataRow["HasTierPrices"]==true)
- {
- GetTierProdutTierPrice((Int32)dataRow["id"], (Int32)dataRow["Quantity"]);
- }
- if(ProductTierPrice !=decimal.Zero)
- {
- ProductInitialPrice = ProductTierPrice;
- }
- else
- {
- ProductInitialPrice = (decimal)dataRow["Price"];
- }
- ProductFinalCost = decimal.Zero;
- ProductFinalCost = decimal.Multiply((ProductInitialPrice + ProductAdjPrice), (Int32)dataRow["Quantity"]);
- //ProductFinalCost = decimal.Multiply(((decimal)dataRow["Price"] + ProductAdjPrice - (decimal)dataRow["Discount"]), (Int32)dataRow["Quantity"]);
- ProductFinalCostExclTax = ProductFinalCost;
- ProductFinalCostInclTax = ProductFinalCost * (1 + taxrate / 100);
- }
- else
- {
- string str = dataRow["AttributesXml"].ToString();
- Product_GetPriceAdjustment(str);
- GetTaxRate((Int32)dataRow["id"]);
- ProductFinalCost = decimal.Zero;
- //ProductFinalCost = decimal.Multiply(((decimal)dataRow["SpecialPrice"] + ProductAdjPrice - (decimal)dataRow["Discount"]), (Int32)dataRow["Quantity"]);
- ProductFinalCost = decimal.Multiply(((decimal)dataRow["Price"] + ProductAdjPrice ), (Int32)dataRow["Quantity"]);
- ProductFinalCostExclTax = ProductFinalCost;
- ProductFinalCostInclTax = ProductFinalCost * (1 + taxrate / 100);
- }
- }
- catch (Exception Err)
- {
- }
-
- return CartSubTotal;
- }
-
- [NonAction]
- private decimal Product_GetPriceAdjustment(string attribute )
- {
- ProductAdjPrice = decimal.Zero;
- try
- {
- if (attribute != "")
- {
- var attributesXml = attribute.ToString();
- var doc = XDocument.Parse(attributesXml);
- // Attributes/ProductVariantAttribute
- foreach (var node1 in doc.Descendants("ProductVariantAttribute"))
- {
- string ID = node1.Attribute("ID").Value;
- int ir = int.Parse(ID);
- // ProductVariantAttributeValue/Value
- foreach (int node2 in node1.Descendants("Value"))
- {
- int Val = node2;
- dt2 = GetPriceAjustments(ir, Val);
- if (dt2.Rows.Count > 0)
- {
- decimal AdditionalPrice = decimal.Zero;
- AdditionalPrice = (decimal)dt2.Rows[0][0];
- ProductAdjPrice += AdditionalPrice;
- }
- }
- }
- }
- }
- catch (Exception Err)
- {
- }
- return result;
- }
- [NonAction]
- private DataTable GetPriceAjustments(int ID, int Value)
- {
- dt2 = OrdersComp.GetPriceAdjnustment(ID, Value);
-
- return dt2;
- }
- [NonAction ]
- private decimal GetTaxRate(int productID)
- {
- taxrate = decimal.Zero;
- try
- {
- DataTable dt1 = OrdersComp.GetProductTaxCategory(productID);
- if (dt1.Rows.Count > 0 && (bool)dt1.Rows[0]["IsTaxExempt"] == false)
- {
- taxrate = (decimal)dt1.Rows[0]["Percentage"];
- }
- else if (dt1.Rows.Count > 0 && (bool)dt1.Rows[0]["IsTaxExempt"] == true)
- {
- taxrate = 0;
- }
- }
- catch (Exception Err)
- {
- }
- return result=taxrate;
- }
- [NonAction]
- private void RemoveFromCart(int CustomerID)
- {
- try
- {
- long res = OrdersComp.RemoveFromCart(CustomerID);
- }
- catch (Exception Err)
- {
- }
-
- }
- [NonAction]
- private void UpdateProductStock(int ProductId, int Qty)
- {
-
- try
- {
- long res = OrdersComp.UpdateProductStock(ProductId, Qty);
- }
- catch (Exception Err)
- {
- }
-
- }
- [NonAction]
- private void GetTierProdutTierPrice(int ProductId, int Qty)
- {
- try
- {
- DataTable dt1 = OrdersComp.GetTierPrice(ProductId);
- if(dt1.Rows.Count > 0)
- {
- for(int i=0;i<=dt1.Rows.Count-1;i++)
- {
- if(Qty >= (Int32) dt1.Rows[i]["Quantity"] )
- {
- ProductTierPrice = (decimal)dt1.Rows[i]["TierPrice"];
- }
- }
- }
- else
- {
- ProductTierPrice = decimal.Zero;
- }
- }
- catch (Exception Err)
- {
- }
- }
- [HttpPost]
- [Authorize]
- public HttpResponseMessage CreateOrderUsingPayment([FromBody][Required]CreateOrderUsingPayment createOrderUsingPayment)
- {
- CreateOrderPaymentResponseObj ResponseObj = new CreateOrderPaymentResponseObj();
- HttpResponseMessage HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
- string response = "";
- try
- {
- if (createOrderUsingPayment != null)
- {
- if (ModelState.IsValid)
- {
- string orderid = "";
- if (createOrderUsingPayment.order_id != "" && createOrderUsingPayment.order_id != "0" && createOrderUsingPayment.order_id != null)
- {
- string sub = createOrderUsingPayment.order_id.Substring(0, 3);
- if (sub == "odr")
- {
- orderid = createOrderUsingPayment.order_id.Substring(3);
- }
- }
- response = PlaceOrder.CreateOrderWithPayment(createOrderUsingPayment.id_customer.ToString(), createOrderUsingPayment.id_address_delivery.ToString(), createOrderUsingPayment.useFromWallet.ToString(), createOrderUsingPayment.order_from, orderid);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
- else
- {
- var error = ModelState.SelectMany(x => x.Value.Errors).First();
- if (error.ErrorMessage != null && error.ErrorMessage != String.Empty)
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error.ErrorMessage);
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- }
- else
- {
- createorderPaymentResult resul = new createorderPaymentResult();
- resul.message= Common.OopsSomethingWentWrong;
- ResponseObj.result = resul;
- ResponseObj.status = 0;
- }
- }
- catch (Exception Err)
- {
- }
-
- response = JsonConvert.SerializeObject(ResponseObj, Formatting.None);
- HttpResponseMessage.Content = new StringContent(response, Encoding.UTF8, "application/json");
- return HttpResponseMessage;
- }
-
- }
- }