예제 #1
0
        public ActionResult MySettings()
        {
            var user = db.Users.Where(p => p.UserName == User.Identity.Name).FirstOrDefault();

            if (user == null)
            {
                return(HttpNotFound());
            }

            var view = new UserSettingsView
            {
                Address   = user.Address,
                FirstName = user.FirstName,
                Grade     = user.Grade,
                Group     = user.Group,
                LastName  = user.LastName,
                Phone     = user.Phone,
                Photo     = user.Photo,
                UserId    = user.UserId,
                UserName  = user.UserName
            };

            return(View(view));
            //RedirectToAction(string.Format("Edit/{0}",user.UserId));
        }
예제 #2
0
        private static async Task NotWalmartAsync(UserSettingsView settings, Listing listing, List <string> notWalmartList, string token, int daysBack, List <string> response)
        {
            try
            {
                notWalmartList.Add(listing.ListingTitle);
                notWalmartList.Add(listing.SupplierItem.ItemURL);
                notWalmartList.Add(string.Empty);

                int cnt   = CountMsgID(listing.ID, 1100, daysBack);
                int total = CountMsgID(listing.ID, 0, daysBack);
                notWalmartList.Add(string.Format("Not Walmart: {0}/{1}", cnt, total));
                notWalmartList.Add(string.Empty);

                if (listing.Qty > 0)
                {
                    listing.Qty = 0;
                    await _repository.ListingSaveAsync(settings, listing, false, "Qty");

                    response = Utility.eBayItem.ReviseItem(token, listing.ListedItemID, qty: 0);
                }
                var log = new ListingLog {
                    ListingID = listing.ID, MsgID = 1100, UserID = settings.UserID
                };
                await _repository.ListingLogAdd(log);
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("NotWalmartAsync", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
                throw;
            }
        }
예제 #3
0
        /// <summary>
        /// items are listed that are not in the db
        /// </summary>
        /// <param name="totalListed"></param>
        /// <returns></returns>
        public static List <string> DBIsMissingItems_notused(UserSettingsView settings, ref ItemTypeCollection storeItems)
        {
            var items = new List <string>();

            /*
             * int cnt = 0;
             * if (storeItems.Count == 0)
             * {
             *  storeItems = ebayAPIs.GetSellerList(settings, out string errMsg);
             * }
             * if (storeItems != null)
             * {
             *  // scan each item in store - is it in db?
             *  foreach (ItemType oItem in storeItems)
             *  {
             *      if (oItem.Quantity > 0)
             *      {
             *          int stop = 99;
             *      }
             *      bool r = Utility.StoreCheck.LookupItemid(settings, oItem.ItemID);
             *      if (!r)
             *      {
             *          items.Add(oItem.Title);
             ++cnt;
             *      }
             *  }
             * }
             */
            return(items);
        }
예제 #4
0
        private static async Task OutOfStockBadArrivalDateAsync(UserSettingsView settings, Listing listing, List <string> outofStockBadArrivalList, string token, int daysBack, List <string> response)
        {
            try
            {
                outofStockBadArrivalList.Add(listing.ListingTitle);
                outofStockBadArrivalList.Add(listing.SupplierItem.ItemURL);
                outofStockBadArrivalList.Add(string.Empty);

                if (listing.Qty > 0)
                {
                    listing.Qty = 0;
                    await _repository.ListingSaveAsync(settings, listing, false, "Qty");

                    response = Utility.eBayItem.ReviseItem(token, listing.ListedItemID, qty: 0);
                }
                var log = new ListingLog {
                    ListingID = listing.ID, MsgID = 200, UserID = settings.UserID
                };
                await _repository.ListingLogAdd(log);
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("OutOfStockBadArrivalDateAsync", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
                throw;
            }
        }
예제 #5
0
        private static async Task ParseArrivalDateAsync(UserSettingsView settings, Listing listing, List <string> parseArrivalDateList, string token, int daysBack, List <string> response, ISupplierItem wmItem)
        {
            try
            {
                parseArrivalDateList.Add(listing.ListingTitle);
                parseArrivalDateList.Add(listing.SupplierItem.ItemURL);
                parseArrivalDateList.Add(string.Format("Code: {0}", wmItem.ArrivalDateFlag));
                parseArrivalDateList.Add(string.Empty);

                int cnt   = CountMsgID(listing.ID, 1000, daysBack);
                int total = CountMsgID(listing.ID, 0, daysBack);
                parseArrivalDateList.Add(string.Format("Parse arrival date: {0}/{1}", cnt, total));
                parseArrivalDateList.Add(string.Empty);

                var log = new ListingLog {
                    ListingID = listing.ID, MsgID = 1000, UserID = settings.UserID
                };
                await _repository.ListingLogAdd(log);
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("ParseArrivalDateAsync", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
                throw;
            }
        }
예제 #6
0
        /// <summary>
        /// GetCompletedItems for a seller.
        /// NOTE: we use the Listing class to house the seller's listing.
        /// </summary>
        /// <returns></returns>
        public static ModelView ScanSeller(UserSettingsView settings, string seller, DateTime fromDate)
        {
            int notSold      = 0;
            var listings     = new List <Listing>();
            var searchResult = new List <SearchResult>();

            try
            {
                CustomFindSold service = new CustomFindSold();
                service.Url   = "http://svcs.ebay.com/services/search/FindingService/v1";
                service.appID = settings.AppID;
                int currentPageNumber = 1;

                var request = ebayAPIs.BuildReqest(seller, fromDate);
                dsutil.DSUtil.WriteFile(_logfile, "Retrieve sales for " + seller, settings.UserName);
                var response = GetCompletedItems(service, request, currentPageNumber);
                dsutil.DSUtil.WriteFile(_logfile, "Retrieve sales complete", settings.UserName);

                if (response.ack == AckValue.Success)
                {
                    var result = response.searchResult;
                    if (result != null && result.count > 0)
                    {
                        listings = MapSearchResultToListing(result);
                        searchResult.Add(result);

                        // are there more pages of results?
                        for (var i = response.paginationOutput.pageNumber; i < response.paginationOutput.totalPages; i++)
                        {
                            currentPageNumber += 1;
                            response           = GetCompletedItems(service, request, currentPageNumber);
                            result             = response.searchResult;
                            searchResult.Add(result);
                            var listingsNewPage = MapSearchResultToListing(result);
                            listings.AddRange(listingsNewPage);
                        }
                    }
                    var mv = new ModelView();
                    mv.Listings     = listings;
                    mv.SearchResult = searchResult;

                    int b = notSold;
                    return(mv);
                }
                else
                {
                    dsutil.DSUtil.WriteFile(_logfile, "ScanSeller: " + seller + " - GetCompletedItems returned Failure", "admin");
                }
                return(null);
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("ScanSeller", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
                return(null);
            }
        }
    public SettingsView()
    {
        InitializeComponent();
        var _content = new UserSettingsView();

        ContentControl.Content = _content;
        this.MinWidth          = _content.MinWidth;
        this.MinHeight         = _content.MinHeight;
        this.Width             = this.MinWidth;
        this.Height            = this.MinHeight;
    }
예제 #8
0
        public ActionResult MySettings(UserSettingsView view)
        {
            var user = context.Users.Find(view.Id);

            user.Address    = view.Address;
            user.FirstName  = view.FirstName;
            user.MiddleName = view.MiddleName;
            user.LastName   = view.LastName;

            context.Entry(user).State = EntityState.Modified;
            context.SaveChanges();
            return(RedirectToAction("Index", "Home"));
        }
예제 #9
0
        /// <summary>
        /// does listing id exist in the db?
        /// </summary>
        /// <param name="itemid"></param>
        /// <returns></returns>
        public static Listing LookupItemid(UserSettingsView settings, string itemid)
        {
            var result = _repository.Context.Listings.Where(x => x.ListedItemID == itemid && x.StoreID == settings.StoreID).SingleOrDefault();

            if (result != null)
            {
                return(result);
            }
            else
            {
                return(null);
            }
        }
예제 #10
0
        private static async Task SupplierPriceChange(
            UserSettingsView settings,
            Listing listing,
            List <string> priceChangeList,
            ISupplierItem wmItem,
            decimal wmShipping,
            decimal wmFreeShippingMin,
            string token,
            double eBayPct,
            List <string> response)
        {
            string body = null;

            priceChangeList.Add(listing.ListingTitle);
            var    str  = listing.ListedItemID + " db supplier price " + listing.SupplierItem.SupplierPrice.Value.ToString("c") + " different from just captured " + wmItem.SupplierPrice.Value.ToString("c");
            string note = "db supplier price " + listing.SupplierItem.SupplierPrice.Value.ToString("c") + " different from just captured " + wmItem.SupplierPrice.Value.ToString("c");

            priceChangeList.Add(str);

            Console.WriteLine("Price change.");
            if (wmItem.SupplierPrice < listing.SupplierItem.SupplierPrice)
            {
                str   = "Supplier dropped their price.";
                note += " " + str;
                priceChangeList.Add(str);
                priceChangeList.Add(listing.SupplierItem.ItemURL);
            }
            else
            {
                str   = "Supplier INCREASED their price!";
                note += " " + str;
                priceChangeList.Add(str);
                priceChangeList.Add(listing.SupplierItem.ItemURL);
            }
            dsutil.DSUtil.WriteFile(_logfile, body, log_username);

            var     priceProfit = wallib.wmUtility.wmNewPrice(wmItem.SupplierPrice.Value, listing.PctProfit, wmShipping, wmFreeShippingMin, eBayPct);
            decimal newPrice    = priceProfit.ProposePrice;

            priceChangeList.Add(string.Format("New price: {0:c}", newPrice));
            note += string.Format(" New price: {0:c}", newPrice);
            priceChangeList.Add(string.Empty);
            response = Utility.eBayItem.ReviseItem(token, listing.ListedItemID, price: (double)newPrice);
            await _repository.UpdatePrice(listing, (decimal)newPrice, wmItem.SupplierPrice.Value);

            var log = new ListingLog {
                ListingID = listing.ID, MsgID = 700, Note = note, UserID = settings.UserID
            };
            await _repository.ListingLogAdd(log);
        }
예제 #11
0
        public ActionResult MySettings(UserSettingsView view)
        {
            if (ModelState.IsValid)
            {
                //Upload images
                string path = string.Empty;
                string pic  = string.Empty;

                if (view.NewPhoto != null)
                {
                    pic  = Path.GetFileName(view.NewPhoto.FileName);
                    path = Path.Combine(Server.MapPath("~/Content/Photos"), pic);
                    view.NewPhoto.SaveAs(path);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        view.NewPhoto.InputStream.CopyTo(ms);
                        byte[] array = ms.GetBuffer();
                    }
                }

                //Save record
                var user = db.Users.Find(view.UserId);
                user.Address   = view.Address;
                user.FirstName = view.FirstName;
                user.Grade     = view.Grade;
                user.Group     = view.Group;
                user.LastName  = view.LastName;
                user.Phone     = view.Phone;

                if (!string.IsNullOrEmpty(pic))
                {
                    user.Photo = string.Format("~/Content/Photos/{0}", pic);
                }

                try
                {
                    db.Entry(user).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("Index", "Home"));
                }
                catch (Exception ex)
                {
                    ViewBag.Error = ex.Message;
                    return(View(view));
                }
            }

            return(View(view));
        }
예제 #12
0
        public ActionResult MySettings()
        {
            var user = context.Users.FirstOrDefault(u => u.Username == User.Identity.Name);

            var view = new UserSettingsView
            {
                Address    = user.Address,
                FirstName  = user.FirstName,
                MiddleName = user.MiddleName,
                LastName   = user.LastName,
                Id         = user.Id,
                Username   = user.Username,
            };


            return(View(view));
        }
예제 #13
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            try
            {
                //Utility.eBayItem.GetStore(11, "03d519ce-2f86-4bb7-8f26-e19fade3e261");
                //Utility.eBayItem.GetStore(1, "65e09eec-a014-4526-a569-9f2d3600aa89");
                //Utility.eBayItem.GetStore(3, "9b63b57d-8839-4ed2-ba98-fad513c4ecec");

                //await DeleteUsrAsync("baf38b89-7007-429e-984e-ff00afb4dd91");
                //await DeleteUsrAsync("78cd1257-a514-4f30-87e5-316369ef0488");
                //await DeleteUsrAsync("b21112f2-bc3e-4540-8587-229b2b1ed0b3");

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                var user = new ApplicationUser()
                {
                    UserName = model.Username, Email = model.Email
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                var p = new UserProfile();
                p.UserID    = user.Id;
                p.Firstname = model.Firstname;
                p.Lastname  = model.Lastname;
                p.Created   = DateTime.Now;

                var settings = new UserSettingsView {
                    UserName = model.Username
                };
                await _repository.UserProfileSaveAsync(p);

                return(Ok());
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("Register", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, "admin");
                return(Content(HttpStatusCode.InternalServerError, msg));
            }
        }
예제 #14
0
        public ActionResult MySettings(UserSettingsView userView)
        {
            if (ModelState.IsValid)
            {
                //Upload Image

                string path = string.Empty;
                string pic  = string.Empty;

                if (userView.NewPhoto != null)
                {
                    pic  = Path.GetFileName(userView.NewPhoto.FileName);
                    path = Path.Combine(Server.MapPath("~/Content/Photos"), pic);
                    userView.NewPhoto.SaveAs(path);

                    using (var ms = new MemoryStream())
                    {
                        userView.NewPhoto.InputStream.CopyTo(ms);
                        byte[] array = ms.GetBuffer();
                    }
                }

                var user = db.Users.Find(userView.UserId);
                user.Address   = userView.Address;
                user.FirstName = userView.FirstName;
                user.LastName  = userView.LastName;
                user.Phone     = userView.Phone;
                user.Grade     = userView.Grade;
                user.Group     = userView.Group;

                if (!string.IsNullOrEmpty(pic))
                {
                    user.Photo = pic == string.Empty ? string.Empty : string.Format("~/Content/Photos/{0}", pic);
                }

                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();


                return(RedirectToAction("Index", "Home"));
            }

            return(View(userView));
        }
예제 #15
0
        private static async Task PutBackInStock(UserSettingsView settings,
                                                 Listing listing,
                                                 List <string> putBackInStockList,
                                                 string token,
                                                 List <string> response,
                                                 ISupplierItem wmItem,
                                                 decimal wmShipping,
                                                 decimal wmFreeShippingMin,
                                                 double eBayPct,
                                                 int newListedQty,
                                                 string output)
        {
            try
            {
                putBackInStockList.Add(listing.ListingTitle);
                putBackInStockList.Add(listing.SupplierItem.ItemURL);
                putBackInStockList.Add(string.Empty);

                var     priceProfit = wallib.wmUtility.wmNewPrice(wmItem.SupplierPrice.Value, listing.PctProfit, wmShipping, wmFreeShippingMin, eBayPct);
                decimal newPrice    = priceProfit.ProposePrice;
                output += string.Format(" Price: {0:0.00} ", newPrice);
                listing.ListingPrice = newPrice;
                response             = Utility.eBayItem.ReviseItem(token, listing.ListedItemID, price: (double)newPrice, qty: newListedQty);

                if (response.Count > 0)
                {
                    output += dsutil.DSUtil.ListToDelimited(response, ';');
                }
                var log = new ListingLog {
                    ListingID = listing.ID, MsgID = 600, UserID = settings.UserID, Note = output
                };
                await _repository.ListingLogAdd(log);

                listing.Qty = newListedQty;
                await _repository.ListingSaveAsync(settings, listing, false, "Qty", "ListingPrice");
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("PutBackInStock", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
                throw;
            }
        }
예제 #16
0
        public static IStoreAnalysis Analysis(UserSettingsView settings, ref ItemTypeCollection storeItems)
        {
            IStoreAnalysis analysis       = new StoreAnalysis();
            var            items          = new List <string>();
            var            qtyMismatch    = new List <string>();
            int            cnt            = 0;
            int            qtyMismatchCnt = 0;

            if (storeItems.Count == 0)
            {
                storeItems = ebayAPIs.GetSellerList(settings, out string errMsg);
            }
            if (storeItems != null)
            {
                // scan each item in store - is it in db?
                foreach (ItemType oItem in storeItems)
                {
                    //if (oItem.ItemID == "224079107216")
                    //{
                    //    int stop = 99;
                    //}
                    var listing = Utility.StoreCheck.LookupItemid(settings, oItem.ItemID);
                    if (listing == null)
                    {
                        items.Add(oItem.Title);
                        ++cnt;
                    }
                    else
                    {
                        if (listing.Qty != (oItem.Quantity - oItem.SellingStatus.QuantitySold))
                        {
                            qtyMismatch.Add(oItem.Title);
                            ++qtyMismatchCnt;
                        }
                    }
                }
                analysis.DBIsMissingItems = items;
                analysis.QtyMismatch      = qtyMismatch;
                analysis.InActive         = GetInactive(settings.StoreID);
            }
            return(analysis);
        }
예제 #17
0
        public ActionResult MySettings()
        {
            var user = db.Users
                       .Where(u => u.UserName == User.Identity.Name)
                       .FirstOrDefault();
            var view = new UserSettingsView()
            {
                Address   = user.Address,
                FirstName = user.FirstName,
                Grade     = user.Grade,
                Group     = user.Group,
                LastName  = user.LastName,
                Phone     = user.Phone,
                Photo     = user.Photo,
                UserId    = user.UserId,
                UserName  = user.UserName
            };

            return(View(view));
        }
예제 #18
0
        public async Task <IHttpActionResult> UserProfileSave(UserProfile profile)
        {
            IUserSettingsView settings = new UserSettingsView();

            try
            {
                string connStr = ConfigurationManager.ConnectionStrings["OPWContext"].ConnectionString;
                settings = _repository.GetUserSettingsView(connStr, profile.UserID);

                await _repository.UserProfileSaveAsync(profile, "SelectedStore");

                return(Ok());
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("UserProfileSave", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
                return(BadRequest(msg));
            }
        }
예제 #19
0
        public async void ShowMetroWindow()
        {
            var metroWindow = Application.Current.MainWindow as MetroWindow;
            var dialog      = await metroWindow.ShowMessageAsync(
                "Błąd połaczenia",
                $"Czy chcesz zmienić ustawienia?",
                MessageDialogStyle.AffirmativeAndNegative);

            if (dialog == MessageDialogResult.Affirmative)
            {
                var userSettingsWindow = new UserSettingsView();
                userSettingsWindow.ShowDialog();
            }


            else if (dialog == MessageDialogResult.Negative)
            {
                Application.Current.Shutdown();
            }
        }
예제 #20
0
        private static async Task DeliveryTooLongAsync(UserSettingsView settings, Listing listing, List <string> deliveryTooLongList, string token, int daysBack, List <string> response, int days, int allowedDeliveryDays)
        {
            try
            {
                deliveryTooLongList.Add(listing.ListingTitle);
                deliveryTooLongList.Add(listing.SupplierItem.ItemURL);
                deliveryTooLongList.Add(string.Format("{0} business days, over by {1} day(s)", days, days - allowedDeliveryDays));
                var note = string.Format("{0} days", days);
                deliveryTooLongList.Add(string.Format("Qty was {0}", listing.Qty));
                note += string.Format(" (Qty was {0})", listing.Qty);
                deliveryTooLongList.Add(string.Empty);

                int cnt   = CountMsgID(listing.ID, 100, daysBack);
                int total = CountMsgID(listing.ID, 0, daysBack);
                deliveryTooLongList.Add(string.Format("Delivery too long: {0}/{1}", cnt, total));
                deliveryTooLongList.Add(string.Empty);

                note += string.Format(" (Qty was {0})", listing.Qty);
                var log = new ListingLog {
                    ListingID = listing.ID, MsgID = 100, Note = note, UserID = settings.UserID
                };
                await _repository.ListingLogAdd(log);

                if (listing.Qty > 0)
                {
                    listing.Qty = 0;
                    await _repository.ListingSaveAsync(settings, listing, false, "Qty");

                    response = Utility.eBayItem.ReviseItem(token, listing.ListedItemID, qty: 0);
                }
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("DeliveryTooLongAsync", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
                throw;
            }
        }
예제 #21
0
        static async Task GetOrders(UserSettingsView settings, string logfile, double finalValueFeePct)
        {
            try
            {
                DateTime ed     = DateTime.Now;
                DateTime sd     = ed.AddHours(-3);
                var      orders = ebayAPIs.GetOrdersByDate(settings, sd, ed, finalValueFeePct, "");
                if (orders.Count > 0)
                {
                    var msg = new List <string>();
                    foreach (var o in orders)
                    {
                        // sync db qty
                        var sellerListing = await ebayAPIs.GetSingleItem(settings, o.ListedItemID, false);

                        var listing = _repository.ListingGet(o.ListedItemID);

                        listing.Qty = sellerListing.Qty.Value;
                        await _repository.ListingSaveAsync(settings, listing, false, "Qty");

                        msg.Add(o.ListedItemID);
                        msg.Add(listing.ListingTitle);
                        msg.Add(o.Buyer);
                        msg.Add(o.DatePurchased.ToString());
                        msg.Add(o.Qty.ToString());
                        msg.Add("");
                    }
                    SendAlertEmail(_toEmail, settings.StoreName + " ORDERS", msg);
                }
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("GetOrders", exc);
                dsutil.DSUtil.WriteFile(logfile, msg, settings.UserName);
                throw;
            }
        }
        public UserSettingsView GetViewModel(int id)
        {
            var user = _db.FirstOrDefault <User>(new Sql().Select("*").From("dbo.umbracoUser").Where("id=@tag", new
            {
                tag = id
            }));


            var languages = _db.Fetch <UserLanguage>(new Sql().Select("*").From("dbo.simpleTranslationUserLanguages").Where("id=@tag", new
            {
                tag = id
            }));

            var model = new UserSettingsView
            {
                User          = user,
                UserLanguages = languages.Select(x => x.LanguageId),
                Languages     = _db.Fetch <Language>(new Sql().Select("*").From("dbo.umbracoLanguage")),
                UserRole      = _urh.GetUserRole(id),
                Roles         = TranslationRole.TranslationRoles
            };

            return(model);
        }
예제 #23
0
        public ActionResult MySettings()
        {
            //this.User.Identity.Name -> Devuelve el nombre del usuario logeado
            var user = db.Users
                       .Where(u => u.UserName == this.User.Identity.Name)
                       .FirstOrDefault();

            var view = new UserSettingsView
            {
                Address   = user.Address,
                FirstName = user.FirstName,
                Grade     = user.Grade,
                Group     = user.Group,
                LastName  = user.LastName,
                Phone     = user.Phone,
                Photo     = user.Photo,
                UserId    = user.UserId,
                UserName  = user.UserName
            };



            return(View(view));
        }
예제 #24
0
        static void Main(string[] args)
        {
            byte             forceSendEmail = 0;
            int              daysBack       = 21;
            UserSettingsView settings       = null;

            try
            {
                int storeID;
                if (args.Length != 4)
                {
                    Console.WriteLine("Invalid arguments: wm [storeID] [logfile] [daysBack] [forceEmail(0,1)]");
                }
                else
                {
                    _logfile       = args[1];
                    storeID        = Convert.ToInt32(args[0]);
                    daysBack       = Convert.ToInt32(args[2]);
                    forceSendEmail = Convert.ToByte(args[3]);
                    string userID = UserID(storeID);
                    if (!string.IsNullOrEmpty(userID))
                    {
                        string connStr = ConfigurationManager.ConnectionStrings["OPWContext"].ConnectionString;

                        ebayAPIs.Init(_repository);
                        FetchSeller.Init(_repository);
                        wallib.wmUtility.Init(_repository);

                        settings = _repository.GetUserSettingsView(connStr, userID, storeID);
                        var wmShipping        = Convert.ToDecimal(_repository.GetAppSetting(settings, "Walmart shipping"));
                        var wmFreeShippingMin = Convert.ToDecimal(_repository.GetAppSetting(settings, "Walmart free shipping min"));
                        int imgLimit          = Convert.ToInt32(_repository.GetAppSetting(settings, "Listing Image Limit"));

                        byte handlingTime        = settings.HandlingTime;
                        byte maxShippingDays     = settings.MaxShippingDays;
                        var  allowedDeliveryDays = handlingTime + maxShippingDays;

                        int outofstock = 0;
                        dsutil.DSUtil.WriteFile(_logfile, "", log_username);
                        dsutil.DSUtil.WriteFile(_logfile, "", log_username);
                        dsutil.DSUtil.WriteFile(_logfile, "START REPRICING", log_username);

                        Task.Run(async() =>
                        {
                            await GetOrders(settings, _logfile, 0.0915);
                        }).Wait();

                        Task.Run(async() =>
                        {
                            outofstock = await ScanItems(settings, _sourceID, wmShipping, wmFreeShippingMin, settings.FinalValueFeePct, imgLimit, allowedDeliveryDays, daysBack, forceSendEmail);
                        }).Wait();
                    }
                    else
                    {
                        Console.WriteLine("Could not find a user with RepricerEmail flag set for this store.");
                    }
                }
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("Main", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, settings.UserName);
            }
        }
예제 #25
0
        private static async Task SearchEngineMatch(UserSettingsView settings, int rptNumber, int minSold, int daysBack, int?minPrice, int?maxPrice, bool?activeStatusOnly, bool?isSellerVariation, string itemID, double pctProfit, decimal wmShipping, decimal wmFreeShippingMin, double eBayPct, int imgLimit, string supplierTag)
        {
            string loopItemID = null;
            bool   found      = false;

            try
            {
                var mv = new ModelViewTimesSold();
                mv.TimesSoldRpt = FilterMatch(settings, rptNumber, minSold, daysBack, minPrice, maxPrice, activeStatusOnly, isSellerVariation, itemID);

                // Only search where MatchCount is null or does not equal 1
                mv.TimesSoldRpt = mv.TimesSoldRpt.Where(p => !p.MatchCount.HasValue || (p.MatchCount.HasValue && p.MatchCount.Value != 1)).ToList();

                foreach (var row in mv.TimesSoldRpt)
                {
                    loopItemID = row.ItemID;
                    if (loopItemID == "392388202275")
                    {
                        var stop = 999;
                    }
                    ISupplierItem walitem;
                    string        descr = row.Description;
                    found = false;

                    // Search sections of description since most search engines only use first part of query anyway
                    for (int i = 0; i < 5; i++)
                    {
                        string section = GetDescrSection(descr, i);
                        if (!string.IsNullOrEmpty(section))
                        {
                            section = supplierTag + " " + section;

                            //var links = dsutil.DSUtil.BingSearch(section);
                            var links = dsutil.DSUtil.GoogleSearchSelenium(section);

                            var validLinks = wallib.wmUtility.ValidURLs(links); // just get supplier links
                            if (validLinks.Count > 0)
                            {
                                // Collect valid supplier links from search engine result
                                foreach (string supplierURL in validLinks)
                                {
                                    walitem = await wallib.wmUtility.GetDetail(supplierURL, imgLimit, false);

                                    if (walitem != null)
                                    {
                                        // If can't get supplier pics, not much point in posting.
                                        // Can happen when not matching correctly on something like an eBook or giftcard where walmart
                                        // is not providing "standard" images. (error is logged in GetDetail()).
                                        if (!string.IsNullOrEmpty(walitem.SupplierPicURL))
                                        {
                                            if (!string.IsNullOrEmpty(walitem.ItemID) || !string.IsNullOrEmpty(walitem.UPC) || !string.IsNullOrEmpty(walitem.MPN))
                                            {
                                                found           = true;
                                                walitem.Updated = DateTime.Now;
                                                _repository.SupplierItemUpdateByID(walitem,
                                                                                   "Updated",
                                                                                   "ItemURL",
                                                                                   "SoldAndShippedBySupplier",
                                                                                   "SupplierBrand",
                                                                                   "SupplierPrice",
                                                                                   "IsVariation",
                                                                                   "SupplierPicURL",
                                                                                   "IsFreightShipping");

                                                var oh = new OrderHistory();
                                                oh.ItemID         = row.ItemID;
                                                oh.MatchCount     = 1;
                                                oh.MatchType      = 3;
                                                oh.SourceID       = walitem.SourceID;
                                                oh.SupplierItemID = walitem.ID;
                                                if (walitem.SupplierPrice.HasValue)
                                                {
                                                    var p = wallib.wmUtility.wmNewPrice(walitem.SupplierPrice.Value, pctProfit, wmShipping, wmFreeShippingMin, eBayPct);
                                                    oh.ProposePrice = p.ProposePrice;
                                                    _repository.OrderHistoryUpdate(oh, "ProposePrice", "MatchType", "MatchCount", "SourceID", "SupplierItemID");
                                                }
                                                else
                                                {
                                                    _repository.OrderHistoryUpdate(oh, "MatchType", "MatchCount", "SourceID", "SupplierItemID");
                                                }
                                            }
                                        }
                                        if (found)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (found)
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                string msgItemID = (!string.IsNullOrEmpty(loopItemID)) ? "ItemID: " + loopItemID : "";
                string header    = "SearchEngineMatch RptNumber: " + rptNumber.ToString() + " " + msgItemID;
                string msg       = dsutil.DSUtil.ErrMsg(header, exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, "");
            }
        }
예제 #26
0
        /// <summary>
        /// Scrape seller
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="seller"></param>
        /// <param name="numItemsToFetch"></param>
        /// <param name="daysToScan"></param>
        /// <returns></returns>
        static async Task <int> FetchSeller(UserSettingsView settings, string seller, int numItemsToFetch, int daysToScan)
        {
            int  numItems        = 0;
            int  completedItems  = 0;
            bool retRemoveDetail = false;

            var sh = new SearchHistory();

            sh.UserId   = settings.UserID;
            sh.Seller   = seller;
            sh.DaysBack = daysToScan;

            int?     rptNumber = null;
            DateTime?fromDate;

            rptNumber = db.LatestRptNumber(seller);
            if (rptNumber.HasValue)
            {
                sh.ID = rptNumber.Value;
            }
            if (daysToScan > 0)
            {
                // passed an override value for date to start scan
                fromDate = DateTime.Now.AddDays(-daysToScan);
            }
            else
            {
                // else calculate start scanning from seller's last sale
                if (rptNumber.HasValue)
                {
                    fromDate = db.fromDateToScan(rptNumber.Value);
                }
                else
                {
                    fromDate = DateTime.Now.AddDays(-30);
                }
            }
            if (!rptNumber.HasValue || rptNumber.Value == 0)
            {
                // first time running seller
                sh.Updated = DateTime.Now;
                var sh_updated = await db.SearchHistoryAdd(sh);

                rptNumber = sh_updated.ID;
            }
            else
            {
                sh.Updated = DateTime.Now;
                db.SearchHistoryUpdate(sh, "Updated");
                retRemoveDetail = await db.HistoryDetailRemove(rptNumber.Value, fromDate.Value);
            }
            try
            {
                // Use eBay API findCompletedItems() to get seller's sold listings but then need to use Selenium to get actual sales by day.
                var modelview = eBayUtility.FetchSeller.ScanSeller(settings, seller, fromDate.Value);
                if (modelview != null)
                {
                    int listingCount = modelview.Listings.Count;
                    dsutil.DSUtil.WriteFile(_logfile, "scan seller count: " + listingCount, "admin");
                    string lastItemID = null;
                    foreach (var listing in modelview.Listings.OrderBy(o => o.ItemID))
                    {
                        if (lastItemID != listing.ItemID)
                        {
                            //output += listing.Title + "\n";      if (listing.ItemID == "392535456736")
                            if (true)
                            {
                                var si = await eBayUtility.ebayAPIs.GetSingleItem(settings, listing.ItemID);

                                var listingStatus = si.ListingStatus;

                                // when navigating to a listing from the website, ebay adds a hash
                                // you don't seem to need it unless navigating to a completed item in which case it doesn't work
                                // i'm not sure how to generate the hash

                                ListingStatusCount(listingStatus);
                                var sellingState = SellingState(listing.ItemID, modelview.SearchResult);
                                SellingStateCount(sellingState);

                                if (listingStatus != "Completed")
                                {
                                    if (numItems++ < numItemsToFetch)
                                    {
                                        if (true)   // listing.ItemID == "312839444438"
                                        {
                                            Console.WriteLine(numItems + "/" + listingCount);
                                            var transactions = NavigateToTransHistory(listing.SellerListing.EbayURL, listing.ItemID);

                                            if (transactions != null)
                                            {
                                                var orderHistory = new OrderHistory();
                                                orderHistory.ItemID              = listing.ItemID;
                                                orderHistory.Title               = listing.SellerListing.Title;
                                                orderHistory.EbayURL             = listing.SellerListing.EbayURL;
                                                orderHistory.PrimaryCategoryID   = listing.PrimaryCategoryID;
                                                orderHistory.PrimaryCategoryName = listing.PrimaryCategoryName;
                                                orderHistory.EbaySellerPrice     = listing.SellerListing.SellerPrice;
                                                orderHistory.Description         = si.Description;
                                                orderHistory.ListingStatus       = listingStatus;
                                                orderHistory.IsSellerVariation   = listing.SellerListing.Variation;

                                                orderHistory.RptNumber           = rptNumber.Value;
                                                orderHistory.OrderHistoryDetails = transactions;
                                                string orderHistoryOutput = db.OrderHistorySave(orderHistory, fromDate.Value);
                                                string specificOutput     = await db.OrderHistoryItemSpecificSave(dsmodels.DataModelsDB.CopyFromSellerListing(si.ItemSpecifics));
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    ++completedItems;
                                }
                            }
                        }
                        lastItemID = listing.ItemID;
                    }
                    dsutil.DSUtil.WriteFile(_logfile, "completed items count: " + completedItems, "admin");
                }
            }
            catch (Exception exc)
            {
                string msg = dsutil.DSUtil.ErrMsg("FetchSeller", exc);
                dsutil.DSUtil.WriteFile(_logfile, msg, "");
            }
            return(numItems);
        }
예제 #27
0
        private void UserSettings(object obj)
        {
            var userSettingWindow = new UserSettingsView();

            userSettingWindow.ShowDialog();
        }
예제 #28
0
        /// <summary>
        /// Main driver to scan listings for issues.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="sourceID"></param>
        /// <param name="pctProfit"></param>
        /// <param name="wmShipping"></param>
        /// <param name="wmFreeShippingMin"></param>
        /// <param name="eBayPct"></param>
        /// <param name="imgLimit"></param>
        /// <returns></returns>
        public static async Task <int> ScanItems(UserSettingsView settings,
                                                 int sourceID,
                                                 decimal wmShipping,
                                                 decimal wmFreeShippingMin,
                                                 double eBayPct,
                                                 int imgLimit,
                                                 int allowedDeliveryDays,
                                                 int daysBack,
                                                 byte forceSendEmail)
        {
            int    i          = 0;
            int    outofstock = 0;
            int    outofstockBadArrivalDate = 0;
            int    invalidURL           = 0;
            int    shippingNotAvailable = 0;
            int    mispriceings         = 0;
            int    numErrors            = 0;
            int    putBackInStock       = 0;
            int    notInStockLongEnough = 0;
            int    deliveryTooLong      = 0;
            int    parseArrivalDate     = 0;
            int    notWalmart           = 0;
            var    response             = new List <string>();
            string body      = null;
            int    listingID = 0;

            var outofStockList           = new List <string>();
            var outofStockBadArrivalList = new List <string>();
            var priceChangeList          = new List <string>();
            var shipNotAvailList         = new List <string>();
            var invalidURLList           = new List <string>();
            var errors                   = new List <string>();
            var putBackInStockList       = new List <string>();
            var deliveryTooLongList      = new List <string>();
            var parseArrivalDateList     = new List <string>();
            var notWalmartList           = new List <string>();
            var notInStockLongEnoughList = new List <string>();

            try
            {
                DateTime startTime, endTime;
                startTime = DateTime.Now;

                string token       = _repository.GetToken(settings);
                var    walListings = _repository.Context.Listings
                                     .Include(d => d.SupplierItem)
                                     .Where(x => x.SupplierItem.SourceID == sourceID && x.Listed != null && x.StoreID == settings.StoreID)
                                     .ToList();

                foreach (Listing listing in walListings)
                {
                    try
                    {
                        //Random random = new Random();
                        //int sec = random.Next(2);
                        //Thread.Sleep(sec * 1000);
                        Thread.Sleep(10000);

                        listingID = listing.ID;

                        //if (listing.SupplierItem.ItemURL != "https://www.walmart.com/ip/Classic-Sport-Premier-Cup-II-Foosball-Table-Brown-Official-Competition-Size/592871184")
                        //{
                        //    continue;
                        //}

                        var wmItem = await wallib.wmUtility.GetDetail(listing.SupplierItem.ItemURL, imgLimit, true);

                        Console.WriteLine((++i) + " " + listing.ListingTitle);
                        if (wmItem == null)  // could not fetch from walmart website
                        {
                            ++invalidURL;
                            await InvalidURLAsync(settings, listing, invalidURLList, token, daysBack, response);
                        }
                        else
                        {
                            if (wmItem.ArrivalDateFlag == 1 || wmItem.ArrivalDateFlag == 2)
                            {
                                ++parseArrivalDate;
                                await ParseArrivalDateAsync(settings, listing, parseArrivalDateList, token, daysBack, response, wmItem);
                            }
                            if (!wmItem.SoldAndShippedBySupplier ?? false)
                            {
                                ++notWalmart;
                                await NotWalmartAsync(settings, listing, notWalmartList, token, daysBack, response);
                            }
                            if (wmItem.ShippingNotAvailable)
                            {
                                ++shippingNotAvailable;
                                await ShipNotAvailableAsync(settings, listing, shipNotAvailList, token, daysBack, response);
                            }
                            if (!wmItem.ShippingNotAvailable && wmItem.OutOfStock)
                            {
                                ++outofstock;
                                await OutOfStockAsync(settings, listing, outofStockList, token, daysBack, response);
                            }
                            if (!wmItem.OutOfStock && !wmItem.ShippingNotAvailable && !wmItem.Arrives.HasValue)
                            {
                                ++outofstockBadArrivalDate;
                                await OutOfStockBadArrivalDateAsync(settings, listing, outofStockBadArrivalList, token, daysBack, response);
                            }
                            bool lateDelivery = false;
                            if (wmItem.Arrives.HasValue)
                            {
                                int days = dsutil.DSUtil.GetBusinessDays(DateTime.Now, wmItem.Arrives.Value);
                                if (days > allowedDeliveryDays)
                                {
                                    lateDelivery = true;
                                    ++deliveryTooLong;
                                    await DeliveryTooLongAsync(settings, listing, deliveryTooLongList, token, daysBack, response, days, allowedDeliveryDays);
                                }
                            }

                            // PUT BACK IN STOCK
                            if (listing.Qty == 0 &&
                                !listing.InActive &&
                                wmItem.Arrives.HasValue &&
                                !wmItem.OutOfStock &&
                                !wmItem.ShippingNotAvailable &&
                                !lateDelivery &&
                                (wmItem.SoldAndShippedBySupplier ?? false))
                            {
                                string msg = null;
                                bool   inStockLongEnough = InStockLongEnough(listing.ID, 1, out msg);
                                string output            = msg + " ";
                                if (inStockLongEnough)
                                {
                                    Console.WriteLine("Put back in stock.");
                                    int newListedQty = 1;
                                    ++putBackInStock;
                                    await PutBackInStock(settings, listing, putBackInStockList, token, response, wmItem, wmShipping, wmFreeShippingMin, eBayPct, newListedQty, output);
                                }
                                else
                                {
                                    ++notInStockLongEnough;
                                    notInStockLongEnoughList.Add(listing.ListingTitle);
                                    notInStockLongEnoughList.Add(listing.SupplierItem.ItemURL);
                                    notInStockLongEnoughList.Add(string.Empty);

                                    var log = new ListingLog {
                                        ListingID = listing.ID, MsgID = 1200, UserID = settings.UserID, Note = output
                                    };
                                    await _repository.ListingLogAdd(log);
                                }
                            }

                            // inactive and might qualify to put back in stock
                            if (listing.Qty == 0 &&
                                listing.InActive &&
                                wmItem.Arrives.HasValue &&
                                !wmItem.OutOfStock &&
                                !wmItem.ShippingNotAvailable &&
                                !lateDelivery &&
                                (wmItem.SoldAndShippedBySupplier ?? false))
                            {
                                string msg = null;
                                if (InStockLongEnough(listing.ID, 1, out msg))
                                {
                                    var log = new ListingLog {
                                        ListingID = listing.ID, MsgID = 1300, UserID = settings.UserID
                                    };
                                    await _repository.ListingLogAdd(log);
                                }
                                else
                                {
                                    var log = new ListingLog {
                                        ListingID = listing.ID, MsgID = 1400, UserID = settings.UserID
                                    };
                                    await _repository.ListingLogAdd(log);
                                }
                            }

                            // SUPPLIER PRICE CHANGE?
                            if (listing.Qty > 0 &&
                                !wmItem.OutOfStock &&
                                !wmItem.ShippingNotAvailable &&
                                !lateDelivery &&
                                (wmItem.SoldAndShippedBySupplier ?? false))
                            {
                                if (Math.Round(wmItem.SupplierPrice.Value, 2) != Math.Round(listing.SupplierItem.SupplierPrice.Value, 2))
                                {
                                    ++mispriceings;
                                    await SupplierPriceChange(settings, listing, priceChangeList, wmItem, wmShipping, wmFreeShippingMin, token, eBayPct, response);
                                }
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        string msg = "ERROR IN LOOP -> " + listing.ListingTitle + " -> " + exc.Message;
                        errors.Add(msg);
                        dsutil.DSUtil.WriteFile(_logfile, msg, "");

                        ++numErrors;
                        var log = new ListingLog {
                            ListingID = listing.ID, MsgID = 10000, UserID = settings.UserID, Note = exc.Message
                        };
                        await _repository.ListingLogAdd(log);

                        if (listing.Qty > 0)
                        {
                            listing.Qty = 0;
                            await _repository.ListingSaveAsync(settings, listing, false, "Qty");

                            try
                            {
                                response = Utility.eBayItem.ReviseItem(token, listing.ListedItemID, qty: 0);
                            }
                            catch
                            {
                                // Utility.eBayItem.ReviseItem() will log and throw its exception but we don't want to leave the for loop
                                // so just swallow the error here
                            }
                        }
                    }
                }   // end for loop

                endTime = DateTime.Now;
                double elapsedMinutes = ((TimeSpan)(endTime - startTime)).TotalMinutes;
                var    storeProfile   = new StoreProfile {
                    ID = settings.StoreID, RepricerLastRan = DateTime.Now, ElapsedTime = elapsedMinutes
                };
                await _repository.StoreProfileUpdate(storeProfile, "RepricerLastRan", "ElapsedTime");

                var elapsedMinutesList = new List <string>();
                var elapsedTimeMsg     = string.Format("Elapsed time: {0} minutes; Total scanned {1}", Math.Round(elapsedMinutes, 2), i);
                elapsedMinutesList.Add(elapsedTimeMsg);
                //SendAlertEmail(_toEmail, settings.StoreName + " ELAPSED TIME ", elapsedMinutesList);

                if (numErrors > 0)
                {
                    SendAlertEmail(_toEmail, settings.StoreName + " TRACKER ERRORS ", errors);
                }

                var sendEmail = false;
                var rightNow  = DateTime.Now;
                if ((rightNow.Hour >= 8 && rightNow.Hour < 9) || forceSendEmail == 1)
                {
                    sendEmail = true;
                }
                if (sendEmail)
                {
                    if (putBackInStock > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " RE-STOCK ", putBackInStockList);
                    }
                    if (notInStockLongEnough > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " NOT IN-STOCK LONG ENOUGH ", notInStockLongEnoughList);
                    }
                    if (mispriceings > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " PRICE CHANGE", priceChangeList);
                    }
                    if (outofstock > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " OUT OF STOCK - LABEL", outofStockList);
                    }
                    if (outofstockBadArrivalDate > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " OUT OF STOCK - Bad Arrival Date", outofStockBadArrivalList);
                    }
                    if (invalidURL > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " INVALID URL ", invalidURLList);
                    }
                    if (shippingNotAvailable > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " DELIVERY NOT AVAILABLE ", shipNotAvailList);
                    }
                    if (deliveryTooLong > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " DELIVERY TOO LONG ", deliveryTooLongList);
                    }
                    if (parseArrivalDate > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " PARSE ARRIVAL DATE - START SELENIUM ", parseArrivalDateList);
                    }
                    if (notWalmart > 0)
                    {
                        SendAlertEmail(_toEmail, settings.StoreName + " NOT SOLD & SHIPPED BY SUPPLIER ", notWalmartList);
                    }

                    if (mispriceings + outofstock + invalidURL + shippingNotAvailable + numErrors + putBackInStock == 0)
                    {
                        string ret = dsutil.DSUtil.SendMailDev(_toEmail, string.Format(settings.StoreName + "REPRICER - scanned {0} items", walListings.Count), "No issues found.");
                    }
                }
                return(outofstock);
            }
            catch (Exception exc)
            {
                string msg = "listingID: " + listingID + " -> " + exc.Message;
                dsutil.DSUtil.WriteFile(_logfile, msg, "");
                throw;
            }
        }