private static PaymentParametersViewModel GetPaymentInfo(Subscription sub, ManBoxEntities ent) { PaymentParametersViewModel payParams = new PaymentParametersViewModel(); var delivery = Utilities.GetActiveDelivery(sub); var itemsTotal = Utilities.GetDeliveryTotal(delivery); var couponAmount = Utilities.CalculateCouponAmount(itemsTotal, delivery); var shippingFee = Utilities.CalculateShippingFee(itemsTotal); var total = itemsTotal + shippingFee - couponAmount; delivery.ShippingFee = shippingFee; delivery.CouponAmount = couponAmount; delivery.Amount = total; ent.SaveChanges(); payParams.SubscriptionId = sub.SubscriptionId; payParams.Total = total; if (sub.User != null) { payParams.User = new UserViewModel() { Email = sub.User.Email, Token = sub.Token, FirstName = sub.User.FirstName, LastName = sub.User.LastName, UserId = sub.User.UserId }; } return(payParams); }
/// <summary> /// sets correct delivery amounts /// gets the preapproval key of the paypal sender /// </summary> /// <param name="deliveryId"></param> /// <returns></returns> public ShipmentPaymentViewModel GetDeliveryPaymentInfo(int deliveryId) { using (ManBoxEntities ent = new ManBoxEntities()) { var delivery = ent.SubscriptionDeliveries.Single(d => d.SubscriptionDeliveryId == deliveryId); decimal deliveryAmount = 0; delivery.SubscriptionDeliveryModels.ToList().ForEach(dm => deliveryAmount += (dm.Model.ShopPrice * dm.Quantity)); var shippingFee = Utilities.CalculateShippingFee(deliveryAmount); var couponAmount = Utilities.CalculateCouponAmount(deliveryAmount, delivery); var total = deliveryAmount + shippingFee - couponAmount; delivery.Amount = deliveryAmount; delivery.ShippingFee = shippingFee; delivery.CouponAmount = couponAmount; ent.SaveChanges(); var shipmentPaymentModel = new ShipmentPaymentViewModel() { Total = total, TotalInt = Convert.ToInt32(total * 100), PayPalSenderEmail = delivery.Subscription.PayPalSenderEmail, PayPalPreapprovalKey = delivery.Subscription.PayPalPreapprovalKey, PaymillPayId = delivery.Subscription.PaymillPayId }; return(shipmentPaymentModel); } }
public ModificationResponseViewModel ConfirmModification(string token) { using (ManBoxEntities ent = new ManBoxEntities()) { var sub = ent.Subscriptions.FirstOrDefault(s => s.Token == token); if (sub.SubscriptionStateCV != CodeValues.SubscriptionState.Subscribed) { throw new Exception("Error: you cannot confirm a modification if you are not subscribed"); } var newDelivery = sub.SubscriptionDeliveries.FirstOrDefault(d => d.DeliveryStateCV == CodeValues.DeliveryState.New); var pendingDelivery = sub.SubscriptionDeliveries.FirstOrDefault(d => d.DeliveryStateCV == CodeValues.DeliveryState.Pending); var newDeliveryTotal = Utilities.GetDeliveryTotal(newDelivery); var pendingDeliveryTotal = Utilities.GetDeliveryTotal(pendingDelivery); // save it right away newDelivery.DeliveryStateCV = CodeValues.DeliveryState.Pending; pendingDelivery.DeliveryStateCV = CodeValues.DeliveryState.Dropped; ent.SaveChanges(); // return success message return(new ModificationResponseViewModel() { IsPaymentNeeded = false }); } }
private Subscription InitializeAnonymousSubscription(ManBoxEntities ent) { var newSubscription = new Subscription() { Token = Guid.NewGuid().ToString(), CreatedDatetime = DateTime.Now, IsActive = true, IsPaused = false, SubscriptionStateCV = CodeValues.SubscriptionState.InCart }; var newSubscriptionDelivery = new SubscriptionDelivery() { DeliveryDate = DateTime.Now.AddDays(defaultNextDeliveryInDays), DeliveryStateCV = CodeValues.DeliveryState.New, QueuedDatetime = DateTime.Now, DeliveryPaymentStatusCV = CodeValues.DeliveryPaymentStatus.None }; newSubscription.SubscriptionDeliveries.Add(newSubscriptionDelivery); ent.Subscriptions.Add(newSubscription); ent.SaveChanges(); return(newSubscription); }
public void SaveGiftPersonalization(string tk, string guestName, string giftMsg) { using (ManBoxEntities ent = new ManBoxEntities()) { var sub = ent.Subscriptions.Single(s => s.Token == tk); var giftMsgMaxLength = giftMsg.Length > 160 ? 160 : giftMsg.Length; var guestNameMaxLength = guestName.Length > 50 ? 50 : guestName.Length; giftMsg = giftMsg.Substring(0, giftMsgMaxLength); guestName = guestName.Substring(0, guestNameMaxLength); if (sub.Gift == null) { sub.Gift = new Gift() { GiftMessage = giftMsg, GuestName = guestName }; } else { sub.Gift.GiftMessage = giftMsg; sub.Gift.GuestName = guestName; } ent.SaveChanges(); } }
public SubscriptionSelectionViewModel GetActiveSelection() { string token = IdHelper.CurrentUser.Token; using (ManBoxEntities ent = new ManBoxEntities()) { Subscription sub = null; if (!string.IsNullOrEmpty(token)) { sub = ent.Subscriptions.FirstOrDefault(s => s.Token == token && s.IsActive); } if (string.IsNullOrEmpty(token) || sub == null || (sub.SubscriptionStateCV == CodeValues.SubscriptionState.Subscribed && !IdHelper.CurrentUser.IsAuthenticated)) { // init defaults for empty cart return(new SubscriptionSelectionViewModel() { ItemsTotal = 0M.ToCurrency(), SelectedProducts = new List <ProductSelectionViewModel>(), ShippingFee = 0M.ToCurrency(), SelectionTotal = 0M.ToCurrency(), SubscriptionId = 0, Token = string.Empty, IsSubscribed = false, DeliveryState = CodeValues.DeliveryState.New, CartNotificationMessage = GetCartNotificationMessage(sub ?? null) }); } return(GetDeliveryCart(ent, sub)); } }
/// <summary> /// sends an expiring login link /// </summary> /// <param name="email"></param> /// <returns>success</returns> public bool SendPasswordReset(string email) { using (ManBoxEntities ent = new ManBoxEntities()) { var user = ent.Users.FirstOrDefault(u => u.Email == email); if (user == null) { this.logger.Log(LogType.Warn, "Password reset attempt without valid email. Too many attempts is fishy."); return(false); } var encryptedToken = HttpUtility.UrlEncode(TokenEncrypt.EncryptTokenAsExpiring(user.Subscriptions.First().Token, DateTime.Now.AddDays(1))); var fromRecipient = new MailRecipient("*****@*****.**", "Support ManBox"); var toRecipient = new MailRecipient(email, user.FirstName); var domain = Utilities.GetCountryDomain(user.Country.IsoCode); var linkToken = string.Format("http://{0}/{1}/Account/TokenLogin?token={2}", domain, user.Language.IsoCode, encryptedToken); mailService.SendMail <PasswordResetMail>(toRecipient, fromRecipient, new PasswordResetMail() { RootUrl = "http://" + domain, LanguageIso = user.Language.IsoCode, Date = DateTime.Now, Name = user.FirstName, Subject = "Password Reset", LinkToken = linkToken }); return(true); } }
public UserViewModel GetUserByEmail(string email) { using (ManBoxEntities ent = new ManBoxEntities()) { var user = (from u in ent.Users where u.Email == email select u).FirstOrDefault(); if (user == null) { return(null); } return(new UserViewModel() { UserId = user.UserId, Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, Token = user.Subscriptions.FirstOrDefault().Token, LanguageId = user.LanguageId, LanguageIsoCode = user.Language.IsoCode }); } }
private Subscription InitializeGiftOrderForSubscribedCustomer(ManBoxEntities ent, string existingSubToken) { var existingSub = ent.Subscriptions.Single(s => s.Token == existingSubToken); var newGiftOrder = new Subscription() { Token = Guid.NewGuid().ToString(), CreatedDatetime = DateTime.Now, IsActive = true, IsPaused = false, SubscriptionStateCV = CodeValues.SubscriptionState.InCart, Gift = new Gift(), User = existingSub.User }; var newSubscriptionDelivery = new SubscriptionDelivery() { DeliveryDate = DateTime.Now.AddDays(defaultNextDeliveryInDays), DeliveryStateCV = CodeValues.DeliveryState.New, QueuedDatetime = DateTime.Now, DeliveryPaymentStatusCV = CodeValues.DeliveryPaymentStatus.None }; newGiftOrder.SubscriptionDeliveries.Add(newSubscriptionDelivery); ent.Subscriptions.Add(newGiftOrder); ent.SaveChanges(); return(newGiftOrder); }
public void SubscribeNewsletterEmail(string email) { using (ManBoxEntities ent = new ManBoxEntities()) { var existing = ent.Newsletters.Any(n => n.Email == email); if (!existing) { ent.Newsletters.Add(new Newsletter() { Email = email, Subscribed = true, LanguageId = IdHelper.CurrentUser.LanguageId, CountryId = IdHelper.CurrentUser.CountryId }); var couponCode = "man" + Guid.NewGuid().ToString().Substring(0, 6); ent.Coupons.Add(new Coupon() { Amount = 3, Code = couponCode, Enabled = true, ExpirationDate = DateTime.Now.AddMonths(12), NumberAvailable = 1 }); ent.SaveChanges(); SendNewsletterWelcomeMail(email, couponCode); } } }
public UserViewModel TokenLogin(string encryptedToken) { var subscrToken = TokenEncrypt.DecryptExpiringToken(encryptedToken); if (string.IsNullOrEmpty(subscrToken)) { return(null); } using (ManBoxEntities ent = new ManBoxEntities()) { var sub = ent.Subscriptions.Single(s => s.Token == subscrToken); if (sub == null) { throw new Exception("Could not find subscription for token login"); } return(new UserViewModel() { Email = sub.User.Email, Token = subscrToken, FirstName = sub.User.Email, LastName = sub.User.Email, UserId = sub.User.UserId, }); } }
/// <summary> /// Get a subscription delivery summary with products and updated totals /// </summary> private SubscriptionSelectionViewModel GetDeliveryCart(ManBoxEntities ent, Subscription sub) { var activeDelivery = Utilities.GetActiveDelivery(sub); decimal itemsTotal = Utilities.GetDeliveryTotal(activeDelivery); decimal shippingFee = Utilities.CalculateShippingFee(itemsTotal); decimal couponAmount = Utilities.CalculateCouponAmount(itemsTotal, activeDelivery); decimal selectionTotal = itemsTotal + shippingFee - couponAmount; return(new SubscriptionSelectionViewModel() { Token = sub.Token, SelectedProducts = GetSubscriptionDeliveryProducts(activeDelivery, ent), SubscriptionId = sub.SubscriptionId, ItemsTotal = itemsTotal.ToCurrency(), ShippingFee = itemsTotal > 0 ? shippingFee.ToCurrency() : 0M.ToCurrency(), CouponAmount = couponAmount > 0 ? (0 - couponAmount).ToCurrency() : string.Empty, CouponLabel = Utilities.GetCouponLabel(activeDelivery.Coupon), SelectionTotal = itemsTotal > 0 ? selectionTotal.ToCurrency() : 0M.ToCurrency(), NextDeliveryDate = activeDelivery.DeliveryDate.Value.ToString("d MMMM yyyy"), IsSubscribed = sub.SubscriptionStateCV == CodeValues.SubscriptionState.Subscribed, DeliveryState = activeDelivery.DeliveryStateCV, CartNotificationMessage = GetCartNotificationMessage(sub, activeDelivery), Pack = GetSubscriptionDeliveryPack(activeDelivery, ent) }); }
public SubscriptionSelectionViewModel RemovePackFromSubscription(int packId) { string token = IdHelper.CurrentUser.Token; using (ManBoxEntities ent = new ManBoxEntities()) { Subscription sub = GetCurrentCart(token, ent); var delivery = Utilities.GetActiveDelivery(sub); var packItems = delivery.SubscriptionDeliveryModels.Where(m => m.PackId == packId).ToList(); foreach (var i in packItems) { delivery.SubscriptionDeliveryModels.Remove(i); } ent.SaveChanges(); // requery with updated data sub = ent.Subscriptions .Include(s => s.SubscriptionDeliveries.Select(d => d.SubscriptionDeliveryModels.Select(m => m.Model.Product))) .FirstOrDefault(s => s.Token == token && s.IsActive); if (sub.SubscriptionStateCV == CodeValues.SubscriptionState.Subscribed && !IdHelper.CurrentUser.IsAuthenticated) { throw new Exception("cannot remove an item from an existing subscription when logged out"); } return(GetDeliveryCart(ent, sub)); } }
public OrdersOverviewViewModel GetOrdersOverview() { using (ManBoxEntities ent = new ManBoxEntities()) { var deliveries = (from d in ent.SubscriptionDeliveries where d.Subscription.Token == IdHelper.CurrentUser.Token && d.Subscription.SubscriptionStateCV == CodeValues.SubscriptionState.Subscribed && (d.DeliveryStateCV == CodeValues.DeliveryState.Sent || d.DeliveryStateCV == CodeValues.DeliveryState.Processing || d.DeliveryStateCV == CodeValues.DeliveryState.Pending) select new { Date = d.DeliveryDate, DeliveryId = d.SubscriptionDeliveryId, DeliveryState = d.DeliveryStateCV, ShippingFee = d.ShippingFee, CouponAmount = d.CouponAmount, Products = (from dm in ent.SubscriptionDeliveryModels where dm.SubscriptionDeliveryId == d.SubscriptionDeliveryId select new { Price = dm.Model.ShopPrice, Quantity = dm.Quantity, ProductName = (from tt in ent.TranslationTexts where tt.LanguageId == IdHelper.CurrentUser.LanguageId && tt.TranslationId == dm.Model.Product.TitleTrId select tt.Text).FirstOrDefault(), ProductReference = dm.Model.Product.Reference, ModelName = dm.Model.Name, TotalPrice = dm.Quantity * dm.Model.ShopPrice }) }).ToList(); // mapping List <OrderDeliveryViewModel> orders = new List <OrderDeliveryViewModel>(); deliveries.ForEach(d => orders.Add(new OrderDeliveryViewModel() { Amount = (from p in d.Products.ToList() select p.TotalPrice).Sum() + d.ShippingFee - d.CouponAmount, CouponAmount = d.CouponAmount, Date = d.Date, DeliveryId = d.DeliveryId, DeliveryState = d.DeliveryState, ShippingFee = d.ShippingFee, Products = d.Products.ToList().Select(p => new DeliveryProductViewModel() { ModelName = p.ModelName, Price = p.Price, ProductName = p.ProductName, Quantity = p.Quantity, TotalPrice = p.TotalPrice, ProductReference = p.ProductReference }).ToList() }) ); return(new OrdersOverviewViewModel() { Orders = orders }); } }
public PaymentParametersViewModel GetPaymentInfo(string subscrToken) { using (ManBoxEntities ent = new ManBoxEntities()) { Subscription sub = ent.Subscriptions.FirstOrDefault(s => s.Token == subscrToken); return(GetPaymentInfo(sub, ent)); } }
public UserViewModel Login(string email, string password, string subscrToken) { using (ManBoxEntities ent = new ManBoxEntities()) { var user = ent.Users.FirstOrDefault(u => u.Email == email.ToLower() && u.Password == password); if (user != null) { // first try to load an active sub for the logged in user var activeSub = user.Subscriptions.FirstOrDefault(); // if he does not have any sub yet if (activeSub == null) { // retrieve anonymous sub or previously used if (!string.IsNullOrEmpty(subscrToken)) { activeSub = ent.Subscriptions.FirstOrDefault(s => s.Token == subscrToken && (s.UserId == user.UserId || s.UserId == null)); } // if no token create a subscription for this user else { activeSub = ent.Subscriptions.Add(new Subscription() { Token = Guid.NewGuid().ToString(), CreatedDatetime = DateTime.Now, IsActive = true, IsPaused = false, SubscriptionStateCV = CodeValues.SubscriptionState.InCart }); } // at this point if we still don't have a sub, something failed really bad if (activeSub == null) { throw new Exception("Login failed, no active subscription could be found or created"); } // link the user to the anonymous sub if any activeSub.User = user; ent.SaveChanges(); } return(new UserViewModel() { Email = user.Email, Token = activeSub.Token, FirstName = user.FirstName, LastName = user.LastName, UserId = user.UserId }); } else { return(null); } } }
public void UpdatePassword(string newPassword) { using (ManBoxEntities ent = new ManBoxEntities()) { var user = ent.Users.Single(u => u.Email == IdHelper.CurrentUser.Email); user.Password = newPassword; ent.SaveChanges(); } }
public void StorePreapprovalAndCharge(PayPalResponseViewModel response, string thankYouUrl, string cancelUrl) { try { logger.Log(LogType.Info, "Trying to process response: " + response.ToString()); if (string.IsNullOrEmpty(response.Sender_Email) || string.IsNullOrEmpty(response.Preapproval_Key)) { throw new Exception("send mail or preapproval key missing"); } using (ManBoxEntities ent = new ManBoxEntities()) { var sub = ent.Subscriptions.Single(s => s.SubscriptionId == response.SubscriptionId); sub.PayPalPreapprovalKey = response.Preapproval_Key; sub.PayPalSenderEmail = response.Sender_Email; ent.SaveChanges(); bool paymentSuccess = false; #if DEBUG paymentSuccess = true; #else paymentSuccess = ChargePayPalSuccess(sub, ent, thankYouUrl, cancelUrl); #endif if (paymentSuccess) { var delivery = sub.SubscriptionDeliveries .OrderByDescending(d => d.QueuedDatetime) .FirstOrDefault(d => d.DeliveryStateCV == CodeValues.DeliveryState.New); sub.IsActive = true; sub.SubscriptionStateCV = CodeValues.SubscriptionState.Subscribed; delivery.DeliveryStateCV = CodeValues.DeliveryState.Processing; delivery.DeliveryPaymentStatusCV = CodeValues.DeliveryPaymentStatus.Paid; if (delivery.Coupon != null) { delivery.Coupon.NumberAvailable--; } ent.SaveChanges(); SendSubscriptionConfirmationMail(sub, ent); } else { logger.Log(LogType.Error, "could not successfully charge with the preapproval key"); } } } catch (Exception e) { var msg = string.Format("send mail: {0} - memo: {1} - exception: {2}", response.Sender_Email, response.Memo, e.Message); logger.Log(LogType.Error, e.Message + msg); } }
private void UpdateStock(SubscriptionDelivery delivery, ManBoxEntities ent) { foreach (var sm in delivery.SubscriptionDeliveryModels) { sm.Model.AmountInStock -= sm.Quantity; } ent.SaveChanges(); }
public Dictionary <string, int> GetAvailableLanguages() { var languages = new Dictionary <string, int>(); using (ManBoxEntities ent = new ManBoxEntities()) { ent.Languages.ToList().ForEach(l => languages.Add(l.IsoCode, l.LanguageId)); } return(languages); }
private bool ChargePayPalSuccess(Subscription sub, ManBoxEntities ent, string thankYouUrl, string cancelUrl) { var payPalAccount = ConfigurationManager.AppSettings[AppConstants.AppSettingsKeys.PayPalAccount] as string; var paymentInfo = GetPaymentInfo(sub, ent); var receiverList = new ReceiverList(); receiverList.receiver = new List <Receiver>(); receiverList.receiver.Add(new Receiver(paymentInfo.Total) { email = payPalAccount }); var service = new AdaptivePaymentsService(); PayResponse response = service.Pay(new PayRequest( new RequestEnvelope("en_US"), "PAY", cancelUrl, "EUR", receiverList, thankYouUrl) { senderEmail = sub.PayPalSenderEmail, preapprovalKey = sub.PayPalPreapprovalKey }); if (response == null) { logger.Log(LogType.Fatal, "No Response was received from PayPal Payrequest service"); } logger.Log(LogType.Info, string.Format("paykey is {0} . exec status is {1}", response.payKey ?? "", response.paymentExecStatus ?? "")); // error handling if (response.error != null && response.error.FirstOrDefault() != null) { logger.Log(LogType.Error, string.Format("error {0}", response.error.FirstOrDefault().message)); } // error handling if (response.payErrorList != null && response.payErrorList.payError.FirstOrDefault() != null) { logger.Log(LogType.Error, string.Format("payerror {0}", response.payErrorList.payError.FirstOrDefault().error.message)); } //payment exec status must be : COMPLETED if (!string.IsNullOrEmpty(response.paymentExecStatus) && response.paymentExecStatus.ToLower() == PayPalConstants.PaymentExecStatus.Completed.ToLower()) { return(true); } return(false); }
public void upcoming_notification_mail_send_is_stored_in_message_history() { // Act _repo.SendUpcomingBoxNotifications(); // Assert using (ManBoxEntities ent = new ManBoxEntities()) { // message history entry was created var msg = ent.SubscriptionDeliveryMessages.FirstOrDefault(m => m.SubscriptionDeliveryId == 123); Assert.AreEqual(CodeValues.DeliveryMessageType.Upcoming, msg.DeliveryMessageTypeCV); } }
public void CancelModification(string token) { using (ManBoxEntities ent = new ManBoxEntities()) { var sub = ent.Subscriptions.FirstOrDefault(s => s.Token == token); if (sub.SubscriptionStateCV != CodeValues.SubscriptionState.Subscribed) { throw new Exception("Error: you cannot cancel a modification if you are not subscribed"); } var newDelivery = sub.SubscriptionDeliveries.FirstOrDefault(d => d.DeliveryStateCV == CodeValues.DeliveryState.New); newDelivery.DeliveryStateCV = CodeValues.DeliveryState.Dropped; ent.SaveChanges(); } }
public void UpdateShipmentPaymentStatus(int deliveryId, string deliveryPaymentStatus) { using (ManBoxEntities ent = new ManBoxEntities()) { var delivery = ent.SubscriptionDeliveries.Single(d => d.SubscriptionDeliveryId == deliveryId); if (CodeValues.DeliveryPaymentStatus.GetAll().Any(s => s == deliveryPaymentStatus)) { throw new Exception("Unexpected codevalue for deliverypaymentstatus"); } delivery.DeliveryPaymentStatusCV = deliveryPaymentStatus; ent.SaveChanges(); } }
public CheckoutShippingViewModel GetSubscriptionCheckoutInfo(string subscrToken) { using (ManBoxEntities ent = new ManBoxEntities()) { Subscription completeSub = null; var viewModel = new CheckoutShippingViewModel(); var sub = ent.Subscriptions.FirstOrDefault(s => s.Token == subscrToken); if (sub == null) { throw new Exception("Subscription not found from checkout"); } viewModel.IsSubscriptionValid = CheckSubscriptionValidity(sub); var user = sub.User; if (user != null) { completeSub = user.Subscriptions.FirstOrDefault(s => s.Address != null); viewModel.Email = user.Email; viewModel.FirstName = user.FirstName; viewModel.LastName = user.LastName; viewModel.Phone = user.Phone; } if (completeSub != null) { viewModel.City = completeSub.Address.City; viewModel.CountryId = completeSub.Address.CountryId; viewModel.PostalCode = completeSub.Address.PostalCode; viewModel.Province = completeSub.Address.Province; viewModel.Street = completeSub.Address.Street; } var paymentInfo = GetPaymentInfo(sub, ent); viewModel.TotalInt = paymentInfo.TotalInt; viewModel.Token = subscrToken; viewModel.IsSubscriptionValid = CheckSubscriptionValidity(sub); if (sub.Gift != null) { viewModel.GuestName = sub.Gift.GuestName; viewModel.GiftMsg = sub.Gift.GiftMessage; } return(viewModel); } }
public SubscriptionSelectionViewModel AddPackToSubscription(int packId) { string token = IdHelper.CurrentUser.Token; using (ManBoxEntities ent = new ManBoxEntities()) { Subscription sub = GetCurrentCart(token, ent); var activeDelivery = Utilities.GetActiveDelivery(sub); // you cannot have more than one pack if (activeDelivery.SubscriptionDeliveryModels.Any(m => m.PackId != null)) { var packItems = activeDelivery.SubscriptionDeliveryModels.Where(m => m.PackId != null).ToList(); foreach (var pi in packItems) { ent.SubscriptionDeliveryModels.Remove(pi); } } var pack = ent.Packs.Single(p => p.PackId == packId); foreach (var p in pack.ProductPacks) { var duplicate = activeDelivery.SubscriptionDeliveryModels.FirstOrDefault(m => m.Model.ProductId == p.ProductId); if (duplicate != null) { activeDelivery.SubscriptionDeliveryModels.Remove(duplicate); ent.SaveChanges(); } activeDelivery.SubscriptionDeliveryModels.Add(new SubscriptionDeliveryModel() { Model = p.Product.Models.First(), Quantity = p.Quantity, PackId = packId }); } ent.SaveChanges(); // requery with updated data sub = ent.Subscriptions .Include(s => s.SubscriptionDeliveries.Select(d => d.SubscriptionDeliveryModels.Select(m => m.Model.Product))) .FirstOrDefault(s => s.Token == sub.Token && s.IsActive); return(GetDeliveryCart(ent, sub)); } }
public void UpdateAddress(AddressViewModel newAddress) { using (ManBoxEntities ent = new ManBoxEntities()) { var sub = ent.Subscriptions.FirstOrDefault(s => s.User.Email == IdHelper.CurrentUser.Email); sub.Address.City = newAddress.City; sub.Address.CountryId = newAddress.CountryId; sub.Address.FirstName = newAddress.FirstName; sub.Address.LastName = newAddress.LastName; sub.Address.PostalCode = newAddress.PostalCode; sub.Address.Province = newAddress.Province; sub.Address.Street = newAddress.Street; ent.SaveChanges(); } }
public void upcoming_notification_mail_not_sent_if_already_sent() { // Act var firstRunResult = _repo.SendUpcomingBoxNotifications(); var secondRunResult = _repo.SendUpcomingBoxNotifications(); // Assert Assert.IsTrue(firstRunResult.NotificationsSent > 0); Assert.IsTrue(secondRunResult.NotificationsSent == 0); using (ManBoxEntities ent = new ManBoxEntities()) { // message history entry was created var msg = ent.SubscriptionDeliveryMessages.First(m => m.SubscriptionDeliveryId == 123 && m.DeliveryMessageTypeCV == CodeValues.DeliveryMessageType.Upcoming); Assert.IsNotNull(msg); } }
public ReScheduleDeliveryViewModel ReScheduleDelivery(int deliveryId, bool rushNow, int?snoozeWeeks) { DateTime newDateTime; bool shippableTomorrow = true; using (ManBoxEntities ent = new ManBoxEntities()) { var pendingDelivery = ent.SubscriptionDeliveries.Single(d => d.SubscriptionDeliveryId == deliveryId && d.DeliveryStateCV == CodeValues.DeliveryState.Pending && d.Subscription.User.Email == IdHelper.CurrentUser.Email); if (rushNow) { newDateTime = DateTime.Now.AddDays(1); // check stocks if it's to be shipped within 7 days shippableTomorrow = pendingDelivery.SubscriptionDeliveryModels.ToList().All(m => m.Model.AmountInStock > 1); /// if asked to rush and stock is insufficient, set a close date if (!shippableTomorrow) { newDateTime = DateTime.Now.AddDays(7); } } else { if (pendingDelivery.DeliveryDate > DateTime.Now.AddMonths(1)) { return(new ReScheduleDeliveryViewModel() { CannotSnoozeYet = true }); } newDateTime = pendingDelivery.DeliveryDate.Value.AddDays(7 * snoozeWeeks.Value); } pendingDelivery.DeliveryDate = newDateTime; ent.SaveChanges(); return(new ReScheduleDeliveryViewModel() { ShippableTomorrow = shippableTomorrow, NewDate = newDateTime }); } }
public GiftPacksViewModel GetGiftPacks() { var model = new GiftPacksViewModel(); var user = IdHelper.CurrentUser; using (ManBoxEntities ent = new ManBoxEntities()) { var packs = from pa in ent.Packs where pa.IsAGift orderby pa.Position descending, pa.ShopPrice select new PackViewModel { PackId = pa.PackId, Title = (from tt in ent.TranslationTexts where tt.TranslationId == pa.TitleTrId && tt.LanguageId == user.LanguageId select tt.Text).FirstOrDefault(), Description = (from tt in ent.TranslationTexts where tt.TranslationId == pa.DescrTrId && tt.LanguageId == user.LanguageId select tt.Text).FirstOrDefault(), Price = pa.ShopPrice, GiftVoucherValue = pa.GiftVoucherValue, AdvisedPrice = pa.AdvisedPrice, Products = (from p in pa.ProductPacks select new ProductViewModel { Quantity = p.Quantity, Brand = p.Product.Brand != null ? p.Product.Brand.Name : null, ProductId = p.ProductId, Reference = p.Product.Reference, Title = (from tt in ent.TranslationTexts where tt.TranslationId == p.Product.TitleTrId && tt.LanguageId == user.LanguageId select tt.Text).FirstOrDefault(), Description = (from tt in ent.TranslationTexts where tt.TranslationId == p.Product.DescriptionTrId && tt.LanguageId == user.LanguageId select tt.Text).FirstOrDefault(), DescriptionDetail = (from tt in ent.TranslationTexts where tt.TranslationId == p.Product.DescriptionDetailTrId && tt.LanguageId == user.LanguageId select tt.Text).FirstOrDefault(), Models = (from m in ent.Models where m.ProductId == p.ProductId orderby m.Name select new ModelViewModel() { ModelId = m.ModelId, Name = m.Name, ShopPrice = m.ShopPrice }), AdvisedPrice = (from m in ent.Models where m.ProductId == p.ProductId orderby m.ShopPrice select m).FirstOrDefault().AdvisedPrice // lowest price }) }; model.GiftPacks = packs.ToList(); } return(model); }