示例#1
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                EmailFactory.SendEmailAsync(new ForgotPassword(user, callbackUrl));
                // await m.SendMessageAsync();

                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#2
0
        public ActionResult Startup(RegisterViewModel model)
        {
            if (UserManager.Users.Any())
            {
                return(RedirectToAction("Index"));
            }
            if (ModelState.IsValid)
            {
                var user = new Models.ApplicationUser
                {
                    UserName         = model.Email,
                    Email            = model.Email,
                    PhoneNumber      = model.Phone,
                    RegisterName     = model.Name,
                    Registered       = DateTime.UtcNow,
                    IsAcceptedOffert = true
                };
                var result = UserManager.Create(user, model.Password);
                if (result.Succeeded)
                {
                    try
                    {
                        var userinfo = new UserInfo()
                        {
                            User            = user,
                            Name            = model.Name ?? model.Email,
                            AdditionalMail  = "",
                            AdditionalPhone = "",
                            Patronymyc      = "",
                            Surname         = ""
                        };
                        db.Insert(userinfo, User.Identity.GetUserId());
                        //  var b = RolesManager.Roles.ToList();
                        UserManager.AddToRole(user.Id, "root");
                        user.Registered       = DateTime.UtcNow;
                        user.AllowPromoEmails = true;
                        user.AllowTradeEmails = true;
                        user.EmailConfirmed   = true;
                        user.AllowedIp        = model.Ip;
                        user.IsDebug          = true;
                        UserManager.Update(user);

                        user.IsAcceptedOffert = true;
                        UserManager.Update(user);
                        db.SaveChanges();
                        //Mailer.SendMail(user.Email, "Для подтверждения е-мэйла перейдите по <a href=\"" + callbackUrl + "\">ccылке</a>");
                        //  Mailer.SendRegistrationMail(user.RegisterName ?? model.Name, user.Email, callbackUrl);
                        EmailFactory.SendEmailAsync(new SuccessRegister(user, "")); // {Link = callbackUrl};
                        //await m.SendMessageAsync();
                        //await EmailFactory.SendEmailAsync(new Email(m));
                    }
                    catch (Exception ex)
                    {
                        return(View("Error"));
                    }
                }
            }
            return(View());
        }
