Example #1
0
        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);
            }
        }
Example #2
0
        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);
        }
Example #3
0
        /// <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);
            }
        }
Example #4
0
        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();
            }
        }
Example #5
0
        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));
            }
        }
Example #6
0
        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
                });
            }
        }
Example #7
0
        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);
                }
            }
        }
Example #8
0
        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);
        }
Example #9
0
        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);
        }
Example #10
0
        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));
            }
        }
Example #11
0
        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);
                }
            }
        }
Example #12
0
 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();
     }
 }
Example #13
0
        private void UpdateStock(SubscriptionDelivery delivery, ManBoxEntities ent)
        {
            foreach (var sm in delivery.SubscriptionDeliveryModels)
            {
                sm.Model.AmountInStock -= sm.Quantity;
            }

            ent.SaveChanges();
        }
Example #14
0
        public SubscriptionSelectionViewModel ChangeSelectionModel(int newModelId, int replacedModelId, int?packId)
        {
            string token = IdHelper.CurrentUser.Token;

            using (ManBoxEntities ent = new ManBoxEntities())
            {
                //ent.Configuration.LazyLoadingEnabled = false;
                Subscription sub = GetCurrentCart(token, ent);

                var activeDelivery = Utilities.GetActiveDelivery(sub);

                var oldModel = activeDelivery.SubscriptionDeliveryModels.FirstOrDefault(m => m.ModelId == replacedModelId && m.PackId == packId);
                var newModel = new SubscriptionDeliveryModel()
                {
                    ModelId = newModelId, PackId = oldModel.PackId, Quantity = oldModel.Quantity
                };

                // merge quantities in case of duplicate
                var duplicate = activeDelivery.SubscriptionDeliveryModels.FirstOrDefault(m => m.ModelId == newModel.ModelId && m.PackId == newModel.PackId);
                if (duplicate != null)
                {
                    activeDelivery.SubscriptionDeliveryModels.Remove(duplicate);
                    ent.SaveChanges();

                    newModel.Quantity += duplicate.Quantity;
                }

                activeDelivery.SubscriptionDeliveryModels.Remove(oldModel);
                ent.SaveChanges();

                activeDelivery.SubscriptionDeliveryModels.Add(newModel);
                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));
            }
        }
Example #15
0
        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();
            }
        }
Example #16
0
        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();
            }
        }
Example #17
0
        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
                });
            }
        }
Example #18
0
        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();
            }
        }
Example #19
0
        /// <summary>
        /// unsubscribes from newsletter any registered user or mailing list entry
        /// </summary>
        /// <param name="email"></param>
        public void Unsubscribe(string email)
        {
            using (ManBoxEntities ent = new ManBoxEntities())
            {
                var newsletterUser = ent.Newsletters.FirstOrDefault(u => u.Email == email);

                if (newsletterUser != null)
                {
                    newsletterUser.Subscribed = false;
                }

                var registeredUser = ent.Users.FirstOrDefault(u => u.Email == email);
                if (registeredUser != null)
                {
                    registeredUser.IsOptin = false;
                }

                ent.SaveChanges();
            }
        }
Example #20
0
        /// <summary>
        /// retrieve customer by token
        /// if token null empty or no subscription ==> create a new subscription
        /// </summary>
        /// <param name="token"></param>
        /// <param name="ent"></param>
        /// <returns></returns>
        private Subscription GetCurrentCart(string token, ManBoxEntities ent)
        {
            Subscription sub = null;

            if (token != null)
            {
                sub = ent.Subscriptions
                      .Include(s => s.SubscriptionDeliveries.Select(d => d.SubscriptionDeliveryModels.Select(m => m.Model.Product)))
                      .FirstOrDefault(s => s.Token == token && s.IsActive);

                // subscribed user requesting a modification delivery
                if (sub != null && sub.SubscriptionStateCV == CodeValues.SubscriptionState.Subscribed)
                {
                    if (!IdHelper.CurrentUser.IsAuthenticated)
                    {
                        // reset cart for existing subscribed token but logged out
                        sub = InitializeAnonymousSubscription(ent);

                        //throw new Exception("cannot modify a processing delivery when logged out");
                    }

                    if (sub.SubscriptionDeliveries.Any(d => d.DeliveryStateCV == CodeValues.DeliveryState.Processing))
                    {
                        throw new Exception("cannot modify a processing delivery");
                    }
                    // create a new delivery if not any yet
                    else if (!sub.SubscriptionDeliveries.Any(d => d.DeliveryStateCV == CodeValues.DeliveryState.New))
                    {
                        var pendingDelivery = sub.SubscriptionDeliveries.FirstOrDefault(s => s.DeliveryStateCV == CodeValues.DeliveryState.Pending);
                        sub.SubscriptionDeliveries.Add(GetCopyNewDelivery(pendingDelivery));
                        ent.SaveChanges();
                    }
                }
            }

            if (sub == null) // create anonymous subscription
            {
                sub = InitializeAnonymousSubscription(ent);
            }
            return(sub);
        }
