void BindDdlDays(List <Day> days)
        {
            rdoDays.DataSource     = days;
            rdoDays.DataTextField  = "DayTitle";
            rdoDays.DataValueField = "DayNumber";
            rdoDays.DataBind();

            foreach (ListItem item in rdoDays.Items)
            {
                item.Attributes.Add("class", "mealDay" + item.Value);
            }

            hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(CurrentCartItem.CartItemID, CurrentCalendarId);

            CurrentDaysWithAllergens(cartCal.CartCalendarID).ForEach(delegate(int a)
            {
                ListItem item = rdoDays.Items.FindByValue(a.ToString());
                if (item != null)
                {
                    item.Attributes["class"] += " redFont";
                }
            });

            if (CurrentDay != 0)
            {
                rdoDays.SelectedValue = CurrentDay.ToString();
            }
            else
            {
                rdoDays.SelectedIndex = 0;
                CurrentDay            = int.Parse(rdoDays.SelectedValue);
            }
            //ddlDays_SelectedIndexChanged(this, new EventArgs());
        }
        void ddlDays_SelectedIndexChanged(object sender, EventArgs e)
        {
            CurrentDay = int.Parse(rdoDays.SelectedValue);

            foreach (ListItem item in rdoDays.Items)
            {
                item.Attributes.Add("class", "mealDay" + item.Value);
            }

            BindForm();

            hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(CurrentCartItem.CartItemID, CurrentCalendarId);

            CurrentDaysWithAllergens(cartCal.CartCalendarID).ForEach(delegate(int a)
            {
                ListItem item = rdoDays.Items.FindByValue(a.ToString());
                if (item != null)
                {
                    item.Attributes["class"] += " redFont";
                }
            });
        }
        public string UpdateCarts(List <UpdateCartItem> carts)
        {
            try
            {
                UpdateCartItem     updatecart   = carts[0];
                hccCart            CurrentCart  = hccCart.GetById(updatecart.cartId);
                hccUserProfile     ownerProfile = CurrentCart.OwnerProfile;
                hccAddress         snapBillAddr = null;
                List <hccCartItem> cartItems    = null;
                bool      isAuthNet             = false;
                hccLedger ledger = null;
                string    retVal = string.Empty;

                if (CurrentCart != null && ownerProfile != null)
                {
                    hccAddress billAddr = null;
                    hccUserProfilePaymentProfile activePaymentProfile = ownerProfile.ActivePaymentProfile;

                    if (updatecart.updateStatus && CurrentCart.StatusID != updatecart.statusId)
                    {
                        CurrentCart.StatusID     = updatecart.statusId;
                        CurrentCart.ModifiedBy   = (Guid)Helpers.LoggedUser.ProviderUserKey;
                        CurrentCart.ModifiedDate = DateTime.Now;

                        if (updatecart.statusId == (int)Enums.CartStatus.Paid)
                        {
                            if (!CurrentCart.PurchaseBy.HasValue)
                            {
                                CurrentCart.PurchaseBy = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            }

                            if (!CurrentCart.PurchaseDate.HasValue)
                            {
                                CurrentCart.PurchaseDate = DateTime.Now;
                            }
                        }
                        CurrentCart.Save();
                    }

                    if (updatecart.updateAddresses) // re-snap addresses
                    {
                        if (ownerProfile.BillingAddressID.HasValue)
                        {
                            billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.BillingSnap,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                        }
                        else
                        {
                            retVal += "Profile has no billing address on record.";
                        }

                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            hccAddress shipAddr = null;

                            if (snapBillAddr != null)
                            {
                                ci.SnapBillAddrId = snapBillAddr.AddressID;
                            }

                            if (ci.UserProfile == null)
                            {
                                ci.UserProfileID = ownerProfile.UserProfileID;
                            }

                            if (ci.UserProfile.ShippingAddressID.HasValue)
                            {
                                shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                            }

                            if (shipAddr != null)
                            {
                                hccAddress snapShipAddr = new hccAddress
                                {
                                    Address1              = shipAddr.Address1,
                                    Address2              = shipAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.ShippingSnap,
                                    City                  = shipAddr.City,
                                    Country               = shipAddr.Country,
                                    DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                    FirstName             = shipAddr.FirstName,
                                    IsBusiness            = shipAddr.IsBusiness,
                                    LastName              = shipAddr.LastName,
                                    Phone                 = shipAddr.Phone,
                                    PostalCode            = shipAddr.PostalCode,
                                    State                 = shipAddr.State,
                                    ProfileName           = ci.UserProfile.ProfileName
                                };
                                snapShipAddr.Save();
                                ci.SnapShipAddrId = snapShipAddr.AddressID;
                            }

                            ci.Save();
                        });
                    }

                    if (updatecart.rerunAuthNet)
                    {
                        CurrentCart.StatusID     = (int)Enums.CartStatus.Unfinalized;
                        CurrentCart.PurchaseBy   = null;
                        CurrentCart.PurchaseDate = null;

                        if (ownerProfile != null)
                        {
                            AuthNetConfig ANConfig = new AuthNetConfig();

                            if (ANConfig.Settings.TestMode)
                            {
                                CurrentCart.IsTestOrder = true;
                            }

                            if (CurrentCart.PaymentDue > 0.00m)
                            {
                                try
                                {   // if total balance remains
                                    CustomerInformationManager cim = new CustomerInformationManager();

                                    if (activePaymentProfile != null)
                                    {
                                        AuthorizeNet.Order order = new AuthorizeNet.Order(ownerProfile.AuthNetProfileID,
                                                                                          activePaymentProfile.AuthNetPaymentProfileID, null);

                                        // charge CIM account with PaymentDue balance
                                        order.Amount        = CurrentCart.PaymentDue;
                                        order.InvoiceNumber = CurrentCart.PurchaseNumber.ToString();
                                        order.Description   = "Healthy Chef Creations Purchase #" + CurrentCart.PurchaseNumber.ToString();

                                        AuthorizeNet.IGatewayResponse rsp = cim.AuthorizeAndCapture(order);

                                        try
                                        {
                                            CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" + rsp.Approved.ToString()
                                                                          + "|" + rsp.AuthorizationCode + "|" + rsp.InvoiceNumber + "|" + rsp.Message
                                                                          + "|" + rsp.TransactionID + "|" + rsp.Amount.ToString() + "|" + rsp.CardNumber;
                                        }
                                        catch (Exception) { }

                                        if (rsp.ResponseCode.StartsWith("1"))
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.PurchaseDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                            isAuthNet = true;
                                        }
                                        CurrentCart.Save();
                                    }
                                    else
                                    {
                                        return("No active payment profile.");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (ex is InvalidOperationException)
                                    {
                                        if (CurrentCart.IsTestOrder)
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.AuthNetResponse  = ex.Message;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Unfinalized;
                                            CurrentCart.Save();
                                        }
                                        else
                                        {
                                            BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Message, this, ex);
                                        }
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                            else
                            {      // no balance left to pay on order, set as paid
                                CurrentCart.AuthNetResponse = "Paid with account balance.";
                                CurrentCart.ModifiedBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.ModifiedDate    = DateTime.Now;
                                CurrentCart.PurchaseBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.PurchaseDate    = DateTime.Now;
                                CurrentCart.StatusID        = (int)Enums.CartStatus.Paid;
                                CurrentCart.Save();
                            }
                        }
                    }

                    if (updatecart.createLedgerEntry)
                    {
                        if (ledger == null)
                        {
                            ledger = hccLedger.GetBy(CurrentCart.CartID);
                        }

                        if (ledger == null)
                        {
                            SaveLedger(ledger, CurrentCart, ownerProfile);
                        }
                    }

                    if (updatecart.createNewSnapshot)
                    {
                        if (((Enums.CartStatus)CurrentCart.StatusID) == Enums.CartStatus.Paid)
                        {
                            if (ledger == null)
                            {
                                ledger = hccLedger.GetBy(CurrentCart.CartID);
                            }

                            if (ledger == null) // it still equals null
                            {
                                SaveLedger(ledger, CurrentCart, ownerProfile);
                            }

                            // create snapshot here
                            hccCartSnapshot snap = new hccCartSnapshot
                            {
                                CartId           = CurrentCart.CartID,
                                MembershipId     = ownerProfile.MembershipID,
                                LedgerId         = ledger.LedgerID,
                                AccountBalance   = ownerProfile.AccountBalance,
                                AuthNetProfileId = ownerProfile.AuthNetProfileID,
                                CreatedBy        = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                CreatedDate      = DateTime.Now,
                                DefaultCouponId  = ownerProfile.DefaultCouponId,
                                Email            = ownerProfile.ASPUser.Email,
                                FirstName        = ownerProfile.FirstName,
                                LastName         = ownerProfile.LastName,
                                ProfileName      = ownerProfile.ProfileName
                            };

                            if (isAuthNet)
                            {
                                if (activePaymentProfile != null)
                                {
                                    snap.AuthNetPaymentProfileId = activePaymentProfile.AuthNetPaymentProfileID;
                                    snap.CardTypeId = activePaymentProfile.CardTypeID;
                                    snap.CCLast4    = activePaymentProfile.CCLast4;
                                    snap.ExpMon     = activePaymentProfile.ExpMon;
                                    snap.ExpYear    = activePaymentProfile.ExpYear;
                                    snap.NameOnCard = activePaymentProfile.NameOnCard;
                                }
                                else
                                {
                                    return("No active payment profile.");
                                }
                            }
                            else
                            {
                                snap.AuthNetPaymentProfileId = string.Empty;
                                snap.CardTypeId = 0;
                                snap.CCLast4    = string.Empty;
                                snap.ExpMon     = 0;
                                snap.ExpYear    = 0;
                                snap.NameOnCard = string.Empty;
                            }
                            snap.Save();

                            if (billAddr == null && ownerProfile.BillingAddressID.HasValue)
                            {
                                billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);
                            }

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = billAddr.AddressTypeID,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                            else
                            {
                                retVal += "Profile has no billing address on record.";
                            }

                            // copy and replace of all addresses for snapshot
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            cartItems.ToList().ForEach(delegate(hccCartItem ci)
                            {
                                if (snapBillAddr != null)
                                {
                                    ci.SnapBillAddrId = snapBillAddr.AddressID;
                                }

                                hccAddress shipAddr = null;
                                if (ci.UserProfile.ShippingAddressID.HasValue)
                                {
                                    shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                                }

                                if (shipAddr != null)
                                {
                                    hccAddress snapShipAddr = new hccAddress
                                    {
                                        Address1              = shipAddr.Address1,
                                        Address2              = shipAddr.Address2,
                                        AddressTypeID         = shipAddr.AddressTypeID,
                                        City                  = shipAddr.City,
                                        Country               = shipAddr.Country,
                                        DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                        FirstName             = shipAddr.FirstName,
                                        IsBusiness            = shipAddr.IsBusiness,
                                        LastName              = shipAddr.LastName,
                                        Phone                 = shipAddr.Phone,
                                        PostalCode            = shipAddr.PostalCode,
                                        State                 = shipAddr.State,
                                        ProfileName           = ci.UserProfile.ProfileName
                                    };
                                    snapShipAddr.Save();
                                    ci.SnapShipAddrId = snapShipAddr.AddressID;
                                }
                                else
                                {
                                    retVal += "Profile has no billing address on record.";
                                }

                                ci.Save();
                            });
                        }
                    }

                    if (updatecart.sendCustomerEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationMerchant(ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml(), CurrentCart.CartID);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send Merchant Mail Failed", this, ex); }
                    }

                    if (updatecart.sendMerchantEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationCustomer(ownerProfile.ASPUser.Email, ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml());
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send customer Mail Failed", this, ex); }
                    }

                    if (updatecart.repairCartCals)
                    {
                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }
                        // wrap in programs

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            if (ci.ItemType == Enums.CartItemType.DefinedPlan)
                            {
                                hccProgramPlan cp = hccProgramPlan.GetById(ci.Plan_PlanID.Value);

                                if (cp != null)
                                {
                                    for (int i = 0; i < cp.NumWeeks; i++)
                                    {
                                        hccProductionCalendar cal;
                                        cal = hccProductionCalendar.GetBy(ci.DeliveryDate.AddDays(7 * i));

                                        if (cal != null)
                                        {
                                            hccCartItemCalendar existCal = hccCartItemCalendar.GetBy(ci.CartItemID, cal.CalendarID);
                                            if (existCal == null)
                                            {
                                                hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                                    CalendarID = cal.CalendarID, CartItemID = ci.CartItemID, IsFulfilled = false
                                                };
                                                cartCal.Save();
                                            }
                                        }
                                        else
                                        {
                                            BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                                "No production calendar found for Delivery Date: " + ci.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                                        }
                                    }
                                }
                            }
                        });
                    }

                    if (updatecart.reCalcItemTax)
                    {
                        try
                        {
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            List <ProfileCart> CurrentProfileCarts = new List <ProfileCart>();

                            if (cartItems.Count > 0)
                            {
                                hccUserProfile parentProfile = hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                                //List<hccProductionCalendar> pc = new List<hccProductionCalendar>();

                                foreach (hccCartItem cartItem in cartItems)
                                {
                                    ProfileCart profCart;
                                    int         shippingAddressId;

                                    //if (!pc.Exists(a => a.DeliveryDate == cartItem.DeliveryDate))
                                    //    pc.Add(hccProductionCalendar.GetBy(cartItem.DeliveryDate));

                                    //hccProductionCalendar cpc = pc.SingleOrDefault(a => a.DeliveryDate == cartItem.DeliveryDate);

                                    //if (cpc != null && (cpc.OrderCutOffDate.AddDays(1) >= DateTime.Now || (HttpContext.Current.Request.Url.OriginalString.Contains("Admin"))))
                                    //{
                                    if (cartItem.UserProfile != null && (cartItem.UserProfile.UseParentShipping || cartItem.UserProfile.ShippingAddressID.HasValue))
                                    {
                                        if (cartItem.UserProfile.UseParentShipping)
                                        {
                                            shippingAddressId = parentProfile.ShippingAddressID.Value;
                                        }
                                        else
                                        {
                                            shippingAddressId = cartItem.UserProfile.ShippingAddressID.Value;
                                        }

                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == shippingAddressId && a.DeliveryDate == cartItem.DeliveryDate);
                                    }
                                    else
                                    {
                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == 0 &&
                                                                    a.DeliveryDate == cartItem.DeliveryDate);

                                        shippingAddressId = 0;
                                    }

                                    if (profCart == null)
                                    {
                                        profCart = new ProfileCart(shippingAddressId, cartItem.DeliveryDate);
                                        CurrentProfileCarts.Add(profCart);
                                    }

                                    profCart.CartItems.Add(cartItem);
                                    //}
                                    //else
                                    //{
                                    //    //cartItem.Delete();
                                    //    //lblFeedbackCart.Text = "Item(s) removed from cart due to expiration of availability.";

                                    //}
                                }
                            }

                            //// display totals
                            CurrentCart.CalculateTotals(CurrentProfileCarts);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Attempt to recalculate taz for cart items failed.", this, ex); }
                    }
                }
                return("Cart Updated: " + DateTime.Now);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        List <Day> BindWeeklyGlance(List <hccProgramDefaultMenu> defaultMenuSelections, int numDaysPerWeek)
        {
            int i;

            for (i = 1; i <= numDaysPerWeek; i++)
            {
                StringBuilder sb         = new StringBuilder();
                int           lastTypeId = 0;

                defaultMenuSelections.Where(a => a.DayNumber == i)
                .OrderBy(a => a.MealTypeID).ToList().ForEach(delegate(hccProgramDefaultMenu defaultSelection)
                {
                    int menuItemId     = defaultSelection.MenuItemID;
                    int menuItemSizeId = defaultSelection.MenuItemSizeID;

                    //hccProductionCalendar prodCal = hccProductionCalendar.GetBy(CurrentCartItem.DeliveryDate);
                    hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(this.PrimaryKeyIndex, CurrentCalendarId);

                    hccCartDefaultMenuException menuItemExc
                        = hccCartDefaultMenuException.GetBy(defaultSelection.DefaultMenuID, cartCal.CartCalendarID);
                    string prefString = string.Empty;

                    if (menuItemExc != null)
                    {
                        menuItemId     = menuItemExc.MenuItemID;
                        menuItemSizeId = menuItemExc.MenuItemSizeID;

                        prefString = hccCartDefaultMenuExPref.GetPrefsBy(menuItemExc.DefaultMenuExceptID)
                                     .Select(a => a.Name).DefaultIfEmpty("None").Aggregate((a, b) => a + ", " + b);
                    }

                    if (menuItemId > 0)
                    {
                        hccMenuItem menuItem = hccMenuItem.GetById(menuItemId);

                        if (defaultSelection.MealTypeID != lastTypeId)
                        {
                            lastTypeId = defaultSelection.MealTypeID;
                            sb.Append("<span class='label'>" + ((Enums.MealTypes)lastTypeId).ToString() + "</span><br />");
                        }

                        if (menuItem != null)
                        {
                            sb.Append(menuItem.Name);
                        }

                        if (((Enums.CartItemSize)menuItemSizeId) != Enums.CartItemSize.NoSize)
                        {
                            sb.Append(" - " + Enums.GetEnumDescription(((Enums.CartItemSize)menuItemSizeId)));
                        }

                        // prefs
                        if (!string.IsNullOrWhiteSpace(prefString))
                        {
                            sb.Append(" - " + prefString);
                        }

                        try
                        {
                            var t = defaultMenuSelections[defaultMenuSelections.IndexOf(defaultSelection) + 1];
                            if (t.MealTypeID == lastTypeId)
                            {
                                sb.Append(", ");
                            }
                            else
                            {
                                sb.Append("<p></p>");
                            }
                        }
                        catch { }
                    }
                    else
                    {
                        sb.Append("<p></p>");
                    }
                });

                days.Add(new Day {
                    DayTitle = "Day: " + i.ToString(), DayNumber = i, DayInfo = sb.ToString().Trim().TrimEnd(',')
                });
            }

            lvwWeekGlance.DataSource = days;
            lvwWeekGlance.DataBind();

            return(days);
        }
        void BindForm()
        {
            if (defaultMenuSelections.Count == 0)
            {
                defaultMenuSelections = hccProgramDefaultMenu.GetBy(CurrentCalendarId, CurrentProgramId);
            }

            List <DropDownList>       ddls         = new List <DropDownList>();
            List <HtmlGenericControl> divDdls      = new List <HtmlGenericControl>();
            DailyNutrition            totalNutInfo = new DailyNutrition {
                DayNumber = CurrentDay
            };
            List <HtmlGenericControl> divItemContainers;
            string             ddlBorderClass = string.Empty;
            List <hccAllergen> userAllergens;

            userAllergens = hccUserProfileAllergen.GetAllergensBy(CurrentCartItem.UserProfile.UserProfileID, true);

            BindDropDownLists(userAllergens);

            divItemContainers =
                pnlDefaultMenu.Controls.OfType <HtmlGenericControl>().Where(a => a.Attributes["class"] == "divItemContainer").ToList();

            divItemContainers.ForEach(delegate(HtmlGenericControl ctrl)
                                      { divDdls.AddRange(ctrl.Controls.OfType <HtmlGenericControl>().Where(a => a.Attributes["class"] == "divDdl")); });

            divDdls.ForEach(a => ddls.AddRange(a.Controls.OfType <DropDownList>()));

            int dailyDefaultsCount = defaultMenuSelections.Where(a => a.DayNumber == CurrentDay).Count();

            if (dailyDefaultsCount == 0 || dailyDefaultsCount != ddls.Count)
            {
                lblFeedback.Text      += "Not all default values have been created for the selected date and program combination. Select the default items on the Production Management -> Program Default Menus page, and press 'Save' to create the default items.";
                pnlDefaultMenu.Visible = false;
            }
            else
            {
                hccCartItemCalendar cartCalendar = hccCartItemCalendar.GetBy(this.PrimaryKeyIndex, CurrentCalendarId);

                defaultMenuSelections.ForEach(delegate(hccProgramDefaultMenu defaultSelection)
                {
                    try
                    {
                        DropDownList ddl = ddls.Where(a => a.Attributes["day"] == defaultSelection.DayNumber.ToString() &&
                                                      a.Attributes["type"] == defaultSelection.MealTypeID.ToString() &&
                                                      a.Attributes["ord"] == defaultSelection.Ordinal.ToString())
                                           .SingleOrDefault();

                        if (ddl != null)
                        {
                            int menuItemId          = defaultSelection.MenuItemID;
                            string value            = menuItemId.ToString() + "-" + defaultSelection.MenuItemSizeID.ToString();
                            int DefaultMenuExceptID = 0;
                            int cartcalendarid      = 0;
                            // bold face the default selection
                            int defaultIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(value));
                            ddl.Items[(defaultIndex <= -1 ? 0 : defaultIndex)].Attributes["class"] += "bold italic";

                            hccCartDefaultMenuException menuItemExc
                                = hccCartDefaultMenuException.GetBy(defaultSelection.DefaultMenuID, cartCalendar.CartCalendarID);

                            if (menuItemExc != null)
                            {
                                menuItemId          = menuItemExc.MenuItemID;
                                value               = menuItemId.ToString() + "-" + menuItemExc.MenuItemSizeID.ToString();
                                DefaultMenuExceptID = menuItemExc.DefaultMenuExceptID;
                                cartcalendarid      = menuItemExc.CartCalendarID;
                            }

                            ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(value));
                            ddl.Attributes.Add("defMenuId", defaultSelection.DefaultMenuID.ToString());
                            ddl.Attributes.Add("defMenuExceptionId", DefaultMenuExceptID.ToString());
                            ddl.Attributes.Add("defMenuCartCalendarId", cartcalendarid.ToString());
                            ddl.SelectedItem.Attributes["class"] += " bold";

                            HtmlGenericControl divItemContainer = (HtmlGenericControl)ddl.Parent.Parent;
                            HtmlGenericControl divNuts          =
                                divItemContainer.Controls.OfType <HtmlGenericControl>().Where(a => a.Attributes["class"] == "divNuts").SingleOrDefault();
                            HtmlGenericControl divAllrgs =
                                divItemContainer.Controls.OfType <HtmlGenericControl>().Where(a => a.Attributes["class"] == "divAllrgs").SingleOrDefault();
                            HtmlGenericControl divPrefs =
                                divItemContainer.Controls.OfType <HtmlGenericControl>().Where(a => a.Attributes["class"] == "divPrefs").SingleOrDefault();

                            if (menuItemId > 0)
                            {
                                hccMenuItem menuItem = null;

                                if (menuItemExc == null)
                                {
                                    if (defaultSelection.MenuItemID > 0)
                                    {
                                        menuItem = hccMenuItem.GetById(defaultSelection.MenuItemID);
                                    }
                                }
                                else if (menuItemExc.MenuItemID > 0)
                                {
                                    menuItem = hccMenuItem.GetById(menuItemExc.MenuItemID);
                                }

                                if (menuItem != null)
                                {
                                    // nutrition info
                                    if (divNuts != null)
                                    {
                                        string nutInfo = string.Empty;
                                        hccMenuItemNutritionData menuNut = hccMenuItemNutritionData.GetBy(menuItem.MenuItemID);

                                        if (menuNut != null)
                                        {
                                            nutInfo = string.Format("Calories: {0}, Fat: {1}, Protein: {2},  Carbohydrates: {3}, Fiber: {4},Sodium: {5}",
                                                                    menuNut.Calories.ToString("f2"), menuNut.TotalFat.ToString("f2"), menuNut.Protein.ToString("f2"),
                                                                    menuNut.TotalCarbohydrates.ToString("f2"), menuNut.DietaryFiber.ToString("f2"), menuNut.Sodium.ToString("f2"));
                                            divNuts.InnerHtml      = nutInfo;
                                            totalNutInfo.Calories += menuNut.Calories;
                                            totalNutInfo.Carbs    += menuNut.TotalCarbohydrates;
                                            totalNutInfo.Fat      += menuNut.TotalFat;
                                            totalNutInfo.Fiber    += menuNut.DietaryFiber;
                                            totalNutInfo.Protein  += menuNut.Protein;
                                            totalNutInfo.Sodium   += menuNut.Sodium;
                                        }
                                        else
                                        {
                                            nutInfo = string.Format("Calories: {0}, Fat: {1}, Protein: {2},  Carbohydrates: {3}, Fiber: {4},Sodium: {5}", 0, 0, 0, 0, 0, 0);
                                        }

                                        divNuts.InnerText = nutInfo;
                                    }

                                    // allergen displays
                                    List <hccAllergen> selectItemAllergens = new List <hccAllergen>();
                                    string allrgsList   = string.Empty;
                                    allrgsList          = "Allergens: " + menuItem.AllergensList;
                                    selectItemAllergens = menuItem.GetAllergens();

                                    if (divAllrgs != null)
                                    {
                                        divAllrgs.InnerText = allrgsList;
                                    }

                                    List <hccAllergen> matchedAllergens = selectItemAllergens.Intersect(userAllergens).ToList();

                                    if (matchedAllergens.Count > 0)
                                    {
                                        ddl.SelectedItem.Attributes["class"] += " bold";
                                        ddlBorderClass = "redBorder";
                                    }
                                    else
                                    {
                                        if (menuItemExc == null)
                                        {
                                            ddlBorderClass = "greenBorder";
                                        }
                                        else
                                        {
                                            ddlBorderClass = "blueBorder";
                                        }
                                    }

                                    // preferences
                                    List <hccPreference> itemPrefs = menuItem.GetPreferences();

                                    if (itemPrefs.Count > 0 && divPrefs != null)
                                    {
                                        itemPrefs.ForEach(delegate(hccPreference pref)
                                        {
                                            HtmlInputCheckBox chkPref = new HtmlInputCheckBox();
                                            chkPref.Value             = pref.PreferenceID.ToString();
                                            Label lblPref             = new Label();
                                            lblPref.Text = pref.Name;

                                            divPrefs.Controls.Add(chkPref);
                                            divPrefs.Controls.Add(lblPref);

                                            hccCartMenuExPref cartMenuExPref = hccCartMenuExPref.GetById(cartCalendar.CartItemID, defaultSelection.DayNumber);

                                            if (cartMenuExPref != null)
                                            {
                                                if (cartMenuExPref.IsModified)
                                                {
                                                    if (menuItemExc != null)
                                                    {
                                                        hccCartDefaultMenuExPref excPref = hccCartDefaultMenuExPref.GetBy(menuItemExc.DefaultMenuExceptID, pref.PreferenceID);
                                                        if (excPref != null)
                                                        {
                                                            chkPref.Checked = true;
                                                        }
                                                    }
                                                }
                                                //hccCartItem cartItem = hccCartItem.GetById(cartCalendar.CartItemID);
                                                //if (cartItem != null)
                                                //{
                                                //    if (Convert.ToBoolean(cartItem.IsModified))
                                                //    {
                                                //        hccCartDefaultMenuExPref excPref = hccCartDefaultMenuExPref.GetBy(menuItemExc.DefaultMenuExceptID, pref.PreferenceID);
                                                //        if (excPref != null)
                                                //        {
                                                //            chkPref.Checked = true;
                                                //        }
                                                //    }
                                                //    else
                                                //    {
                                                //        hccCartDefaultMenuExPref excPref = hccCartDefaultMenuExPref.GetBy(menuItemExc.DefaultMenuExceptID, pref.PreferenceID);
                                                //        if (excPref != null)
                                                //            chkPref.Checked = true;
                                                //        hccProgramDefaultMenuExPref programmenuexpref = hccProgramDefaultMenuExPref.GetBy(defaultSelection.DefaultMenuID, pref.PreferenceID);
                                                //        if (programmenuexpref != null)
                                                //            chkPref.Checked = true;
                                                //    }
                                                //}
                                            }
                                            else
                                            {
                                                //hccCartItem cartItem = hccCartItem.GetById(cartCalendar.CartItemID);
                                                //if (cartItem != null)
                                                //{
                                                //    if (!Convert.ToBoolean(cartItem.IsModified))
                                                //    {
                                                //        hccProgramDefaultMenuExPref programmenuexpref = hccProgramDefaultMenuExPref.GetBy(defaultSelection.DefaultMenuID, pref.PreferenceID);
                                                //        if (programmenuexpref != null)
                                                //            chkPref.Checked = true;
                                                //    }
                                                //}
                                                hccProgramDefaultMenuExPref programmenuexpref = hccProgramDefaultMenuExPref.GetBy(defaultSelection.DefaultMenuID, pref.PreferenceID);
                                                if (programmenuexpref != null)
                                                {
                                                    chkPref.Checked = true;
                                                }
                                            }
                                        });
                                    }
                                }
                                else
                                {
                                    divNuts.InnerText   = string.Empty;
                                    divPrefs.InnerText  = string.Empty;
                                    divAllrgs.InnerText = string.Empty;
                                }
                                ddl.CssClass = "mealItemDdl " + ddlBorderClass;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                });

                if (totalNutInfo == null)
                {
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Cals##", "0");
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Fats##", "0");
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Ptrns##", "0");
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Carbs##", "0");
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Fbrs##", "0");
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Sod##", "0");
                }
                else
                {
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Cals##", totalNutInfo.Calories.ToString("f2"));
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Fats##", totalNutInfo.Fat.ToString("f2"));
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Ptrns##", totalNutInfo.Protein.ToString("f2"));
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Carbs##", totalNutInfo.Carbs.ToString("f2"));
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Fbrs##", totalNutInfo.Fiber.ToString("f2"));
                    divTotalNutrition.InnerHtml = divTotalNutrition.InnerHtml.Replace("##Sod##", totalNutInfo.Sodium.ToString("f2"));
                }

                divTotalNutrition.Visible = true;
            }
        }
        protected override void LoadForm()
        {
            try
            {
                hccProductionCalendar cal = null;

                if (Request.QueryString["dd"] != null && !string.IsNullOrEmpty(Request.QueryString["dd"]))
                {
                    DateTime _delDate = DateTime.ParseExact(Request.QueryString["dd"].ToString(), "M/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
                    cal = hccProductionCalendar.GetBy(_delDate);
                    //cal = hccProductionCalendar.GetBy(DateTime.Parse(Request.QueryString["dd"].ToString()));

                    if (cal != null)
                    {
                        CurrentCalendarId = cal.CalendarID;
                    }

                    lkbBack.PostBackUrl += "?cal=" + cal.CalendarID.ToString();
                }

                hccProgramPlan plan    = hccProgramPlan.GetById(CurrentCartItem.Plan_PlanID.Value);
                hccProgram     program = hccProgram.GetById(plan.ProgramID);
                if (plan != null && program != null)
                {
                    CurrentProgramId = program.ProgramID;
                    CurrentNumOfDays = plan.NumDaysPerWeek;

                    // load user profile data
                    hccUserProfile profile = CurrentCartItem.UserProfile;
                    hccUserProfile parent  = hccUserProfile.GetParentProfileBy(profile.MembershipID);

                    lblCustomerName.Text = parent.FirstName + " " + parent.LastName;
                    lblProfileName.Text  = profile.ProfileName;
                    lblProgram.Text      = program.Name;
                    lblPlan.Text         = plan.Name;
                    lblPlanOption.Text   = hccProgramOption.GetById(CurrentCartItem.Plan_ProgramOptionID.Value).OptionText;
                    lblOrderNumber.Text  = CurrentCartItem.OrderNumber;
                    lblQuantity.Text     = CurrentCartItem.Quantity.ToString();
                    lblDeliveryDate.Text = cal.DeliveryDate.ToShortDateString();

                    hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(CurrentCartItem.CartItemID, cal.CalendarID);

                    if (cartCal != null)
                    {
                        chkIsComplete.Checked = cartCal.IsFulfilled;
                    }

                    chkIsCancelledDisplay.Checked = CurrentCartItem.IsCancelled;

                    lvwAllrgs.DataSource = profile.GetAllergens();
                    lvwAllrgs.DataBind();
                    ProfileNotesEdit_AllergenNote.CurrentUserProfileId = profile.UserProfileID;
                    ProfileNotesEdit_AllergenNote.Bind();

                    lvwPrefs.DataSource = profile.GetPreferences();
                    lvwPrefs.DataBind();
                    ProfileNotesEdit_PreferenceNote.CurrentUserProfileId = profile.UserProfileID;
                    ProfileNotesEdit_PreferenceNote.Bind();

                    defaultMenuSelections = hccProgramDefaultMenu.GetBy(CurrentCalendarId, CurrentProgramId);

                    days = BindWeeklyGlance(defaultMenuSelections, CurrentNumOfDays);

                    BindDdlDays(days);

                    BindForm();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        //public string GetProgramImage(string programName)
        //{
        //    var fileName = "/userfiles/images/programs/" + programName.Replace(" ", "-") + ".jpg";

        //    if (!File.Exists(Server.MapPath(fileName)))
        //        return "";

        //    return "<img width='150' height='126' alt='' src='/userfiles/images/programs/" + programName.Replace(" ", "-") + ".jpg' class='left' />";
        //}

        protected void btn_add_to_cart_Click(object sender, EventArgs e)
        {
            try
            {
                Page.Validate("AddToCartGroup");

                if (Page.IsValid)
                {
                    hccCart userCart = hccCart.GetCurrentCart();

                    //Define form variables
                    int itemId   = Convert.ToInt32(Request.Form["plan_type"]);
                    int optionId = ((Request.Form["plan_option"] == null) ? 0 : Convert.ToInt32(Request.Form["plan_option"]));

                    //Select chosen Program Plan
                    hccProgramPlan plan = hccProgramPlan.GetById(itemId);
                    if (plan == null)
                    {
                        throw new Exception("ProgramPlan not found: " + itemId.ToString());
                    }

                    hccProgram       prog   = hccProgram.GetById(plan.ProgramID);
                    hccProgramOption option = hccProgramOption.GetBy(plan.ProgramID).Where(a => a.ProgramOptionID == optionId).SingleOrDefault();

                    int      numDays      = plan.NumDaysPerWeek * plan.NumWeeks;
                    int      numMeals     = numDays * plan.MealsPerDay;
                    decimal  dailyPrice   = plan.PricePerDay + option.OptionValue;
                    decimal  itemPrice    = numDays * dailyPrice;
                    DateTime deliveryDate = DateTime.Parse(ddl_delivery_date.SelectedValue);

                    MembershipUser user = Helpers.LoggedUser;

                    hccCartItem newItem = new hccCartItem
                    {
                        CartID        = userCart.CartID,
                        CreatedBy     = (user == null ? Guid.Empty : (Guid)user.ProviderUserKey),
                        CreatedDate   = DateTime.Now,
                        IsTaxable     = plan.IsTaxEligible,
                        ItemDesc      = plan.Description,
                        NumberOfMeals = numMeals,
                        //ItemName = string.Format("{0} - {1} - {2} - {3} & {4}", (prog == null ? string.Empty : prog.Name), plan.Name, option.OptionText, deliveryDate.ToShortDateString(), numMeals),
                        ItemName             = string.Format("{0} - {1} - {2} - {3}", (prog == null ? string.Empty : prog.Name), plan.Name, option.OptionText, deliveryDate.ToShortDateString()),
                        ItemPrice            = itemPrice,
                        ItemTypeID           = (int)Enums.CartItemType.DefinedPlan,
                        Plan_IsAutoRenew     = false, //chx_renew.Checked,
                        Plan_PlanID          = itemId,
                        Plan_ProgramOptionID = optionId,
                        DeliveryDate         = deliveryDate,
                        Quantity             = int.Parse(txt_quantity.Text),
                        UserProfileID        = ((ddlProfiles.Items.Count == 0) ? 0 : Convert.ToInt32(ddlProfiles.SelectedValue)),
                        IsCompleted          = false
                    };
                    Meals obj = new Meals();
                    obj.CartID    = newItem.CartID;
                    obj.MealCount = newItem.NumberOfMeals;
                    obj.NoOfWeeks = plan.NumWeeks;

                    var ID    = obj.CartID;
                    var Meal  = obj.MealCount;
                    var Weeks = obj.NoOfWeeks;

                    HealthyChef.Templates.HealthyChef.Controls.TopHeader header =
                        (HealthyChef.Templates.HealthyChef.Controls.TopHeader) this.Page.Master.FindControl("TopHeader1");
                    if (header != null)
                    {
                        header.MealsCountVal(ID, Meal);
                    }

                    newItem.GetOrderNumber(userCart);
                    int profileId = 0;
                    if (divProfiles.Visible)
                    {
                        profileId = int.Parse(ddlProfiles.SelectedValue);
                    }
                    else
                    {
                        if (CartUserASPNetId != Guid.Empty)
                        {
                            profileId = hccUserProfile.GetParentProfileBy(CartUserASPNetId).UserProfileID;
                        }
                    }

                    if (profileId > 0)
                    {
                        newItem.UserProfileID = profileId;
                    }

                    hccCartItem existItem = hccCartItem.GetBy(userCart.CartID, newItem.ItemName, profileId);

                    if (existItem == null)
                    {
                        newItem.Save();

                        hccProductionCalendar cal;

                        for (int i = 0; i < plan.NumWeeks; i++)
                        {
                            cal = hccProductionCalendar.GetBy(newItem.DeliveryDate.AddDays(7 * i));

                            if (cal != null)
                            {
                                hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                    CalendarID = cal.CalendarID, CartItemID = newItem.CartItemID
                                };
                                cartCal.Save();
                            }
                            else
                            {
                                BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                    "No production calendar found for Delivery Date: " + newItem.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                            }
                        }
                    }
                    else
                    {
                        existItem.AdjustQuantity(existItem.Quantity + newItem.Quantity);
                    }

                    //Recurring Order Record
                    if (cbxRecurring.Checked)
                    {
                        List <hccRecurringOrder> lstRo = null;
                        if (Session["autorenew"] != null)
                        {
                            lstRo = ((List <hccRecurringOrder>)Session["autorenew"]);
                        }
                        else
                        {
                            lstRo = new List <hccRecurringOrder>();
                        }

                        //var filter = cartItemsRecurring.Where(ci => ci.ItemType == Enums.CartItemType.DefinedPlan);

                        //for(var i = 0; i < int.Parse(txt_quantity.Text); i++)
                        //{
                        lstRo.Add(new hccRecurringOrder
                        {
                            CartID         = userCart.CartID,
                            CartItemID     = newItem.CartItemID,
                            UserProfileID  = newItem.UserProfileID,
                            AspNetUserID   = userCart.AspNetUserID,
                            PurchaseNumber = userCart.PurchaseNumber,
                            TotalAmount    = newItem.ItemPrice
                        });
                        Session["autorenew"] = lstRo;
                        //}
                    }

                    HealthyChef.Templates.HealthyChef.Controls.TopHeader header1 =
                        (HealthyChef.Templates.HealthyChef.Controls.TopHeader) this.Page.Master.FindControl("TopHeader1");

                    if (header1 != null)
                    {
                        header.SetCartCount();
                    }

                    //Redirect user to Program Selection screen
                    Response.Redirect("~/meal-programs.aspx");
                    //multi_programs.ActiveViewIndex = 0;
                    //litMessage.Text = "Your Meal Program has been added to your cart.";
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #8
0
        void lvwOrders_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                try
                {
                    AggrCartItem aggrItem = (AggrCartItem)e.Item.DataItem;

                    if (aggrItem != null)
                    {
                        string qs = "?ci=" + aggrItem.CartItem.CartItemID + "&dd=" + aggrItem.DeliveryDate.ToShortDateString();

                        if (aggrItem.CartItem.ItemType == Enums.CartItemType.AlaCarte)
                        {
                            if (aggrItem.ALC_Count > 1)
                            {
                                ((Label)e.Item.FindControl("lblSimpleName")).Text += " (" + aggrItem.ALC_Count + ")";
                            }

                            qs += "&it=" + ((int)Enums.CartItemType.AlaCarte).ToString();
                        }
                        else if (aggrItem.CartItem.ItemType == Enums.CartItemType.DefinedPlan)
                        {
                            PlaceHolder plcAllergies = (PlaceHolder)e.Item.FindControl("plcAllergies");
                            if (plcAllergies != null)
                            {
                                Label lblAllg = new Label();

                                if (aggrItem.CartItem.ItemType == Enums.CartItemType.DefinedPlan)
                                {
                                    hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(aggrItem.CartItem.CartItemID, aggrItem.DeliveryDate);
                                    if (aggrItem.CartItem.GetDaysWithAllergens(cartCal.CartCalendarID).Count > 0)
                                    {
                                        lblAllg.Text = "Alert";
                                    }
                                    else
                                    {
                                        lblAllg.Text = "Ok";
                                    }
                                }
                                plcAllergies.Controls.Add(lblAllg);
                            }

                            LinkButton lkbPostpone = (LinkButton)e.Item.FindControl("lkbPostpone");
                            if (lkbPostpone != null)
                            {
                                lkbPostpone.Attributes.Add("onclick", "if (confirm('Are you sure that you want to postpone this delivery? This cannot be undone.')) {return confirm('Are you really sure that you want to postpone this delivery? Seriously, postponements cannot be undone.');} else {return false;}");
                                if (aggrItem.CartItem.ItemType == Enums.CartItemType.DefinedPlan)
                                {
                                    lkbPostpone.Visible = true;
                                }
                            }

                            qs += "&it=" + ((int)Enums.CartItemType.DefinedPlan).ToString();
                        }
                        else if (aggrItem.CartItem.ItemType == Enums.CartItemType.GiftCard)
                        {
                            qs += "&it=" + ((int)Enums.CartItemType.GiftCard).ToString();
                        }

                        PlaceHolder plcDetails = (PlaceHolder)e.Item.FindControl("plcDetails");
                        if (plcDetails != null)
                        {
                            Label lblDetails = new Label();
                            lblDetails.Text = "<a href='OrderFulfillmentEditor.aspx" + qs + "'>Details</a>";
                            plcDetails.Controls.Add(lblDetails);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        protected override void SaveForm()
        {
            try
            {
                hccCart        userCart = hccCart.GetById(this.PrimaryKeyIndex);
                MembershipUser user     = Membership.GetUser(userCart.AspNetUserID);

                if (user != null)
                {
                    hccProgramPlan selPlan = hccProgramPlan.GetById(int.Parse(ddlPlans.SelectedValue));

                    if (selPlan != null)
                    {
                        List <hccProgramOption> progOptions = hccProgramOption.GetBy(selPlan.ProgramID);
                        hccProgramOption        option      = progOptions.Where(a => a.ProgramOptionID == (int.Parse(ddlOptions.SelectedValue))).SingleOrDefault();
                        hccProgram prog = hccProgram.GetById(selPlan.ProgramID);

                        int     numDays    = selPlan.NumDaysPerWeek * selPlan.NumWeeks;
                        decimal dailyPrice = selPlan.PricePerDay + option.OptionValue;
                        decimal itemPrice  = numDays * dailyPrice;
                        int     profileId  = 0;
                        //bool autoRenew = chkAutoRenew.Checked;
                        string   itemFullName = string.Empty;
                        DateTime startDate    = DateTime.Parse(ddlStartDates.SelectedItem.Text);

                        itemFullName = string.Format("{0} - {1} - {2} - {3}",
                                                     prog == null ? string.Empty : prog.Name, selPlan.Name, option.OptionText, startDate.ToShortDateString());

                        if (divProfiles.Visible)
                        {
                            profileId = int.Parse(ddlProfiles.SelectedValue);
                        }
                        else
                        {
                            profileId = hccUserProfile.GetParentProfileBy(userCart.AspNetUserID.Value).UserProfileID;
                        }

                        if (userCart != null && selPlan != null)
                        {
                            int         currentQty = int.Parse(txtQuantity.Text.Trim());
                            hccCartItem existItem  = hccCartItem.GetBy(userCart.CartID, itemFullName, profileId);

                            if (existItem == null)
                            {
                                hccCartItem planItem = new hccCartItem
                                {
                                    CartID               = userCart.CartID,
                                    CreatedBy            = (Guid)Membership.GetUser().ProviderUserKey,
                                    CreatedDate          = DateTime.Now,
                                    IsTaxable            = selPlan.IsTaxEligible,
                                    ItemDesc             = selPlan.Description,
                                    ItemName             = itemFullName,
                                    ItemPrice            = itemPrice,
                                    ItemTypeID           = (int)Enums.CartItemType.DefinedPlan,
                                    Plan_IsAutoRenew     = false, //autoRenew,
                                    Plan_PlanID          = selPlan.PlanID,
                                    Plan_ProgramOptionID = option.ProgramOptionID,
                                    DeliveryDate         = startDate,
                                    UserProfileID        = profileId,
                                    Quantity             = currentQty,
                                    IsCompleted          = false
                                };

                                planItem.GetOrderNumber(userCart);
                                planItem.Save();

                                hccProductionCalendar cal;

                                for (int i = 0; i < selPlan.NumWeeks; i++)
                                {
                                    cal = hccProductionCalendar.GetBy(planItem.DeliveryDate.AddDays(7 * i));

                                    if (cal != null)
                                    {
                                        hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                            CalendarID = cal.CalendarID, CartItemID = planItem.CartItemID, IsFulfilled = false
                                        };
                                        cartCal.Save();
                                    }
                                    else
                                    {
                                        BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                            "No production calendar found for Delivery Date: " + planItem.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                                    }
                                }


                                if (cbxRecurring.Checked)
                                {
                                    var cartItemsRecurring = hccCartItem.GetBy(userCart.CartID);
                                    var filter             = cartItemsRecurring.Where(ci => ci.ItemType == Enums.CartItemType.DefinedPlan);
                                    var roItem             = new hccRecurringOrder();
                                    roItem.CartID         = planItem.CartID;
                                    roItem.CartItemID     = planItem.CartItemID;
                                    roItem.UserProfileID  = planItem.UserProfileID;
                                    roItem.AspNetUserID   = userCart.AspNetUserID;
                                    roItem.PurchaseNumber = userCart.PurchaseNumber;
                                    roItem.TotalAmount    = Math.Round(Convert.ToDecimal(Convert.ToDouble(planItem.ItemPrice) - Convert.ToDouble(planItem.ItemPrice) * 0.05), 2);
                                    roItem.Save();
                                    if (planItem != null)

                                    {
                                        planItem.Plan_IsAutoRenew = true;
                                        planItem.Save();
                                    }

                                    //foreach (var recurringOrder in filter.Select(item => new hccRecurringOrder
                                    //{
                                    //    CartID = item.CartID,
                                    //    CartItemID = item.CartItemID,
                                    //    UserProfileID = item.UserProfileID,
                                    //    AspNetUserID = userCart.AspNetUserID,
                                    //    PurchaseNumber = userCart.PurchaseNumber,
                                    //    TotalAmount = userCart.TotalAmount
                                    //}))
                                    //{
                                    //    recurringOrder.Save();
                                    //}
                                }
                                OnSaved(new ControlSavedEventArgs(planItem.CartItemID));
                                cbxRecurring.Checked = false;
                            }
                            else
                            {
                                if (existItem.AdjustQuantity(existItem.Quantity + currentQty))
                                {
                                    OnSaved(new ControlSavedEventArgs(existItem.CartItemID));
                                }
                                cbxRecurring.Checked = false;
                            }
                        }
                    }
                }
                //Page.Response.Redirect(Page.Request.Url.ToString()+ "#tabs9", true);
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #10
0
        public string ReplaceProgramMeals(List <DefaultMenu> defaultMenus)
        {
            try
            {
                bool tryBool;
                bool isCancel   = false;
                bool isComplete = false;
                int  cartItemId = int.Parse(this.Context.Request.QueryString["cid"]);

                hccCartItem cartItem = hccCartItem.GetById(cartItemId);
                if (cartItem != null)
                {
                    if (this.Context.Request.QueryString["can"] != null)
                    {
                        tryBool = bool.TryParse(this.Context.Request.QueryString["can"], out isCancel);
                        cartItem.IsCancelled = isCancel;
                    }

                    if (this.Context.Request.QueryString["cmplt"] != null)
                    {
                        tryBool = bool.TryParse(this.Context.Request.QueryString["cmplt"], out isComplete);
                    }
                    hccCartMenuExPref cartMenuExPref = hccCartMenuExPref.GetById(cartItem.CartItemID, defaultMenus[0].DayNumber);
                    if (cartMenuExPref == null)
                    {
                        hccCartMenuExPref hccCartMenuExPref = new hccCartMenuExPref();
                        hccCartMenuExPref.CartItemID = cartItem.CartItemID;
                        hccCartMenuExPref.DayNumber  = defaultMenus[0].DayNumber;
                        hccCartMenuExPref.IsModified = true;
                        hccCartMenuExPref.Save();
                    }
                    cartItem.Save();
                }

                decimal cals1 = 0.0m, fat1 = 0.0m, prtn1 = 0.0m, carb1 = 0.0m, fbr1 = 0.0m, sod1 = 0.0m;

                foreach (DefaultMenu defaultMenuItem in defaultMenus)
                {
                    hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(cartItem.CartItemID, defaultMenuItem.CalendarID);

                    if (cartCal != null)
                    {
                        if (isComplete != cartCal.IsFulfilled)
                        {
                            cartCal.IsFulfilled = isComplete;
                            cartCal.Save();
                        }

                        // get original defaultMenuItem for comparison of menuItem
                        hccProgramDefaultMenu origDefaultMenu =
                            hccProgramDefaultMenu.GetBy(cartCal.CalendarID, defaultMenuItem.ProgramID,
                                                        defaultMenuItem.DayNumber, defaultMenuItem.MealTypeID, defaultMenuItem.Ordinal);

                        hccCartDefaultMenuException existMenuEx = hccCartDefaultMenuException.GetBy(defaultMenuItem.DefaultMenuID, cartCal.CartCalendarID);

                        if (origDefaultMenu != null &&
                            origDefaultMenu.MenuItemID == defaultMenuItem.MenuItemID &&
                            origDefaultMenu.MenuItemSizeID == defaultMenuItem.MenuItemSizeID)
                        {
                            if (string.IsNullOrWhiteSpace(defaultMenuItem.Prefs))
                            {
                                if (existMenuEx != null)
                                {
                                    List <hccCartDefaultMenuExPref> prefs = hccCartDefaultMenuExPref.GetBy(existMenuEx.DefaultMenuExceptID);
                                    prefs.ForEach(a => a.Delete());
                                    existMenuEx.Delete();
                                }
                            }
                            else
                            {
                                if (existMenuEx == null)
                                {   // create exception menuItem
                                    existMenuEx = new hccCartDefaultMenuException
                                    {
                                        CartCalendarID = cartCal.CartCalendarID,
                                        DefaultMenuID  = defaultMenuItem.DefaultMenuID
                                    };
                                }

                                existMenuEx.MenuItemID     = defaultMenuItem.MenuItemID;
                                existMenuEx.MenuItemSizeID = defaultMenuItem.MenuItemSizeID;
                                existMenuEx.Save();

                                List <hccCartDefaultMenuExPref> prefs = hccCartDefaultMenuExPref.GetBy(existMenuEx.DefaultMenuExceptID);
                                prefs.ForEach(a => a.Delete());

                                if (!string.IsNullOrWhiteSpace(defaultMenuItem.Prefs))
                                {
                                    List <string> prefIds = defaultMenuItem.Prefs.Split(',').ToList();
                                    prefIds.ForEach(delegate(string prefId)
                                    {
                                        hccCartDefaultMenuExPref exPref = new hccCartDefaultMenuExPref
                                        {
                                            DefaultMenuExceptID = existMenuEx.DefaultMenuExceptID,
                                            PreferenceID        = int.Parse(prefId)
                                        };

                                        exPref.Save();
                                    });
                                }
                            }
                        }
                        else
                        {
                            if (existMenuEx == null)
                            {   // create exception menuItem
                                existMenuEx = new hccCartDefaultMenuException
                                {
                                    CartCalendarID = cartCal.CartCalendarID,
                                    DefaultMenuID  = defaultMenuItem.DefaultMenuID
                                };
                            }

                            existMenuEx.MenuItemID     = defaultMenuItem.MenuItemID;
                            existMenuEx.MenuItemSizeID = defaultMenuItem.MenuItemSizeID;
                            existMenuEx.Save();

                            List <hccCartDefaultMenuExPref> exPrefs = hccCartDefaultMenuExPref.GetBy(existMenuEx.DefaultMenuExceptID);
                            exPrefs.ForEach(a => a.Delete());

                            if (!string.IsNullOrWhiteSpace(defaultMenuItem.Prefs))
                            {
                                List <string> prefIds = defaultMenuItem.Prefs.Split(',').ToList();
                                prefIds.ForEach(delegate(string prefId)
                                {
                                    hccCartDefaultMenuExPref exPref = new hccCartDefaultMenuExPref
                                    {
                                        DefaultMenuExceptID = existMenuEx.DefaultMenuExceptID,
                                        PreferenceID        = int.Parse(prefId)
                                    };

                                    exPref.Save();
                                });
                            }
                        }

                        hccMenuItemNutritionData nutrition;

                        if (existMenuEx == null)
                        {
                            nutrition = hccMenuItemNutritionData.GetBy(defaultMenuItem.MenuItemID);
                        }
                        else
                        {
                            nutrition = hccMenuItemNutritionData.GetBy(existMenuEx.MenuItemID);
                        }

                        if (nutrition != null)
                        {
                            cals1 = cals1 + nutrition.Calories;
                            fat1  = fat1 + nutrition.TotalFat;
                            prtn1 = prtn1 + nutrition.Protein;
                            carb1 = carb1 + nutrition.TotalCarbohydrates;
                            fbr1  = fbr1 + nutrition.DietaryFiber;
                            sod1  = sod1 + nutrition.Sodium;
                        }
                    }
                }

                string nutri = cals1.ToString("f2") + "|" + fat1.ToString("f2") + "|" + prtn1.ToString("f2") + "|" + carb1.ToString("f2") + "|" + fbr1.ToString("f2") + "|" + sod1.ToString("f2");

                return(nutri);
            }
            catch (Exception ex)
            {
                throw;
            }
        }