Exemple #1
0
        public Guid AddAddressToCustomer([FromUri] Guid customerId, [FromBody] Address address)
        {
            CustomerContact contact    = CustomerContext.Current.GetContactById(customerId);
            CustomerAddress newAddress = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);

            // Get data from contact
            if (string.IsNullOrEmpty(address.FirstName))
            {
                address.FirstName = contact.FirstName;
            }
            if (string.IsNullOrEmpty(address.LastName))
            {
                address.LastName = contact.LastName;
            }
            if (string.IsNullOrEmpty(address.Email))
            {
                address.Email = contact.Email;
            }

            address.Populate(newAddress);
            contact.AddContactAddress(newAddress);
            contact.SaveChanges();

            return((Guid)newAddress.AddressId);
        }
Exemple #2
0
        /// <summary>
        /// Adds the customer address.
        /// </summary>
        /// <param name="orderAddress">The order address.</param>
        /// <returns></returns>
        private static void AddCustomerAddress(OrderAddress orderAddress)
        {
            var contact = CustomerContext.Current.GetContactById(SecurityContext.Current.CurrentUserId);

            if (contact == null)
            {
                return;
            }

            var address = contact.ContactAddresses.FirstOrDefault(x => x.Name.Equals(orderAddress.Name));

            if (address == null)
            {
                address              = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);
                address.AddressType  = CustomerAddressTypeEnum.Public;
                address.CreatorId    = SecurityContext.Current.CurrentUserId;
                address.Created      = DateTime.Now.ToUniversalTime();
                address.PrimaryKeyId = BusinessManager.Create(address);
                if (!contact.ContactAddresses.Any(x => x.PrimaryKeyId == address.PrimaryKeyId))
                {
                    address.ContactId = contact.PrimaryKeyId;
                }
            }

            address.ModifierId = SecurityContext.Current.CurrentUserId;
            address.Modified   = DateTime.Now.ToUniversalTime();
            OrderAddress.CopyOrderAddressToCustomerAddress(orderAddress, address);
            BusinessManager.Update(address);
        }
        public CustomerContact CreateCustomer(string email, string password, string phone, OrderAddress billingAddress,
                                              OrderAddress shippingAddress, bool hasPassword, Action <MembershipCreateStatus> userCreationFailed)
        {
            MembershipCreateStatus createStatus;
            var user = Membership.CreateUser(email, password, email, null, null, true, out createStatus);

            switch (createStatus)
            {
            case MembershipCreateStatus.Success:

                Roles.AddUserToRole(user.UserName, Mediachase.Commerce.Core.AppRoles.EveryoneRole);
                Roles.AddUserToRole(user.UserName, Mediachase.Commerce.Core.AppRoles.RegisteredRole);

                var customer = CustomerContext.Current.GetContactForUser(user);
                customer.FirstName = billingAddress.FirstName;
                customer.LastName  = billingAddress.LastName;
                customer.FullName  = string.Format("{0} {1}", customer.FirstName, customer.LastName);
                customer.SetPhoneNumber(phone);
                customer.SetHasPassword(hasPassword);

                var customerBillingAddress = CustomerAddress.CreateForApplication(Mediachase.Commerce.Core.AppContext.Current.ApplicationId);
                OrderAddress.CopyOrderAddressToCustomerAddress(billingAddress, customerBillingAddress);
                customer.AddContactAddress(customerBillingAddress);
                customer.SaveChanges();
                customer.PreferredBillingAddressId = customerBillingAddress.AddressId;
                customerBillingAddress.Name        = string.Format("{0}, {1} {2}", customerBillingAddress.Line1,
                                                                   customerBillingAddress.PostalCode, customerBillingAddress.City);
                CheckCountryCode(customerBillingAddress);
                BusinessManager.Update(customerBillingAddress);
                customer.SaveChanges();

                var customerShippingAddress = CustomerAddress.CreateForApplication(Mediachase.Commerce.Core.AppContext.Current.ApplicationId);
                OrderAddress.CopyOrderAddressToCustomerAddress(shippingAddress, customerShippingAddress);
                customer.AddContactAddress(customerShippingAddress);
                customer.SaveChanges();
                customer.PreferredShippingAddressId = customerShippingAddress.AddressId;
                customerShippingAddress.Name        = string.Format("{0}, {1} {2}", customerShippingAddress.Line1,
                                                                    customerShippingAddress.PostalCode, customerShippingAddress.City);
                CheckCountryCode(customerShippingAddress);
                BusinessManager.Update(customerShippingAddress);
                customer.SaveChanges();

                return(customer);

            default:
                userCreationFailed(createStatus);
                break;
            }
            return(null);
        }
        /// <summary>
        /// If current user is registered user, try to save the OrderAddress to its Contact.
        /// </summary>
        /// <param name="orderAddress">The modified order address.</param>
        /// <param name="customerAddressType">The customer address type.</param>
        private static void TrySaveCustomerAddress(IOrderAddress orderAddress, CustomerAddressTypeEnum customerAddressType)
        {
            if (HttpContext.Current == null)
            {
                return;
            }
            var httpProfile = HttpContext.Current.Profile;
            var profile     = httpProfile == null ? null : new CustomerProfileWrapper(httpProfile);

            if (profile == null || profile.IsAnonymous)
            {
                return;
            }

            // Add to contact address
            var customerContact = PrincipalInfo.CurrentPrincipal.GetCustomerContact();

            if (customerContact != null)
            {
                var customerAddress = CustomerAddress.CreateForApplication();
                customerAddress.Name               = orderAddress.Id;
                customerAddress.AddressType        = customerAddressType;
                customerAddress.City               = orderAddress.City;
                customerAddress.CountryCode        = orderAddress.CountryCode;
                customerAddress.CountryName        = orderAddress.CountryName;
                customerAddress.DaytimePhoneNumber = orderAddress.DaytimePhoneNumber;
                customerAddress.Email              = orderAddress.Email;
                customerAddress.EveningPhoneNumber = orderAddress.EveningPhoneNumber;
                customerAddress.FirstName          = orderAddress.FirstName;
                customerAddress.LastName           = orderAddress.LastName;
                customerAddress.Line1              = orderAddress.Line1;
                customerAddress.Line2              = orderAddress.Line2;
                customerAddress.PostalCode         = orderAddress.PostalCode;
                customerAddress.RegionName         = orderAddress.RegionName;
                customerAddress.RegionCode         = orderAddress.RegionCode;

#pragma warning disable 618
                if (customerContact.ContactAddresses == null || !IsAddressInCollection(customerContact.ContactAddresses, customerAddress))
#pragma warning restore 618
                {
                    // If there is an address has the same name with new address,
                    // rename new address by appending the index to the name.
                    var addressCount = customerContact.ContactAddresses.Count(a => a.Name == customerAddress.Name);
                    customerAddress.Name = $"{customerAddress.Name}{(addressCount == 0 ? string.Empty : "-" + addressCount.ToString())}";

                    customerContact.AddContactAddress(customerAddress);
                    customerContact.SaveChanges();
                }
            }
        }
        public void Save(Address model)
        {
            CustomerAddress address = _currentContact.ContactAddresses.FirstOrDefault(a => a.AddressId.ToString() == model.Id);

            PrimaryKeyId addressId;

            if (address == null)
            {
                address = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);

                _currentContact.AddContactAddress(address);
                _currentContact.SaveChanges();
                addressId = address.AddressId;
            }
            else
            {
                addressId = address.AddressId;
            }

            address.Name        = string.Format("{0}, {1} {2}", model.StreetAddress, model.City, model.ZipCode);
            address.FirstName   = model.FirstName;
            address.LastName    = model.LastName;
            address.Line1       = model.StreetAddress;
            address.PostalCode  = model.ZipCode;
            address.City        = model.City;
            address.CountryCode = model.CountryCode;
            if (string.IsNullOrEmpty(address.Name))
            {
                address.Name = Guid.NewGuid().ToString();
            }

            _currentContact.SaveChanges();

            if (model.IsPreferredBillingAddress)
            {
                _currentContact.PreferredBillingAddressId = addressId;
            }

            if (model.IsPreferredShippingAddress)
            {
                _currentContact.PreferredShippingAddressId = addressId;
            }


            BusinessManager.Update(address);
            _currentContact.SaveChanges();
        }
        /// <summary>
        /// Converts to customer address.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <returns></returns>
        public static Mediachase.Commerce.Customers.CustomerAddress ConvertToCustomerAddress(OrderAddress address)
        {
            Mediachase.Commerce.Customers.CustomerAddress newAddress = CustomerAddress.CreateForApplication();

            newAddress.Name = GetAddressName(address);

            newAddress.City               = address.City;
            newAddress.CountryCode        = address.CountryCode;
            newAddress.CountryName        = address.CountryName;
            newAddress.DaytimePhoneNumber = address.DaytimePhoneNumber;
            newAddress.Email              = address.Email;
            newAddress.EveningPhoneNumber = address.EveningPhoneNumber;
            //newAddress.FaxNumber = address.FaxNumber;
            newAddress.FirstName = address.FirstName;
            newAddress.LastName  = address.LastName;
            newAddress.Line1     = address.Line1;
            newAddress.Line2     = address.Line2;
            //newAddress.Organization = address.Organization;
            newAddress.PostalCode = address.PostalCode;
            newAddress.RegionName = address.RegionName;
            newAddress.RegionCode = address.RegionCode;
            newAddress.State      = address.State;
            return(newAddress);
        }