Example #21
0
        public void ConfirmShipmentSent(int deliveryId, bool notify)
        {
            using (ManBoxEntities ent = new ManBoxEntities())
            {
                var delivery = ent.SubscriptionDeliveries.Single(d => d.SubscriptionDeliveryId == deliveryId);
                delivery.DeliveryStateCV         = CodeValues.DeliveryState.Sent;
                delivery.DeliveryPaymentStatusCV = CodeValues.DeliveryPaymentStatus.Paid;

                // add next delivery
                delivery.Subscription.SubscriptionDeliveries.Add(GetCopyPendingDelivery(delivery));

                if (notify)
                {
                    SendShipmentConfirmationMail(delivery, ent);
                    ShipmentRepository.StoreDeliveryMessage(delivery, CodeValues.DeliveryMessageType.ShippingConfirmation);
                }

                ent.SaveChanges();

                // updates stock
                UpdateStock(delivery, ent);
            }
        }
Example #22
0
        public SubscriptionSelectionViewModel ApplyCouponToDelivery(string code, string token)
        {
            Subscription sub = null;

            using (ManBoxEntities ent = new ManBoxEntities())
            {
                var coupon = (from c in ent.Coupons
                              where c.Code == code.ToLower() &&
                              c.Enabled &&
                              c.NumberAvailable > 0 &&
                              c.ExpirationDate > DateTime.Now
                              select c).FirstOrDefault();

                if (coupon != null)
                {
                    if (coupon.Percentage == null ^ coupon.Amount == null)
                    {
                        sub = ent.Subscriptions.FirstOrDefault(s => s.Token == token);
                        var delivery = sub.SubscriptionDeliveries.Single(d => d.DeliveryStateCV == CodeValues.DeliveryState.New);

                        delivery.CouponId = coupon.CouponId;
                        ent.SaveChanges();
                    }
                    else
                    {
                        throw new Exception("Trying to add an invalid coupon. Coupons must have an amount OR a percentage but never both");
                    }
                }

                // 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);

                return(GetDeliveryCart(ent, sub));
            }
        }
Example #23
0
        /// <summary>
        /// Add to subscription
        /// Creates a NEW delivery if modifying a subscribed selection
        /// Creates a new subscription if the user is anonymous (no token yet) and returns a new token in this case
        /// </summary>
        /// <param name="modelId"></param>
        /// <param name="quantity"></param>
        /// <param name="token"></param>
        /// <returns>Updated subscription</returns>
        public SubscriptionSelectionViewModel AddToSubscription(int modelId, int quantity)
        {
            string token = IdHelper.CurrentUser.Token;

            using (ManBoxEntities ent = new ManBoxEntities())
            {
                //ent.Configuration.LazyLoadingEnabled = false;
                Subscription sub = GetCurrentCart(token, ent);

                var activeDelivery = Utilities.GetActiveDelivery(sub);

                var selectionModel = activeDelivery.SubscriptionDeliveryModels.FirstOrDefault(m => m.ModelId == modelId);
                if (selectionModel != null)
                {
                    if ((selectionModel.Quantity + quantity) <= maxModelQuantity)
                    {
                        selectionModel.Quantity += quantity;
                    }
                }
                else
                {
                    activeDelivery.SubscriptionDeliveryModels.Add(new SubscriptionDeliveryModel()
                    {
                        ModelId = modelId, Quantity = quantity
                    });
                }

                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));
            }
        }
