public List<ParcelItem> GetPendingOrders(int userCode, int userAccountCode)
    {
        DataModelEntities context = new DataModelEntities();

        UserAccount userAccount = context.UserAccounts.First(u => u.User_Account_Code == userAccountCode);
        List<ChargeCode> chargeCodes = context.ChargeCodes.Where(u => u.Is_Active == true && u.User_Code == userCode).ToList();

        ShopifyAuthorizationState authState = new ShopifyAuthorizationState();
        authState.AccessToken = userAccount.Config_Value1;
        authState.ShopName = userAccount.Application_Name;

        ShopifyAPIClient api = new ShopifyAPIClient(authState);

        try
        {
            // by default JSON string is returned
            dynamic data = new JavaScriptSerializer().DeserializeObject(api.Get("/admin/orders.json?fulfillment_status=unshipped").ToString());

            List<PriceManagerDAL.ParcelItem> parcelItems = context.ParcelItems.Where(f => f.User_Code == userCode && f.UserAccount.Account_Code == (int)Constant.Accounts.Shopify && f.Is_Active == true).ToList();

            // delete all database entries
            foreach (PriceManagerDAL.ParcelItem existingItem in parcelItems)
            {
                context.ParcelItems.DeleteObject(existingItem);
            }
            context.SaveChanges();

            List<ParcelItem> items = new List<ParcelItem>();

            foreach (dynamic order in data["orders"])
            {
                foreach (dynamic lineItem in order["line_items"])
                {
                    ParcelItem item = new ParcelItem();

                    item.Type = "SHOPIFY";
                    item.AccountID = userAccount.User_Account_Code.ToString();
                    item.RecordNumber = order["order_number"].ToString();
                    item.ItemID = lineItem["id"].ToString();
                    item.TransactionID = order["id"].ToString();
                    item.ItemName = lineItem["title"];
                    item.CustomLabel = lineItem["sku"].ToString();
                    item.CustomLabelText = lineItem["sku"].ToString();

                    string state = order["shipping_address"]["province"];
                    string stateCode = order["shipping_address"]["province_code"];

                    if (StateHelper.States.Where(s => s.Key == stateCode).Count() > 0)
                        item.State = StateHelper.States[stateCode];
                    else
                        item.State = state;

                    item.BuyerName = order["customer"]["first_name"] + " " + order["customer"]["last_name"];
                    item.EmailAddress = order["email"];
                    item.BuyerID = order["customer"]["id"].ToString();

                    item.Street2 = order["shipping_address"]["address1"];
                    item.Street3 = order["shipping_address"]["address2"];
                    item.City = order["shipping_address"]["city"];
                    item.PostalCode = order["shipping_address"]["zip"].TrimStart('0');
                    item.Country = order["shipping_address"]["country_code"];
                    item.Phone = order["shipping_address"]["phone"];

                    item.Quantity = lineItem["quantity"];
                    if (order["shipping_lines"] != null)
                        item.ShippingCost = double.Parse(order["shipping_lines"][0]["price"]);
                    item.SaleRecordId = order["order_number"].ToString();

                    // insurance details //

                    item.Currency = order["currency"];
                    item.Price = double.Parse(lineItem["price"]);

                    item.Messages = GetMessageText(order["note"],order["created_at"]);

                    item.ShippingMethod = order["shipping_lines"][0]["title"];

                    string shippingCode = order["shipping_lines"][0]["code"];
                    ChargeCode code = chargeCodes.FirstOrDefault(u => shippingCode.ToLower().Contains(u.Ebay_Code.ToLower()) == true);
                    if (code != null && code.Charge_Code_Name.ToLower() == "ignore")
                    {
                        continue; // ignore the item
                    }

                    bool IspostCodeOK = Common.VerifyPostCode(order["shipping_address"]["zip"], order["shipping_address"]["city"]);
                    if (IspostCodeOK)
                        item.PostCodeImageURL = Constant.tickURL;
                    else
                        item.PostCodeImageURL = Constant.crossURL;

                    items.Add(item);
                }
            }

            return items;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
 /// <summary>
 /// Deprecated Method for adding a new object to the ParcelItems EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToParcelItems(ParcelItem parcelItem)
 {
     base.AddObject("ParcelItems", parcelItem);
 }
 /// <summary>
 /// Create a new ParcelItem object.
 /// </summary>
 /// <param name="parcel_Item_Code">Initial value of the Parcel_Item_Code property.</param>
 public static ParcelItem CreateParcelItem(global::System.Int32 parcel_Item_Code)
 {
     ParcelItem parcelItem = new ParcelItem();
     parcelItem.Parcel_Item_Code = parcel_Item_Code;
     return parcelItem;
 }
    public List<ParcelItem> GetPendingOrders()
    {
        try
        {
            if (UserAccountCode != 0)
            {
                List<ParcelItem> items = new List<ParcelItem>();
                DataModelEntities context = new DataModelEntities();
                UserAccount userAccount = context.UserAccounts.First(u => u.User_Account_Code == UserAccountCode);

                MagentoService service = new MagentoService();
                service.Url = userAccount.Application_Name;

                string sessionID = service.login(userAccount.Config_Value1, userAccount.Config_Value2);
                List<associativeEntity> listAssociatedEntity = new List<associativeEntity>();
                listAssociatedEntity.Add(new associativeEntity() { key = "status", value = "pending" });

                filters filters = new filters();
                filters.filter = listAssociatedEntity.ToArray();

                salesOrderListEntity[] orders = service.salesOrderList(sessionID, filters);

                List<ChargeCode> chargeCodes = context.ChargeCodes.Where(u => u.Is_Active == true && u.User_Code == UserCode).ToList();

                foreach (salesOrderListEntity order in orders)
                {
                    salesOrderEntity orderDetail = service.salesOrderInfo(sessionID, order.increment_id);

                    foreach (salesOrderItemEntity lineItem in orderDetail.items)
                    {

                        ParcelItem item = new ParcelItem();

                        item.Type = "MAGENTO";
                        item.AccountID = userAccount.User_Account_Code.ToString();
                        item.RecordNumber = orderDetail.order_id;
                        item.ItemID = lineItem.item_id;
                        item.TransactionID = orderDetail.increment_id;
                        item.ItemName = lineItem.name;
                        item.CustomLabel = lineItem.sku;
                        item.CustomLabelText = lineItem.sku;

                        string state = orderDetail.shipping_address.region;
                        string stateCode = orderDetail.shipping_address.region_id;

                        if (StateHelper.States.Where(s => s.Key == stateCode).Count() > 0)
                            item.State = StateHelper.States[stateCode];
                        else
                            item.State = state;

                        item.BuyerName = orderDetail.customer_firstname + " " + orderDetail.customer_lastname;
                        item.EmailAddress = orderDetail.customer_email;
                        item.BuyerID = orderDetail.customer_id;

                        item.Street2 = orderDetail.shipping_address.street;
                        item.Street3 = string.Empty;
                        item.City = orderDetail.shipping_address.city;
                        item.PostalCode = orderDetail.shipping_address.postcode;
                        item.Country = orderDetail.shipping_address.country_id;
                        item.Phone = orderDetail.shipping_address.telephone;

                        item.Quantity = lineItem.qty_ordered == string.Empty ? 0 : (int)decimal.Parse(lineItem.qty_ordered);
                        if (orderDetail.shipping_amount != string.Empty)
                            item.ShippingCost = double.Parse(orderDetail.shipping_amount);
                        item.SaleRecordId = orderDetail.increment_id;

                        // insurance details //

                        item.Currency = orderDetail.order_currency_code;
                        item.Price = double.Parse(lineItem.price);

                        item.ShippingMethod = orderDetail.shipping_description;

                        string shippingCode = orderDetail.shipping_description;
                        ChargeCode code = chargeCodes.FirstOrDefault(u => shippingCode.ToLower().Contains(u.Ebay_Code.ToLower()) == true);
                        if (code != null && code.Charge_Code_Name.ToLower() == "ignore")
                        {
                            continue; // ignore the item
                        }

                        bool IspostCodeOK = Common.VerifyPostCode(orderDetail.shipping_address.postcode, orderDetail.shipping_address.city);
                        if (IspostCodeOK)
                            item.PostCodeImageURL = Constant.tickURL;
                        else
                            item.PostCodeImageURL = Constant.crossURL;

                        items.Add(item);
                    }
                }

                return items;
            }
            else
            {
                return null;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    private List<ParcelItem> GetEbayAccountTransactions(EbayServiceBL service, KeyValuePair<int, string> account, int UserCode)
    {
        int accountID = account.Key;
        DataModelEntities context = new DataModelEntities();
        List<PriceManagerDAL.ParcelItem> parcelItems = context.ParcelItems.Where(f => f.AccountID == accountID && f.User_Code == UserCode && f.Is_Active == true).ToList();

        string currentItemID = string.Empty, currentTransactionID = string.Empty, currentRecordNo = string.Empty;

        SellingManagerSoldOrderType[] results = service.GetPendingShipmentItems(account.Value);

        if(results == null)
            results = new SellingManagerSoldOrderType[0];

        // delete all database entries that does not exist in the API results.
        foreach (PriceManagerDAL.ParcelItem existingItem in parcelItems)
        {
            long transactionID = long.Parse(existingItem.TransactionID);
            SellingManagerSoldOrderType checkResult = results.FirstOrDefault(r => r.SellingManagerSoldTransaction.Count(c => c.ItemID == existingItem.ItemID && c.TransactionID == transactionID) > 0);
            if (checkResult == null)
            {
                context.ParcelItems.DeleteObject(existingItem);
            }
        }

        // delete entries which do not have correct shipping details
        foreach (PriceManagerDAL.ParcelItem existingItem in parcelItems.Where(p => string.IsNullOrEmpty(p.BuyerName) == true))
        {
            context.ParcelItems.DeleteObject(existingItem);
        }

        // now traverse through API results and save only those which are new
        List<ParcelItem> items = new List<ParcelItem>();
        if (results != null && results.Length > 0)
        {
            List<ChargeCode> chargeCodes = new DataModelEntities().ChargeCodes.Where(u => u.Is_Active == true && u.User_Code == UserCode).ToList();
            foreach (SellingManagerSoldOrderType result in results)
            {
                foreach (SellingManagerSoldTransactionType transaction in result.SellingManagerSoldTransaction)
                {
                    try
                    {

                        currentItemID = transaction.ItemID;
                        currentTransactionID = transaction.TransactionID.ToString();

                        // ignore if the item already exists in our database
                        if (context.ParcelItems.FirstOrDefault(f => f.AccountID == accountID && f.ItemID == currentItemID && f.TransactionID == currentTransactionID) != null)
                        {
                            continue;
                        }

                        ParcelItem item = new ParcelItem();
                        item.Type = "EBAY";

                        SellingManagerSoldOrderType itemDetails = service.GetSaleRecordDetails(transaction.ItemID, transaction.TransactionID.ToString(), account.Value);

                        currentRecordNo = itemDetails.SaleRecordID.ToString();

                        item.AccountID = account.Key.ToString();
                        item.ItemID = transaction.ItemID;
                        item.TransactionID = transaction.TransactionID.ToString();
                        item.ItemName = transaction.ItemTitle;
                        item.CustomLabel = transaction.CustomLabel;
                        item.CustomLabelText = transaction.SaleRecordID.ToString() + ":" + transaction.CustomLabel;
                        if (itemDetails.ShippingAddress != null)
                        {
                            if (StateHelper.States.Where(s => s.Key == itemDetails.ShippingAddress.StateOrProvince.ToLower()).Count() > 0)
                                item.State = StateHelper.States[itemDetails.ShippingAddress.StateOrProvince.ToLower()];
                            else
                                item.State = itemDetails.ShippingAddress.StateOrProvince.ToLower();
                            item.BuyerName = itemDetails.ShippingAddress.Name;
                            item.Street = itemDetails.ShippingAddress.Street;
                            item.Street2 = itemDetails.ShippingAddress.Street1;
                            item.Street3 = itemDetails.ShippingAddress.Street2;
                            item.City = itemDetails.ShippingAddress.CityName;
                            item.PostalCode = itemDetails.ShippingAddress.PostalCode.TrimStart('0'); ;
                            item.Country = itemDetails.ShippingAddress.Country.ToString();
                            item.Phone = itemDetails.ShippingAddress.Phone;
                        }
                        else
                        {

                        }
                        item.EmailAddress = itemDetails.BuyerEmail;
                        item.BuyerID = itemDetails.BuyerID;
                        item.Quantity = transaction.QuantitySold;
                        if (itemDetails.ActualShippingCost != null)
                            item.ShippingCost = itemDetails.ActualShippingCost.Value;
                        item.SaleRecordId = itemDetails.SaleRecordID.ToString();

                        bool IspostCodeOK = true;
                        if (itemDetails.ShippingDetails != null)
                        {
                            if (itemDetails.ShippingDetails.InsuranceFee == null)
                                item.HasInsurance = false;
                            else
                            {
                                item.HasInsurance = true;
                                item.Insurance = itemDetails.ShippingDetails.InsuranceFee.Value;
                            }
                            if (itemDetails.ShippingDetails != null && itemDetails.ShippingDetails.ShippingServiceOptions != null)
                                item.ShippingMethod = itemDetails.ShippingDetails.ShippingServiceOptions[0].ShippingService;
                            else
                                item.ShippingMethod = "N/A";

                            IspostCodeOK = Common.VerifyPostCode(itemDetails.ShippingAddress.PostalCode, itemDetails.ShippingAddress.CityName);
                            if (IspostCodeOK)
                                item.PostCodeImageURL = Constant.tickURL;
                            else
                                item.PostCodeImageURL = Constant.crossURL;
                        }

                        if (itemDetails.SellingManagerSoldTransaction != null)
                        {
                            item.Currency = itemDetails.SellingManagerSoldTransaction[0].ItemPrice.currencyID.ToString();
                            item.Price = itemDetails.SellingManagerSoldTransaction[0].ItemPrice.Value;
                        }

                        item.RecordNumber = itemDetails.SaleRecordID.ToString();

                        ChargeCode code = chargeCodes.FirstOrDefault(u => item.ShippingMethod.ToLower().Contains(u.Ebay_Code.ToLower()) == true);
                        if (code != null && code.Charge_Code_Name.ToLower() == "ignore")
                        {
                            continue; // ignore the item
                        }

                        GetMemberMessagesResponseType messages = service.GetTransactionMessages(item.ItemID, item.BuyerID, account.Value);
                        if (messages.MemberMessage != null)
                        {
                            List<ParcelMessage> ebayMessages = service.ConvertEbayMessages(messages);
                            item.Messages = Common.Serialize(ebayMessages);
                        }

                        items.Add(item);

                        currentItemID = string.Empty;
                        currentRecordNo = string.Empty;
                        currentTransactionID = string.Empty;
                    }
                    catch (Exception ex)
                    {
                        Logging.WriteLog(LogType.Critical, ex.ToString());
                    }
                }
            }
            context.SaveChanges();
            return items.OrderBy(i => i.BuyerID).ToList();
        }
        else
        {
            context.SaveChanges();
            return null;
        }
    }
    public void SaveTransactions(List<ParcelItem> allItems, int UserCode)
    {
        DataModelEntities context = new DataModelEntities();
        PriceManagerDAL.User user = context.Users.FirstOrDefault(f => f.User_Code == UserCode);
        List<PriceManagerDAL.ParcelItem> eItems = context.ParcelItems.Where(p => p.User_Code == UserCode && p.Is_Active == true).ToList();
        Dictionary<int, int> itemsToUpdateQty = new Dictionary<int, int>();
        Dictionary<string, int> itemsToSendAlert = new Dictionary<string, int>();
        foreach (ParcelItem item in allItems)
        {
            try
            {
                // check if the item already does not exist in the database and insert it then.
                PriceManagerDAL.ParcelItem dbItem = eItems.FirstOrDefault(p => p.ItemID == item.ItemID && p.TransactionID == item.TransactionID);

                if (dbItem == null)
                {
                    dbItem = new PriceManagerDAL.ParcelItem();
                    dbItem.User_Code = UserCode;
                    dbItem.AccountID = int.Parse(item.AccountID);
                    dbItem.BuyerID = item.BuyerID;
                    dbItem.BuyerName = item.BuyerName;
                    dbItem.City = item.City;
                    dbItem.Country = item.Country;
                    dbItem.Created_Date = DateTime.Now;
                    dbItem.Currency = item.Currency;
                    dbItem.CustomLabel = item.CustomLabel;
                    dbItem.CustomLabelText = item.CustomLabelText;
                    dbItem.EmailAddress = item.EmailAddress;
                    dbItem.HasInsurance = item.HasInsurance;
                    dbItem.Insurance = Convert.ToDecimal(item.Insurance);
                    dbItem.Is_Active = true;
                    dbItem.ItemID = item.ItemID;
                    dbItem.ItemName = item.ItemName;
                    dbItem.Messages = item.Messages;
                    dbItem.Parcel_Status_Code = (int)Constant.ParcelStatusCode.Pending;
                    dbItem.Phone = item.Phone;
                    dbItem.PostalCode = item.PostalCode;
                    dbItem.PostCodeImageURL = item.PostCodeImageURL;
                    dbItem.Price = Convert.ToDecimal(item.Price);
                    dbItem.Quantity = item.Quantity;
                    dbItem.RecordNumber = item.RecordNumber;
                    dbItem.SaleRecordId = item.SaleRecordId;
                    dbItem.ShippingCost = Convert.ToDecimal(item.ShippingCost);
                    dbItem.ShippingMethod = item.ShippingMethod;
                    dbItem.State = item.State;
                    dbItem.Street = item.Street;
                    dbItem.Street2 = item.Street2;
                    dbItem.Street3 = item.Street3;
                    dbItem.TransactionID = item.TransactionID;
                    dbItem.Type = item.Type;
                    dbItem.AddressID = item.AddressID;
                    context.ParcelItems.AddObject(dbItem);

                }
                /*Create Order for inventory tracking*/
                PriceManagerDAL.Item product = context.Items.FirstOrDefault(f => f.CustomLabel == item.CustomLabel && f.UserCode == UserCode);
                if (product != null)
                {
                    /*First Check if item with the same ItemID and TransactionID does not exists in the order table*/
                    PriceManagerDAL.StockLedger checkorder = context.StockLedgers.FirstOrDefault(p => p.ItemID == item.ItemID && p.TransactionID == item.TransactionID && p.Type == item.Type && p.AccountID == item.AccountID);
                    if (checkorder == null)
                    {
                        PriceManagerDAL.StockLedger dborder = new PriceManagerDAL.StockLedger();
                        dborder.User_Code = UserCode;
                        dborder.AccountID = item.AccountID;
                        dborder.Type = item.Type;
                        dborder.TransactionID = item.TransactionID;
                        dborder.ItemID = item.ItemID;
                        dborder.CustomLabel = item.CustomLabel;
                        dborder.Quantity = item.Quantity * -1;
                        dborder.Narration = item.Type + " New Sale";
                        dborder.Stock_Ledger_Type = (int)Common.StockLegerType.NewSale;
                        dborder.Created_Date = System.DateTime.Now;
                        dborder.ID = product.ID;
                        context.AddToStockLedgers(dborder);

                        if (!itemsToUpdateQty.Any(a => a.Key == product.ID))
                            itemsToUpdateQty.Add(product.ID, item.Quantity);
                        else
                            itemsToUpdateQty[product.ID] = itemsToUpdateQty[product.ID] + item.Quantity;

                    }
                    else
                    {
                        /*Check if Qty is different from the existing order item*/
                        if (checkorder.Quantity != item.Quantity * -1)
                        {
                            if (!itemsToUpdateQty.Any(a => a.Key == product.ID))
                                itemsToUpdateQty.Add(product.ID, item.Quantity - (int)checkorder.Quantity);
                            else
                                itemsToUpdateQty[product.ID] = itemsToUpdateQty[product.ID] + (item.Quantity - (int)checkorder.Quantity);

                            checkorder.Quantity = item.Quantity;
                            checkorder.Modifed_Date = System.DateTime.Now;

                        }

                    }
                }
            }
            catch (Exception ex)
            {
                Logging.WriteLog(LogType.Critical, ex.ToString());
            }
        }
        /*Update Items Balance Qty*/
        foreach (var item in itemsToUpdateQty)
        {
            PriceManagerDAL.Item updateItem = context.Items.FirstOrDefault(f => f.ID == item.Key);
            if (updateItem != null && updateItem.Balance_Quantity != null)
            {
                int previousBalance = updateItem.Balance_Quantity != null ? (int)updateItem.Balance_Quantity : 0;
                int currentBalance = previousBalance - item.Value;

                /*Add items if user min threshold alert is on and item is reaching to min threshold level*/
                if (user.Minimum_Threshold_Alert == true && updateItem.Minimum_Threshold != null && previousBalance > updateItem.Minimum_Threshold && currentBalance <= updateItem.Minimum_Threshold)
                    itemsToSendAlert.Add(updateItem.CustomLabel + " - " + updateItem.Description, currentBalance);

                /*Update item's balance quantity*/
                updateItem.Balance_Quantity = currentBalance;

            }
        }
        context.SaveChanges();

        /*Send Email Notification For Minimum Threshold*/
        if (itemsToSendAlert.Count > 0)
        {
            System.Threading.Thread t = new System.Threading.Thread(() => SendMinimumThresholdAlert(itemsToSendAlert, user));
            t.Start();
        }
    }