Exemple #7
0
        //private void AddClubPoints()
        //{
        //    if (CustomerContext.Current.CurrentContact != null)
        //    {
        //        //this.contact = CustomerContext.Current.CurrentContact;
        //        //this.AddClubCardPoints(OrderGroup);

        //    }
        //}

        #region From Fund. Address & Shipping

        private IOrderAddress AddAddressToOrder(ICart cart)
        {
            IOrderAddress shippingAddress;

            if (CustomerContext.Current.CurrentContact == null)
            {
                // Anonymous... one way of "doing it"... for example, if no other address exist
                var shipment = cart.GetFirstShipment(); // ... moved to shipment - prev. = .OrderAddresses.Add(

                if (shipment.ShippingAddress != null)
                {
                    //return false/true; // Should clean up? ... did earlier for ship & pay
                }


                //Shipment oldShip = shipment as Shipment;
                shippingAddress = shipment.ShippingAddress = // should be an else here... below?
                                                             new OrderAddress
                {
                    CountryCode        = "USA",
                    CountryName        = "United States",
                    Name               = "SomeCustomerAddressName",
                    DaytimePhoneNumber = "123456",
                    FirstName          = "John",
                    LastName           = "Smith",
                    Email              = "*****@*****.**",
                };
            }
            else
            {
                // Logged in
                if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null)
                {
                    // no pref. address set... so we set one for the contact
                    CustomerAddress newCustAddress =
                        CustomerAddress.CreateForApplication(Mediachase.Commerce.Core.AppContext.Current.ApplicationId);
                    newCustAddress.AddressType        = CustomerAddressTypeEnum.Shipping; // mandatory
                    newCustAddress.ContactId          = CustomerContext.Current.CurrentContact.PrimaryKeyId;
                    newCustAddress.CountryCode        = "SWE";
                    newCustAddress.CountryName        = "Sweden";
                    newCustAddress.Name               = "new customer address"; // mandatory
                    newCustAddress.DaytimePhoneNumber = "123456";
                    newCustAddress.FirstName          = CustomerContext.Current.CurrentContact.FirstName;
                    newCustAddress.LastName           = CustomerContext.Current.CurrentContact.LastName;
                    newCustAddress.Email              = "*****@*****.**";

                    // note: Line1 & City is what is shown in CM at a few places... not the Name
                    CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress);
                    CustomerContext.Current.CurrentContact.SaveChanges();

                    // ... needs to be in this order
                    CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress;
                    CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again

                    // then, for the cart
                    //.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress)); - OLD
                    shippingAddress = new OrderAddress(newCustAddress); // - NEW
                }
                else
                {
                    // 3:rd vay there is a preferred address set (and, a fourth alternative exists... do later )
                    shippingAddress = new OrderAddress(
                        CustomerContext.Current.CurrentContact.PreferredShippingAddress);
                }
            }

            return(shippingAddress);
        }