Example #24
0
        public void ConfirmPaymillPayment(string subscrToken, string paymillToken, string paymillClientId, string paymillPayId)
        {
            try
            {
                logger.Log(LogType.Info, "Confirming paymill payment");

                using (ManBoxEntities ent = new ManBoxEntities())
                {
                    var sub = ent.Subscriptions.Single(s => s.Token == subscrToken);
                    sub.PaymillClientId     = paymillClientId;
                    sub.PaymillPayId        = paymillPayId;
                    sub.PaymillToken        = paymillToken;
                    sub.IsActive            = true;
                    sub.SubscriptionStateCV = CodeValues.SubscriptionState.Subscribed;

                    var delivery = sub.SubscriptionDeliveries
                                   .OrderByDescending(d => d.QueuedDatetime)
                                   .FirstOrDefault(d => d.DeliveryStateCV == CodeValues.DeliveryState.New);
                    delivery.DeliveryStateCV         = CodeValues.DeliveryState.Processing;
                    delivery.DeliveryPaymentStatusCV = CodeValues.DeliveryPaymentStatus.Paid;

                    if (delivery.Coupon != null)
                    {
                        delivery.Coupon.NumberAvailable--;
                    }

                    ent.SaveChanges();

                    SendSubscriptionConfirmationMail(sub, ent);
                }
            }
            catch (Exception e)
            {
                var msg = string.Format(" could not store paymill data!");
                logger.Log(LogType.Error, e.Message + msg);
            }
        }
Example #25
0
        public NotificationResultViewModel SendUpcomingBoxNotifications()
        {
            try
            {
                int notificationsSent = 0;

                Stopwatch sw = new Stopwatch();
                sw.Start();

                using (ManBoxEntities ent = new ManBoxEntities())
                {
                    var upcomingDeliveries = from sd in ent.SubscriptionDeliveries
                                             where sd.DeliveryStateCV == CodeValues.DeliveryState.Pending &&
                                             sd.Subscription.GiftId == null &&
                                             sd.Subscription.SubscriptionStateCV == CodeValues.SubscriptionState.Subscribed &&
                                             EntityFunctions.AddDays(sd.DeliveryDate.Value, -daysBefore).Value < DateTime.Now &&
                                             !sd.SubscriptionDeliveryMessages.Any(m => m.DeliveryMessageTypeCV == CodeValues.DeliveryMessageType.Upcoming)
                                             select new
                    {
                        SubscriptionDelivery = sd,
                        Name       = sd.Subscription.User.FirstName,
                        Token      = sd.Subscription.Token,
                        Email      = sd.Subscription.User.Email,
                        LangIso    = sd.Subscription.User.Language.IsoCode,
                        CountryIso = sd.Subscription.User.Country.IsoCode,
                        Address    = sd.Subscription.Address,
                        Products   = from m in sd.SubscriptionDeliveryModels
                                     select new
                        {
                            ProductName = (from tt in ent.TranslationTexts where tt.TranslationId == m.Model.Product.TitleTrId && tt.LanguageId == sd.Subscription.User.LanguageId select tt.Text).FirstOrDefault(),
                            ModelName   = m.Model.Name,
                            Quantity    = m.Quantity,
                            Price       = m.Model.ShopPrice,
                            TotalPrice  = m.Model.ShopPrice * m.Quantity
                        }
                    };

                    var notificationMails = new List <UpcomingBoxNotificationMail>();

                    foreach (var del in upcomingDeliveries)
                    {
                        var itemsTotal   = Utilities.GetDeliveryTotal(del.SubscriptionDelivery);
                        var shippingFee  = Utilities.CalculateShippingFee(itemsTotal);
                        var couponAmount = Utilities.CalculateCouponAmount(itemsTotal, del.SubscriptionDelivery);
                        var total        = itemsTotal + shippingFee - couponAmount;
                        var couponLabel  = Utilities.GetCouponLabel(del.SubscriptionDelivery.Coupon);

                        var products         = new List <MailProduct>();
                        var notificationMail = new UpcomingBoxNotificationMail()
                        {
                            Name        = del.Name,
                            Email       = del.Email,
                            Token       = del.Token,
                            LanguageIso = del.LangIso,
                            CountryIso  = del.CountryIso,
                            Address     = new MailAddress()
                            {
                                City       = del.Address.City,
                                Street     = del.Address.Street,
                                Province   = del.Address.Province,
                                PostalCode = del.Address.PostalCode
                            },
                            SubTotal     = itemsTotal,
                            Total        = total,
                            ShippingFee  = shippingFee,
                            CouponAmount = couponAmount,
                            CouponLabel  = couponLabel
                        };

                        foreach (var prod in del.Products)
                        {
                            products.Add(new MailProduct()
                            {
                                ModelName   = prod.ModelName,
                                ProductName = prod.ProductName,
                                Price       = prod.Price,
                                Quantity    = prod.Quantity,
                                TotalPrice  = prod.TotalPrice
                            });
                        }

                        notificationMail.Products = products;

                        SendMail(notificationMail);
                        ShipmentRepository.StoreDeliveryMessage(del.SubscriptionDelivery, CodeValues.DeliveryMessageType.Upcoming);

                        notificationsSent++;
                    }

                    sw.Stop();
                    ent.SaveChanges();
                }

                return(new NotificationResultViewModel()
                {
                    NotificationsSent = notificationsSent,
                    EndedDateTime = DateTime.Now,
                    ElapsedTime = sw.Elapsed,
                    MessageType = CodeValues.DeliveryMessageType.Upcoming
                });
            }
            catch (Exception e)
            {
                logger.Log(e);
                throw;
            }
        }
Example #26
0
        public PaymentParametersViewModel SaveShippingInfo(CheckoutShippingViewModel shippingInfo, string subscrToken)
        {
            using (ManBoxEntities ent = new ManBoxEntities())
            {
                var          user = ent.Users.SingleOrDefault(u => u.Email == shippingInfo.Email);
                Subscription sub  = ent.Subscriptions.FirstOrDefault(s => s.Token == subscrToken);

                if (user == null)
                {
                    sub.User = new User()
                    {
                        CountryId       = shippingInfo.CountryId,
                        CreatedDatetime = DateTime.Now,
                        Email           = shippingInfo.Email.ToLower(),
                        FirstName       = shippingInfo.FirstName,
                        IsOptin         = true,
                        LastName        = shippingInfo.LastName,
                        Password        = shippingInfo.Password,
                        SignInTypeCV    = CodeValues.SignInType.EmailPass,
                        Phone           = shippingInfo.Phone,
                        LanguageId      = IdHelper.CurrentUser.LanguageId
                    };
                }
                //else if (user.Subscriptions.Any(s => s.SubscriptionStateCV == CodeValues.SubscriptionState.Subscribed))
                //{
                //    return new PaymentParametersViewModel() { AlreadyMember = true };
                //}
                else
                {
                    sub.User = user; // user was already in database but was not subscribed yet
                }

                var address = new ManBox.Model.Address()
                {
                    City       = shippingInfo.City,
                    FirstName  = shippingInfo.FirstName,
                    LastName   = shippingInfo.LastName,
                    PostalCode = shippingInfo.PostalCode,
                    Street     = shippingInfo.Street,
                    Province   = shippingInfo.Province,
                    CountryId  = shippingInfo.CountryId
                };

                var shippingAddress = new ManBox.Model.Address()
                {
                    City       = shippingInfo.City,
                    FirstName  = string.IsNullOrEmpty(shippingInfo.ShippingFirstName) ? shippingInfo.FirstName : shippingInfo.ShippingFirstName,
                    LastName   = string.IsNullOrEmpty(shippingInfo.ShippingLastName) ? shippingInfo.LastName : shippingInfo.ShippingLastName,
                    PostalCode = shippingInfo.PostalCode,
                    Street     = shippingInfo.Street,
                    Province   = shippingInfo.Province,
                    CountryId  = shippingInfo.CountryId
                };

                sub.Address             = address;
                sub.ShippingAddress     = shippingAddress;
                sub.SubscriptionStateCV = CodeValues.SubscriptionState.Checkout;

                ent.SaveChanges();

                return(GetPaymentInfo(sub, ent));
            }
        }
Example #27
0
        public UserViewModel Register(UserViewModel user, string signinType, string subscrToken)
        {
            using (ManBoxEntities ent = new ManBoxEntities())
            {
                Subscription sub = null;

                if (string.IsNullOrEmpty(user.Password) && signinType != CodeValues.SignInType.Facebook)
                {
                    throw new Exception("Password cannot be empty");
                }

                var existingUser = ent.Users.FirstOrDefault(u => u.Email == user.Email);

                // if it's an existing facebook user, retrieve his subscription or create a new one
                if (existingUser != null)
                {
                    if (signinType == CodeValues.SignInType.Facebook)
                    {
                        sub = existingUser.Subscriptions.FirstOrDefault();

                        if (sub == null)
                        {
                            sub = new Subscription()
                            {
                                Token               = Guid.NewGuid().ToString(),
                                CreatedDatetime     = DateTime.Now,
                                IsActive            = true,
                                IsPaused            = false,
                                SubscriptionStateCV = CodeValues.SubscriptionState.InCart,
                                UserId              = existingUser.UserId
                            };
                            ent.Subscriptions.Add(sub);
                        }

                        return(new UserViewModel()
                        {
                            Email = existingUser.Email,
                            Token = sub.Token,
                            FirstName = existingUser.FirstName,
                            LastName = existingUser.LastName,
                            UserId = existingUser.UserId
                        });
                    }

                    return(null);
                }

                var newUser = new User()
                {
                    Email           = user.Email,
                    Password        = user.Password,
                    CreatedDatetime = DateTime.Now,
                    CountryId       = IdHelper.CurrentUser.CountryId,
                    FirstName       = user.FirstName,
                    LastName        = user.LastName,
                    IsOptin         = true,
                    SignInTypeCV    = signinType,
                    LanguageId      = IdHelper.CurrentUser.LanguageId
                };
                ent.Users.Add(newUser);

                sub = ent.Subscriptions.FirstOrDefault(u => u.Token == subscrToken);

                // assign current anonymous subscription to the new user
                if (sub != null)
                {
                    sub.User = newUser;
                }

                ent.SaveChanges();

                return(new UserViewModel()
                {
                    Email = newUser.Email,
                    Token = subscrToken,
                    FirstName = newUser.FirstName,
                    LastName = newUser.LastName,
                    UserId = newUser.UserId
                });
            }
        }
Example #28
0
        public SubscriptionSelectionViewModel AddGift(int giftPackId)
        {
            string token = IdHelper.CurrentUser.Token;

            using (ManBoxEntities ent = new ManBoxEntities())
            {
                Subscription sub;
                if (token == null || !IdHelper.CurrentUser.IsAuthenticated)
                {
                    sub = InitializeAnonymousSubscription(ent);
                }
                else
                {
                    sub = InitializeGiftOrderForSubscribedCustomer(ent, token);
                }

                var activeDelivery = Utilities.GetActiveDelivery(sub);

                // you cannot have other subscription items
                if (activeDelivery.SubscriptionDeliveryModels.Any(m => m.PackId == null))
                {
                    return(new SubscriptionSelectionViewModel()
                    {
                        CartNotificationMessage = "Vous ne pouvez combiner un paquet cadeau avec un abonnement."
                    });
                }

                // you cannot have more than one gift 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 == giftPackId);

                if (!pack.IsAGift)
                {
                    throw new Exception("Expected a gift pack");
                }

                foreach (var p in pack.ProductPacks)
                {
                    activeDelivery.SubscriptionDeliveryModels.Add(new SubscriptionDeliveryModel()
                    {
                        Model = p.Product.Models.First(), Quantity = p.Quantity, PackId = pack.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));
            }
        }