示例#3
0
        public async Task <ActionResult> Create(NewAuctionViewModel model)
        {
            model.IsOffer = false;
            model.IsOrder = true;
            // model.SelectedProduct = model?.ProductsList?.FirstOrDefault(c => c.Code == TradeTypes.closeFixed.ToString())??new Areas.Admin.Models.CatalogModel() { Code= "closeFixed" };
            try
            {
                if ((model.TradeEnd - model.TradeBegin).TotalMinutes < 59)
                {
                    return
                        (Json(
                             new
                    {
                        Success = false,
                        responseText =
                            LocalText.Inst.Get("error", "Orders.Create.WrongTimeOfOffer",
                                               "Час актуальності пропозиції повинен бути не меншим за годину",
                                               "Время актуальности предложения должно быть, как минимум, равным часу")
                    },
                             JsonRequestBehavior.AllowGet));
                }
                model.HasRedemptionPrice = true;
                model.IsPreApproved      = true;
                model.IsAccepted         = true;
                model.RedemptionPrice    = model.StartPrice;

                var trade = tradeDataLayer.CreateTrade(model, User.Identity.GetUserId());
                trade.BankBill = Db.BankBills.FirstOrDefault(c => c.Id == trade.BankBillId);
                //  var trademodel = tradeDataLayer.CreateTradeViewModel(trade);
                foreach (var user in UserManager.Users)
                {
                    EmailFactory.SendEmailAsync(new NewOrder(user, tradeDataLayer.CreateTradeViewModel(trade, user)));
                }

                await EmailFactory.Brodcast(new Broadcast()
                {
                    Body = "Нова заявка", Subject = "На РТР створено нову пропозицію. Подивіться, може у вас є що запропонувати?"
                });

                //Mailer.SendMail("*****@*****.**", "Новый торг на модерации",
                //    "Уважаемый модератор, просьба одобрить новый торг: " + Url.Action("TradesOnApproving", "Trade", null, Request.Url.Scheme));
                return(Json(new { Success = true, redirectUrl = Url.Action("Index", "Orders") },
                            JsonRequestBehavior.AllowGet));
            }
            catch (ArgumentNullException ex)
            {
                logger.Error(ex);
                return(Json(new { Success = false, responseText = LocalText.Inst.Get("error", "errorfilenotuploaded", "Паспорт товару не загружено, перейдіть на сторінку модерації торгів та спробуйте знову") }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(Json(new { Success = false, responseText = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
示例#4
0
        public async Task <ActionResult> Order(UserOrderViewModel model)
        {
            try
            {
                var offer = Db.Trades.Find(model.OfferId);
                if (offer == null)
                {
                    logger.Info("Какой-то чмошник что-то чудит");
                    throw new ArgumentNullException("lot", "Bet must not be empty");
                }
                var user = UserManager.FindById(User.Identity.GetUserId());

                tradeDataLayer.CheckOfferOnOrder(user, model, offer);
                var order = new Order(model);
                Db.Insert(order, user.Id);
                offer.Buyers.Add(order.Buyer);
                Db.UpdateEntity(offer, user.Id);


                foreach (var u in offer.Orders.GroupBy(c => c.Buyer).SelectMany(f => f.Key.ContragentUsers).ToList())
                {
                    await hub.UpdateTradeTable(offer.Id, u.UserName);
                }
                foreach (var u in offer.Seller.ContragentUsers.ToList())
                {
                    await hub.UpdateTradeTable(offer.Id, u.UserName);

                    EmailFactory.SendEmailAsync(new NewReplyToOffer(u, order));
                }

                return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
            }
            catch (ArgumentOutOfRangeException ex)
            {
                logger.Error(ex);
                return
                    (Json(new
                {
                    success = false,
                    error = $"{LocalText.Inst.Get("error", "VolumeTooMuch", "Зменшіть об’єм Вашої заявки", "Уменьшите объем Вашей заявки")} {GetFullErrorMessage(ex)}"
                }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return
                    (Json(new
                {
                    success = false,
                    error = $"{LocalText.Inst.Get("error", "errorBet", "Відбулася помилка", "Произошла ошибка")} {GetFullErrorMessage(ex)}"
                }, JsonRequestBehavior.AllowGet));
            }
        }
示例#5
0
        public void CloseTrade(Trade trade)
        {
            try
            {
                logger.Info($"try close trade {trade.Id}");
                // trade.SendPopups(trade.Buyers.SelectMany(c => c.ContragentUsers).Distinct().ToList(), _notificationHub, NotifyType.AboutTradeEnd);
                foreach (var user in trade.Seller.ContragentUsers.ToList().Distinct())
                {
                    logger.Info($"Send seller letter to {user.Email}");
                    int winnerscount = TradeWinners(trade).Count();
                    EmailFactory.SendEmailAsync(new SellerLetter(user, trade, winnerscount));
                }
                foreach (var buyer in TradeWinners(trade).Distinct())
                {
                    CreateBill(trade.Id, buyer.Id);

                    foreach (var user in GetContragentUsers(buyer).Distinct().ToList())
                    {
                        var bets =
                            buyer.Bets.Where(f => f.TradeId == trade.Id && (f.IsActual || f.IsRedemption))
                            .ToList();
                        #region SendMail to winner
                        logger.Info($"send WINNER leter to {user.Email}");
                        EmailFactory.SendEmailAsync(new WonFix(trade, bets, buyer, user));
                    }
                    #endregion

                    foreach (var loser in TradeLosers(trade.Id).ToList().Distinct().ToList())
                    {
                        EmailFactory.SendEmailAsync(new LoserLetter(loser, trade.Id, trade.Seller.LongName));
                    }

                    foreach (var failedtrade in GetFailedTrades())
                    {
                        logger.Info($"NEED TO SEND LETTERS ABOUT FAILED TRADE: {failedtrade.Id}");
                        failedtrade.IsClosedByBills = true;
                        _context.UpdateEntity(failedtrade);
                    }
                }
                logger.Info($"CLOSING trade {trade.Id}");
                trade.IsClosedByBills = true;
                _context.UpdateEntity(trade);
            }


            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
示例#6
0
        public async Task <ActionResult> Edit(ApproveModel model)
        {
            try
            {
                var currentuser = UserManager.FindById(User.Identity.GetUserId());
                var cont        = db.Contragents.Single(x => x.Id == model.ContragentId);
                cont.ApprovingComment    = model.Comment;
                cont.HasContractCopy     = model.HasContractCopy;
                cont.HasContractOriginal = model.HasContractOriginal;
                cont.IsApproved          = model.IsApproved;
                cont.IsBuyer             = model.IsBuyer;
                cont.IsSeller            = model.IsSeller;
                cont.ApprovedByUserId    = currentuser.Id;
                cont.ApprovedByUser      = currentuser;
                cont.ContractOnSignin    = model.ContractIsOnSign;
                db.UpdateEntity(cont, currentuser.Id);

                if (cont.IsApproved)
                {
                    CheckRoles(cont);

                    EmailFactory.SendEmailAsync(new LegalActive(cont.CreatedByUser, cont));
                }
                else
                {
                    CheckRoles(cont);
                    if (model.SendMail)
                    {
                        foreach (var user in cont.ContragentUsers.ToList())
                        {
                            logger.Info($"contragent {cont.LongName} deactivated, sending mail");

                            EmailFactory.SendEmailAsync(new LegalNotActive(user, cont));
                        }
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                ModelState.AddModelError("", ex.Message);
                return(RedirectToAction("Details", new { @id = model.ContragentId }));
            }
        }
示例#7
0
        public ActionResult SendMails(Broadcast model)
        {
            try
            {
                ViewBag.Message = "ГОТОВО";
                //await EmailFactory.Brodcast(mod);
                if (model.ToAll)
                {
                    foreach (var user in UserManager.Users.ToList())
                    {
                        EmailFactory.SendEmailAsync(model, user);
                    }
                }
                else
                {
                    EmailFactory.SendEmailAsync(model);
                    if (model.IsReply)
                    {
                        var feedback = db.Feedbacks.Find(model.ReplyId);
                        if (feedback != null)
                        {
                            feedback.IsCommited = true;
                        }
                        db.SaveChanges();
                        return(RedirectToAction("Index", "Feedback", new { area = "Admin" }));
                    }
                }

                return(View(new Broadcast()
                {
                    Body = "Шановні покупці! Повідомляємо, що на ЕТП РТР оголошено нові торги, запрошуємо до участі!",
                    Subject = "Нові торги"
                }));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                ModelState.AddModelError("other", ex);
                return(View("Error"));
            }
        }
示例#8
0
        public async Task <ActionResult> Create(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser()
                {
                    UserName         = model.Email,
                    Email            = model.Email,
                    PhoneNumber      = model.Phone,
                    RegisterName     = model.Name,
                    Registered       = DateTime.UtcNow,
                    IsAcceptedOffert = true
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    try
                    {
                        var userinfo = new UserInfo()
                        {
                            User            = user,
                            Name            = model.Name ?? model.Email,
                            AdditionalMail  = "",
                            AdditionalPhone = "",
                            Patronymyc      = "",
                            Surname         = ""
                        };
                        db.Insert(userinfo, User.Identity.GetUserId());
                        //  var b = RolesManager.Roles.ToList();
                        await UserManager.AddToRoleAsync(user.Id, model.Role);

                        user.Registered       = DateTime.UtcNow;
                        user.AllowPromoEmails = true;
                        user.AllowTradeEmails = true;
                        user.EmailConfirmed   = true;
                        user.IpRestricted     = true;
                        user.AllowedIp        = model.Ip;
                        user.IsDebug          = true;
                        await UserManager.UpdateAsync(user);

                        string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                        var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code },
                                                     protocol: Request.Url.Scheme);
                        user.IsAcceptedOffert = true;
                        UserManager.Update(user);
                        db.SaveChanges();
                        //Mailer.SendMail(user.Email, "Для подтверждения е-мэйла перейдите по <a href=\"" + callbackUrl + "\">ccылке</a>");
                        //  Mailer.SendRegistrationMail(user.RegisterName ?? model.Name, user.Email, callbackUrl);
                        EmailFactory.SendEmailAsync(new ForgotPassword(user, callbackUrl));
                        //await m.SendMessageAsync();
                        //await EmailFactory.SendEmailAsync(new Email(m));
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        UserManager.Delete(user);
                        ModelState.AddModelError("other", ex.Message);
                        return(View("Error", ModelState));
                    }

                    return(RedirectToAction("Index", "Users", new { name = model.Name }));
                }
                else
                {
                    //ModelState.AddModelError("Other", result.Errors.First());
                    AddErrors(result);
                    logger.Error(String.Join(",", result.Errors));
                }
            }
            return(View(model));
        }