Exemple #8
0
        /// <summary>
        /// Handles the Click event of the save control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void save_Click(object sender, EventArgs e)
        {
            var contact = CustomerContext.Current.CurrentContact;

            if (contact == null)
            {
                return;
            }

            var address = contact.ContactAddresses.FirstOrDefault(x => x.AddressId.ToString().ToLower().Equals(_addressId.ToLower()));

            var isNew = false;

            if (address == null)
            {
                address           = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);
                address.ContactId = contact.PrimaryKeyId;
                isNew             = true;
            }

            address.Name        = addressName.Text;
            address.Line1       = address1.Text;
            address.Line2       = address2.Text;
            address.City        = city.Text;
            address.CountryCode = country.SelectedValue;
            address.CountryName = country.SelectedItem.ToString();

            if (state.Visible)
            {
                address.State      = state.SelectedValue;
                address.RegionName = state.SelectedValue;
            }
            else
            {
                address.RegionName = region.Text;
            }

            address.PostalCode         = zipcode.Text;
            address.OrganizationName   = companyName.Text;
            address.DaytimePhoneNumber = phoneNumber.Text;
            address.Email     = emailAddress.Text;
            address.FirstName = firstName.Text;
            address.LastName  = lastName.Text;

            if (isNew)
            {
                address.PrimaryKeyId = BusinessManager.Create(address);
            }
            else
            {
                BusinessManager.Update(address);
            }

            if (defaultBilling.Checked)
            {
                contact.PreferredBillingAddressId = address.PrimaryKeyId;
            }
            else if (!defaultBilling.Checked && contact.PreferredBillingAddressId == address.PrimaryKeyId)
            {
                contact.PreferredBillingAddressId = null;
            }

            if (defaultShipping.Checked)
            {
                contact.PreferredShippingAddressId = address.PrimaryKeyId;
            }
            else if (!defaultShipping.Checked && contact.PreferredShippingAddressId == address.PrimaryKeyId)
            {
                contact.PreferredShippingAddressId = null;
            }

            contact.SaveChanges();
            Context.RedirectFast("/self-service/your-addresses/");
        }
        //Exercise (E2) Do CheckOut
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // ToDo: declare a variable for CartHelper
            CartHelper ch = new CartHelper(Cart.DefaultName);

            int orderAddressId = 0;

            // ToDo: Addresses (an If-Else)
            if (CustomerContext.Current.CurrentContact == null)
            {
                // Anonymous... one way of "doing it"... for example, if no other address exist
                orderAddressId = ch.Cart.OrderAddresses.Add(
                    new OrderAddress
                {
                    CountryCode        = "SWE",
                    CountryName        = "Sweden",
                    Name               = "SomeCustomerAddress",
                    DaytimePhoneNumber = "123456",
                    FirstName          = "John",
                    LastName           = "Smith",
                    Email              = "*****@*****.**",
                });
            }
            else
            {
                // Logged in
                if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null)
                {
                    // no pref. address set... so we set one for the contact
                    CustomerAddress newCustAddress =
                        CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);
                    newCustAddress.AddressType        = CustomerAddressTypeEnum.Shipping; // mandatory
                    newCustAddress.ContactId          = CustomerContext.Current.CurrentContact.PrimaryKeyId;
                    newCustAddress.CountryCode        = "SWE";
                    newCustAddress.CountryName        = "Sweden";
                    newCustAddress.Name               = "new customer address"; // mandatory
                    newCustAddress.DaytimePhoneNumber = "123456";
                    newCustAddress.FirstName          = CustomerContext.Current.CurrentContact.FirstName;
                    newCustAddress.LastName           = CustomerContext.Current.CurrentContact.LastName;
                    newCustAddress.Email              = "*****@*****.**";

                    // note: Line1 & City is what is shown in CM at a few places... not the Name
                    CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress);
                    CustomerContext.Current.CurrentContact.SaveChanges();

                    // ... needs to be in this order
                    CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress;
                    CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress));
                }
                else
                {
                    // there is a preferred address set (and, a fourth alternative exists... do later )
                    OrderAddress orderAddress =
                        new OrderAddress(CustomerContext.Current.CurrentContact.PreferredShippingAddress);

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(orderAddress);
                }
            }

            // Depending how it was created...
            OrderAddress address = ch.FindAddressById(orderAddressId.ToString());

            // ToDo: Define Shipping
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            int shippingId = ch.Cart.OrderForms[0].Shipments.Add(
                new Shipment
            {                                          // ...removing anything?
                ShippingAddressId      = address.Name, // note: use no custom prefixes
                ShippingMethodId       = theShip.ShippingMethodId,
                ShippingMethodName     = theShip.Name,
                ShipmentTotal          = theShip.BasePrice,
                ShipmentTrackingNumber = "My tracking number",
            });

            // get the Shipping ... check to see if the Shipping knows about the LineItem
            Shipment firstOrderShipment = ch.Cart.OrderForms[0].Shipments.FirstOrDefault();

            // First (and only) OrderForm
            LineItemCollection lineItems = ch.Cart.OrderForms[0].LineItems;

            // ...basic now... one OrderForm - one Shipping
            foreach (LineItem lineItem in lineItems)
            {
                int index = lineItems.IndexOf(lineItem);
                if ((firstOrderShipment != null) && (index != -1))
                {
                    firstOrderShipment.AddLineItemIndex(index, lineItem.Quantity);
                }
            }


            // Execute the "Shipping & Taxes - WF" (CartPrepare) ... and take care of the return object
            WorkflowResults resultPrepare     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartPrepareWorkflowName);
            List <string>   wfMessagesPrepare = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultPrepare));


            // ToDo: Define Shipping
            PaymentMethodDto.PaymentMethodRow thePay = PaymentManager.GetPaymentMethod(model.SelectedPayId).PaymentMethod.First();
            Payment firstOrderPayment = ch.Cart.OrderForms[0].Payments.AddNew(typeof(OtherPayment));

            // ... need both below
            firstOrderPayment.Amount            = firstOrderShipment.SubTotal + firstOrderShipment.ShipmentTotal; // will change...
            firstOrderPayment.BillingAddressId  = address.Name;
            firstOrderPayment.PaymentMethodId   = thePay.PaymentMethodId;
            firstOrderPayment.PaymentMethodName = thePay.Name;
            // ch.Cart.CustomerName = "John Smith"; // ... this line overwrites what´s in there, if logged in


            // Execute the "Payment activation - WF" (CartCheckout) ... and take care of the return object
            // ...activates the gateway (same for shipping)
            WorkflowResults resultCheckout     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartCheckOutWorkflowName, false);
            List <string>   wfMessagesCheckout = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultCheckout));
            //ch.RunWorkflow("CartValidate") ... can see this (or variations)

            string        trackingNumber = String.Empty;
            PurchaseOrder purchaseOrder  = null;

            // Add a transaction scope and convert the cart to PO
            using (var scope = new Mediachase.Data.Provider.TransactionScope())
            {
                purchaseOrder = ch.Cart.SaveAsPurchaseOrder();
                ch.Cart.Delete();
                ch.Cart.AcceptChanges();
                trackingNumber = purchaseOrder.TrackingNumber;
                scope.Complete();
            }

            // Housekeeping below (Shipping release, OrderNotes and save the order)
            OrderStatusManager.ReleaseOrderShipment(purchaseOrder.OrderForms[0].Shipments[0]);

            OrderNotesManager.AddNoteToPurchaseOrder(purchaseOrder, DateTime.UtcNow.ToShortDateString() + " released for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId);

            purchaseOrder.ExpirationDate = DateTime.UtcNow.AddDays(30);
            purchaseOrder.Status         = OrderStatus.InProgress.ToString();

            purchaseOrder.AcceptChanges(); // need this here, else no "order-note" persisted


            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Service.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = trackingNumber;

            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }