示例#1
0
        internal void AddCustomer(customer_entity entity)
        {
            #region Command Definition
            if (addNewCustomerCommand == null)
            {
                addNewCustomerCommand             = Connection.CreateCommand();
                addNewCustomerCommand.CommandType = CommandType.Text;
                addNewCustomerCommand.CommandText = String.Format(@"INSERT INTO {0} (entity_id, entity_type_id, attribute_set_id, website_id, email, group_id, increment_id, store_id, created_at, updated_at, is_active)
                                                          VALUES (?entity_id, ?entity_type_id, ?attribute_set_id, ?website_id, ?email, ?group_id, ?increment_id, ?store_id, ?created_at, ?updated_at, ?is_active)
                                                          ", _tablesNames["customer_entity"]);

                addNewCustomerCommand.Prepare();

                addNewCustomerCommand.Parameters.AddWithValue("?entity_id", 0);
                addNewCustomerCommand.Parameters.AddWithValue("?entity_type_id", 0);
                addNewCustomerCommand.Parameters.AddWithValue("?attribute_set_id", 0);
                addNewCustomerCommand.Parameters.AddWithValue("?website_id", 0);
                addNewCustomerCommand.Parameters.AddWithValue("?email", string.Empty);
                addNewCustomerCommand.Parameters.AddWithValue("?group_id", 0);
                addNewCustomerCommand.Parameters.AddWithValue("?increment_id", string.Empty);
                addNewCustomerCommand.Parameters.AddWithValue("?store_id", 0);
                addNewCustomerCommand.Parameters.AddWithValue("?created_at", DateTime.Now);
                addNewCustomerCommand.Parameters.AddWithValue("?updated_at", DateTime.Now);
                addNewCustomerCommand.Parameters.AddWithValue("?is_active", true);
            }
            #endregion

            addNewCustomerCommand.Parameters["?entity_id"].Value        = entity.entity_id;
            addNewCustomerCommand.Parameters["?entity_type_id"].Value   = entity.entity_type_id;
            addNewCustomerCommand.Parameters["?attribute_set_id"].Value = entity.attribute_set_id;
            addNewCustomerCommand.Parameters["?website_id"].Value       = entity.website_id;
            addNewCustomerCommand.Parameters["?email"].Value            = entity.email;
            addNewCustomerCommand.Parameters["?group_id"].Value         = entity.group_id;
            addNewCustomerCommand.Parameters["?increment_id"].Value     = entity.increment_id;
            addNewCustomerCommand.Parameters["?store_id"].Value         = entity.store_id;
            addNewCustomerCommand.Parameters["?created_at"].Value       = entity.created_at;
            addNewCustomerCommand.Parameters["?updated_at"].Value       = entity.updated_at;
            addNewCustomerCommand.Parameters["?is_active"].Value        = entity.is_active;


            addNewCustomerCommand.ExecuteNonQuery();
        }
示例#2
0
        protected override void Process()
        {
            SyncMagentoDatabase();
            var configuration = GetConfiguration();

            //var BusinessUnits = configuration.AppSettings.Settings["BusinessUnits"].Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);


            foreach (var connector in base.Connectors.Where(c => ((ConnectorType)c.ConnectorType).Has(ConnectorType.Customers)))
            {
                log.Debug(connector.Connection);


                string BusinessUnits = string.Empty;

                BusinessUnits = connector.ConnectorSettings.GetValueByKey <string>("BusinessUnits", string.Empty);

                if (string.IsNullOrEmpty(BusinessUnits))
                {
                    throw new InvalidOperationException("No business units set for this connector");
                }

                var units = BusinessUnits.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);


                foreach (var businessUnit in units)
                {
                    JDECustomerSoapClient client = new Web.ServiceClient.JdeCustomerService.JDECustomerSoapClient();

                    XDocument customerData = XDocument.Parse(client.GetCustomerData(businessUnit));

                    #region Parse data
                    var customers = (from customerXml in customerData.Root.Elements("Customer")
                                     let allCustomers = customerData.Root.Elements("Customer").ToList()
                                                        let addressInfo = customerXml.Element("AddressInformation")
                                                                          let telephoneNumbers = customerXml.Element("TelephoneNumbers").Elements("TelephoneNumber")
                                                                                                 let addresses = customerXml.Element("Addresses").Elements("Address")
                                                                                                                 let accountManager = customerXml.Element("AccountManager")
                                                                                                                                      let backendRelationID = customerXml.Attribute("BackendRelationID").Value
                                                                                                                                                              let parentBackendRelationID = customerXml.Attribute("ParentBackendRelationID").Value
                                                                                                                                                                                            let hashed = string.IsNullOrEmpty(customerXml.Element("Password").Value) ? string.Empty : new UTF8Encoding().GetString(MD5.Create().ComputeHash(Encoding.Default.GetBytes(HttpUtility.HtmlDecode(customerXml.Element("Password").Value))))
                                                                                                                                                                                                         select new
                    {
                        BackendRelationID = backendRelationID,
                        ParentBackendRelationID = parentBackendRelationID,
                        Name = customerXml.Element("Name").Value,
                        Password = HttpUtility.HtmlDecode(customerXml.Element("Password").Value.Trim()),
                        TaxNumber = customerXml.Element("TaxNumber").Value,
                        KvkNr = customerXml.Element("KvkNr").Value,
                        Level = DetermineLevel(int.Parse(backendRelationID), int.Parse(parentBackendRelationID), 0, allCustomers),
                        Contacts = (from cp in customerXml.Element("ContactPersons").Elements("Person")
                                    select new
                        {
                            FirstName = cp.Element("FirstName").Value,
                            LastName = cp.Element("LastName").Value,
                            Phone = cp.Element("Phone").Value,
                            Email = cp.Element("Email").Value,
                            Occupation = cp.Element("Occupation").Value,
                            ContactType = cp.Element("ContactType").Value
                        }
                                    ),
                        Children = (from child in customerData.Root.Elements("Customer")
                                    where child.Attribute("ParentBackendRelationID").Value == backendRelationID
                                    select new
                        {
                            BackendRelationID = child.Attribute("BackendRelationID")
                        }),
                        AddressInformation = new
                        {
                            AddressLine1 = addressInfo.Element("AddressLine1").Value,
                            AddressLine2 = addressInfo.Element("AddressLine2").Value,
                            ZipCode = addressInfo.Element("ZipCode").Value,
                            City = addressInfo.Element("City").Value,
                            Country = addressInfo.Element("Country").Value,
                            AddressType = addressInfo.Element("AddressType").Value.Trim()
                        },
                        TelephoneNumbers = (from tp in telephoneNumbers
                                            select new
                        {
                            Type = tp.Element("TelephoneType").Value,
                            AreaCode = tp.Element("AreaCode").Value,
                            Number = tp.Element("Number").Value
                        }),
                        EmailAddresses = (from a in addresses
                                          select new
                        {
                            EAddress = a.Element("ElectronicAddress").Value.Trim(),
                            EAddressType = a.Element("ElectronicAddressType").Value.Trim()
                        }),
                        AccountManager = new
                        {
                            Name = accountManager.Element("Name").Value,
                            Email = accountManager.Element("Email").Value.Trim(),
                            PhoneNumber = accountManager.Element("PhoneNumber").Value
                        },
                        DefaultCarrier = customerXml.Element("DefaultCarrier").Value,
                        DefaultCarrierName = customerXml.Element("DefaultCarrierName").Value,
                        Currency = customerXml.Element("Currency").Value,
                        CreditLimit = customerXml.Element("CreditLimit").Value,
                        PaymentDays = customerXml.Element("PaymentDays").Value,
                        PaymentInstrument = customerXml.Element("PaymentInstrument").Value,
                        RouteCode = customerXml.Element("RouteCode").Value,
                        InvoiceAmount = customerXml.Element("InvoiceAmount").Value,
                        OpenInvoiceAmount = customerXml.Element("OpenInvoiceAmount").Value,
                        InvoiceCurrency = customerXml.Element("InvoiceCurrency").Value
                    });
                    #endregion

                    log.Debug("Parsed customer data");



                    string connectionString = connector.ConnectionString;

                    using (var container = new magentoContext(MagentoUtility.GetMagentoConnectionString(connectionString)))
                    {
                        try
                        {
                            #region Attributes
                            var createdInAttribute           = container.GetAttribute(1, "created_in", true, true, true);
                            var firstnameAttribute           = container.GetAttribute(1, "firstname", true, true, true);
                            var lastNameAttribute            = container.GetAttribute(1, "lastname", true, true, true);
                            var passwordAttribute            = container.GetAttribute(1, "password_hash", true, true, true);
                            var createdAtAttribute           = container.GetAttribute(1, "created_at", true, true, true);
                            var taxAttribute                 = container.GetAttribute(1, "taxvat", true, true, true);
                            var kvkAttribute                 = container.GetAttribute(1, "kvknr", true, true, true);
                            var accountManagerNameAttribute  = container.GetAttribute(1, "accountmanagername", true, true, true);
                            var accountManagerEmailAttribute = container.GetAttribute(1, "accountmanageremailaddress", true, true, true);
                            var companyNameAttribute         = container.GetAttribute(1, "companyname", true, true, true);
                            var accountManagerPhoneNumber    = container.GetAttribute(1, "accountmanagerphonenumber", true, true, true);
                            var invoiceAmountAttribute       = container.GetAttribute(1, "invoiceamount", true, true, true);
                            var openInvoiceAmountAttribute   = container.GetAttribute(1, "openinvoiceamount", true, true, true);
                            var paymentInstrumentAttribute   = container.GetAttribute(1, "paymentinstrument", true, true, true);
                            var paymentDaysAttribute         = container.GetAttribute(1, "paymentdays", true, true, true);
                            var creditLimitAttribute         = container.GetAttribute(1, "creditlimit", true, true, true);
                            var routeCodeAttribute           = container.GetAttribute(1, "routecode", true, true, true);
                            var defaultCarrierAttribute      = container.GetAttribute(1, "defaultcarrier", true, true, true);
                            var defaultCarrierNameAttribute  = container.GetAttribute(1, "defaultcarriername", true, true, true);
                            var parentAttribute              = container.GetAttribute(1, "parentrelationid", true, true, true);
                            var accountNumberAttribute       = container.GetAttribute(1, "accountnumber", true, true, true);
                            var financialAttribute           = container.GetAttribute(1, "financialemail", true, true, true);
                            var websiteAttribute             = container.GetAttribute(1, "website", true, true, true);
                            var extraEmailAttribute          = container.GetAttribute(1, "extraemail", true, true, true);


                            var telephoneAttribute        = container.GetAttribute(2, "telephones", true, true, true);
                            var cityAttribute             = container.GetAttribute(2, "city", true, true, true);
                            var countyAttribute           = container.GetAttribute(2, "country_id", true, true, true);
                            var companyAttribute          = container.GetAttribute(2, "company", true, true, true);
                            var postcodeAttribute         = container.GetAttribute(2, "postcode", true, true, true);
                            var addressLineAttribute      = container.GetAttribute(2, "street", true, true, true);
                            var billingAddressAttribute   = container.GetAttribute(1, "default_billing", true, true, true);
                            var shippingAddressAttribute  = container.GetAttribute(1, "default_shipping", true, true, true);
                            var changePendingAttribute    = container.GetAttribute(1, "changepending", true, true, true);
                            var firstNameAddressAttribute = container.GetAttribute(2, "firstname", true, true);
                            var lastNameAddressAttribute  = container.GetAttribute(2, "lastname", true, true);
                            var telephoneAddressAttribute = container.GetAttribute(2, "telephone", true, true);
                            var emailAttribute            = container.GetAttribute(1, "email", true, true, true);
                            #endregion

                            log.Info("Updated attributes");

                            #region Customer data

                            #region General customer information
                            foreach (var customer in customers)
                            {
                                try
                                {
                                    long backEndRelationID = 0;
                                    long parentRelationID  = 0;
                                    long.TryParse(customer.BackendRelationID, out backEndRelationID);
                                    long.TryParse(customer.ParentBackendRelationID, out parentRelationID);
                                    var magentoCustomer = container.customer_entity.FirstOrDefault(c => c.entity_id == backEndRelationID);

                                    if (magentoCustomer == null)
                                    {
                                        magentoCustomer = new customer_entity()
                                        {
                                            entity_id        = backEndRelationID,
                                            entity_type_id   = 1,
                                            attribute_set_id = 0,
                                            website_id       = 1,
                                            group_id         = 1,
                                            store_id         = 1,
                                            created_at       = DateTime.Now,
                                            updated_at       = DateTime.Now,
                                            is_active        = true,
                                            increment_id     = ""
                                        };

                                        container.AddTocustomer_entity(magentoCustomer);
                                    }
                                    magentoCustomer.email = "undefined@" + customer.BackendRelationID + ".com";

                                    #region customer entity attributes

                                    SyncCustomerEntityVarchar(container, changePendingAttribute, (x => x.entity_id == backEndRelationID), string.Empty, backEndRelationID);
                                    SyncCustomerEntityVarchar(container, createdInAttribute, x => x.entity_id == backEndRelationID, "JDE Import", backEndRelationID);
                                    SyncCustomerEntityVarchar(container, firstnameAttribute, x => x.entity_id == backEndRelationID, "-", backEndRelationID);
                                    SyncCustomerEntityVarchar(container, lastNameAttribute, x => x.entity_id == backEndRelationID, "-", backEndRelationID);

                                    #region Password

                                    var hasher = System.Security.Cryptography.MD5.Create();

                                    var bytes = hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(customer.Password));

                                    StringBuilder sBuilder = new StringBuilder();

                                    // Loop through each byte of the hashed data
                                    // and format each one as a hexadecimal string.
                                    for (int i = 0; i < bytes.Length; i++)
                                    {
                                        sBuilder.Append(bytes[i].ToString("x2"));
                                    }

                                    // Return the hexadecimal string.
                                    SyncCustomerEntityVarchar(container, passwordAttribute, (x => x.entity_id == backEndRelationID), string.Format("{0}:", sBuilder.ToString()), backEndRelationID);
                                    #endregion

                                    SyncCustomerEntityDateTime(container, createdAtAttribute, (x => x.entity_id == backEndRelationID), DateTime.Now, backEndRelationID);

                                    SyncCustomerEntityVarchar(container, taxAttribute, (x => x.entity_id == backEndRelationID), string.Format("{0}", customer.TaxNumber), backEndRelationID);

                                    SyncCustomerEntityVarchar(container, kvkAttribute, (x => x.entity_id == backEndRelationID), string.Format("{0}", customer.KvkNr), backEndRelationID);

                                    SyncCustomerEntityVarchar(container, accountManagerNameAttribute, (x => x.entity_id == backEndRelationID), customer.AccountManager.Name, backEndRelationID);

                                    SyncCustomerEntityVarchar(container, accountManagerEmailAttribute, (x => x.entity_id == backEndRelationID), customer.AccountManager.Email, backEndRelationID);

                                    SyncCustomerEntityVarchar(container, companyNameAttribute, (x => x.entity_id == backEndRelationID), customer.Name, backEndRelationID);

                                    SyncCustomerEntityVarchar(container, accountManagerPhoneNumber, (x => x.entity_id == backEndRelationID), customer.AccountManager.PhoneNumber, backEndRelationID);

                                    SyncCustomerEntityDecimal(container, invoiceAmountAttribute, (x => x.entity_id == backEndRelationID), customer.Try(c => decimal.Parse(c.InvoiceAmount), 0), backEndRelationID);

                                    SyncCustomerEntityDecimal(container, openInvoiceAmountAttribute, (x => x.entity_id == backEndRelationID), customer.Try(c => decimal.Parse(c.OpenInvoiceAmount), 0), backEndRelationID);

                                    SyncCustomerEntityVarchar(container, paymentInstrumentAttribute, (x => x.entity_id == backEndRelationID), customer.PaymentInstrument, backEndRelationID);

                                    SyncCustomerEntityVarchar(container, paymentDaysAttribute, (x => x.entity_id == backEndRelationID), customer.PaymentDays, backEndRelationID);

                                    SyncCustomerEntityDecimal(container, creditLimitAttribute, (x => x.entity_id == backEndRelationID), customer.Try(c => decimal.Parse(c.CreditLimit), 0), backEndRelationID);

                                    SyncCustomerEntityVarchar(container, routeCodeAttribute, (x => x.entity_id == backEndRelationID), customer.RouteCode, backEndRelationID);

                                    SyncCustomerEntityVarchar(container, defaultCarrierAttribute, (x => x.entity_id == backEndRelationID), customer.DefaultCarrier, backEndRelationID);

                                    SyncCustomerEntityVarchar(container, defaultCarrierNameAttribute, (x => x.entity_id == backEndRelationID), customer.DefaultCarrierName, backEndRelationID);

                                    SyncCustomerEntityInt(container, parentAttribute, (x => x.entity_id == backEndRelationID), int.Parse(customer.ParentBackendRelationID), backEndRelationID);

                                    SyncCustomerEntityInt(container, accountNumberAttribute, (x => x.entity_id == backEndRelationID), (int)backEndRelationID, backEndRelationID);

                                    #region Email addresses

                                    var mainEmail      = customer.EmailAddresses.FirstOrDefault(c => c.EAddressType == "A");
                                    var website        = customer.EmailAddresses.FirstOrDefault(c => c.EAddressType == "I");
                                    var financialEmail = customer.EmailAddresses.FirstOrDefault(c => c.EAddressType == "F");
                                    var extraEmails    = customer.EmailAddresses.Where(c => c.EAddressType != "A" && c.EAddressType != "I" && c.EAddressType != "F");

                                    SyncCustomerEntityVarchar(container, emailAttribute, (x => x.entity_id == backEndRelationID), mainEmail.Try(c => c.EAddress, "undefined@" + customer.BackendRelationID + ".com"), backEndRelationID);

                                    SyncCustomerEntityVarchar(container, financialAttribute, (x => x.entity_id == backEndRelationID), financialEmail.Try(c => c.EAddress, "undefined@" + customer.BackendRelationID + ".com"), backEndRelationID);

                                    SyncCustomerEntityVarchar(container, websiteAttribute, (x => x.entity_id == backEndRelationID), website.Try(c => c.EAddress, "undefined@" + customer.BackendRelationID + ".com"), backEndRelationID);

                                    string emails = string.Empty;
                                    extraEmails.ForEach((email, index) =>
                                    {
                                        emails += email.EAddress;
                                        if (index < extraEmails.Count() - 1)
                                        {
                                            emails += ",";
                                        }
                                    });

                                    SyncCustomerEntityVarchar(container, extraEmailAttribute, (x => x.entity_id == backEndRelationID), emails, backEndRelationID);

                                    #endregion

                                    #endregion

                                    foreach (var contactPerson in customer.Contacts)
                                    {
                                        var contact = container.customercontact.FirstOrDefault(c => c.customer_id == backEndRelationID && c.email == contactPerson.Email);
                                        if (contact == null)
                                        {
                                            contact = new customercontact()
                                            {
                                                customer_id = backEndRelationID,
                                                firstname   = contactPerson.FirstName,
                                                lastname    = contactPerson.LastName,
                                                is_changed  = 0,
                                                is_deleted  = 0
                                            };
                                            container.AddTocustomercontact(contact);
                                        }
                                        contact.email       = contactPerson.Email;
                                        contact.contacttype = contactPerson.ContactType;
                                        contact.phone       = contactPerson.Phone;
                                        contact.occupation  = contactPerson.Occupation;
                                        contact.phonemobile = "";
                                    }

                                    //var customerAddressEntity = container.customer_address_entity.FirstOrDefault(c => c.parent_id == backEndRelationID);
                                    //if (customerAddressEntity == null)
                                    //{
                                    //  customerAddressEntity = new customer_address_entity()
                                    //  {
                                    //    entity_type_id = 2,
                                    //    attribute_set_id = 0,
                                    //    increment_id = "0",
                                    //    parent_id = backEndRelationID,
                                    //    created_at = DateTime.Now,
                                    //    updated_at = DateTime.Now,
                                    //    is_active = true
                                    //  };
                                    //  container.AddTocustomer_address_entity(customerAddressEntity);
                                    //}
                                    container.SaveChanges();
                                }
                                catch (Exception e)
                                {
                                    log.AuditError("Customer export failed for customer " + customer.BackendRelationID, e, "Magento customer export");
                                }
                            }
                            #endregion

                            log.Info("Starting customers address import");

                            #region Customer address information new

                            foreach (var customer in customers.OrderBy(cc => cc.Level))
                            {
                                long backEndRelationID = 0;
                                long parentRelationID  = 0;
                                long.TryParse(customer.BackendRelationID, out backEndRelationID);
                                long.TryParse(customer.ParentBackendRelationID, out parentRelationID);

                                var customerEntity = container.customer_entity.FirstOrDefault(c => c.entity_id == backEndRelationID);
                                //var customerAddressEntity = container.customer_address_entity.FirstOrDefault(c => c.parent_id == backEndRelationID);

                                //if (customerAddressEntity == null) continue;addressEntityIDFromParent

                                string commaSepTels = "";
                                var    telList      = customer.TelephoneNumbers
                                                      .Select(c => c.Number).ToList();
                                var count = telList.Count;
                                telList.ForEach((tel, index) =>
                                {
                                    commaSepTels += tel;
                                    if (index < count - 1)
                                    {
                                        commaSepTels += " , ";
                                    }
                                });


                                string cityAddress     = customer.AddressInformation.City;
                                string postcodeAddress = customer.AddressInformation.ZipCode;
                                string addressLines    = string.Format("{0}\n{1}", customer.AddressInformation.AddressLine1, customer.AddressInformation.AddressLine2);

                                //shipping address
                                var addressEntityID = (int)SyncAddress(container, customer.AddressInformation.Country, countyAttribute, cityAddress, cityAttribute,
                                                                       commaSepTels, telephoneAttribute, backEndRelationID, customer.Name, companyAttribute,
                                                                       postcodeAddress, postcodeAttribute, firstNameAddressAttribute, lastNameAddressAttribute,
                                                                       telephoneAddressAttribute, addressLines, addressLineAttribute);


                                #region mapping
                                //the inserted values are the shipping address of the customer
                                SyncCustomerEntityInt(container, shippingAddressAttribute, (x => x.entity_id == customerEntity.entity_id), (int)addressEntityID, customerEntity.entity_id);

                                container.SaveChanges();

                                var parentCustomerEntity = container.customer_entity.FirstOrDefault(c => c.entity_id == parentRelationID);

                                var hasParent = (parentCustomerEntity != null && parentRelationID != 0);



                                //if no parent just map to billing address as well
                                if (customer.AddressInformation.AddressType == "X" || !hasParent)
                                {
                                    SyncCustomerEntityInt(container, billingAddressAttribute, (x => x.entity_id == backEndRelationID), addressEntityID, backEndRelationID);
                                    container.SaveChanges();
                                }
                                else //billing address of parent
                                {
                                    //var parentAddressEntity = container.customer_address_entity.FirstOrDefault(c => c.parent_id == parentRelationID);

                                    if (parentCustomerEntity == null)
                                    {
                                        log.Debug("Parent entity/Parent address entity is null");
                                        continue;
                                    }

                                    //take the billing address of the parent
                                    var billingAdressEntityID = container.customer_entity_int.FirstOrDefault(l => l.attribute_id == billingAddressAttribute.attribute_id && l.entity_id == parentRelationID).value;

                                    //var billingAddressEntity = container.customer_address_entity.FirstOrDefault(l => l.entity_id == billingAdressEntityID);
                                    var country    = container.customer_address_entity_varchar.FirstOrDefault(l => l.entity_id == billingAdressEntityID && l.attribute_id == countyAttribute.attribute_id).value;
                                    var city       = container.customer_address_entity_varchar.FirstOrDefault(l => l.entity_id == billingAdressEntityID && l.attribute_id == cityAttribute.attribute_id).value;
                                    var telephones = container.customer_address_entity_varchar.FirstOrDefault(l => l.entity_id == billingAdressEntityID && l.attribute_id == telephoneAttribute.attribute_id).value;
                                    var company    = container.customer_address_entity_varchar.FirstOrDefault(l => l.entity_id == billingAdressEntityID && l.attribute_id == companyAttribute.attribute_id).value;
                                    var postcode   = container.customer_address_entity_varchar.FirstOrDefault(l => l.entity_id == billingAdressEntityID && l.attribute_id == postcodeAttribute.attribute_id).value;
                                    var lines      = container.customer_address_entity_text.FirstOrDefault(l => l.entity_id == billingAdressEntityID && l.attribute_id == addressLineAttribute.attribute_id).value;

                                    var addressEntityIDFromParent = (int)SyncAddress(container, country, countyAttribute, city, cityAttribute, telephones, telephoneAttribute,
                                                                                     backEndRelationID, company, companyAttribute, postcode, postcodeAttribute, firstNameAddressAttribute, lastNameAddressAttribute, telephoneAddressAttribute,
                                                                                     lines, addressLineAttribute);


                                    //map the parent default billing address to the child
                                    SyncCustomerEntityInt(container, billingAddressAttribute, (l => l.entity_id == backEndRelationID), addressEntityIDFromParent, backEndRelationID);


                                    //push child address to parent without mapping as default shipping
                                    SyncAddress(container, customer.AddressInformation.Country, countyAttribute, cityAddress, cityAttribute,
                                                commaSepTels, telephoneAttribute, parentRelationID, customer.Name, companyAttribute,
                                                postcodeAddress, postcodeAttribute, firstNameAddressAttribute, lastNameAddressAttribute,
                                                telephoneAddressAttribute, addressLines, addressLineAttribute);
                                    container.SaveChanges();
                                }

                                #endregion

                                container.SaveChanges();
                            }
                            #endregion

                            #endregion
                        }
                        catch (Exception e) { log.Debug("Customer import failed", e); }
                    }
                }
            }
            log.AuditSuccess("Magento customer import finished", "Magento customer export");
        }
        private customer_address_entity SyncEntityAddress(SortedDictionary <string, eav_attribute> addressAttributeList, CustomerHelper helper, XElement customer, customer_entity entity, int address_line_id)
        {
            var addressNode = customer.Element("AddressInformation");

            var phonesNode = customer.Element("TelephoneNumbers").Elements("TelephoneNumber");

            string mainPhone = String.Empty;

            if (phonesNode.Count() > 0)
            {
                mainPhone = phonesNode.FirstOrDefault(x => x.Element("TelephoneType").Value == "TEL").Try(x => x.Element("AreaCode").Value + " " + x.Element("Number").Value, string.Empty);
            }
            else
            {
                mainPhone = "0123456789";
            }

            string addressLines = addressNode.Element("AddressLine1").Value + "\n" + addressNode.Element("AddressLine2").Value;

            string companyName = customer.Element("Name").Value;

            customer_address_entity addressEntity = helper.GetCustomerAddress(entity.entity_id, address_line_id);

            if (addressEntity == null)
            {
                addressEntity = new customer_address_entity()
                {
                    parent_id        = entity.entity_id,
                    entity_type_id   = CUSTOMER_ADDRESS_ENTITY_TYPE_ID,
                    is_active        = true,
                    attribute_set_id = 0,
                    increment_id     = "0",
                    created_at       = DateTime.Now,
                    updated_at       = DateTime.Now,
                };
            }

            helper.SyncAddress(addressEntity);

            helper.SyncAttributeValue(addressAttributeList["address_line_id"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, address_line_id, "int");

            helper.SyncAttributeValue(addressAttributeList["company"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, companyName, "varchar");

            helper.SyncAttributeValue(addressAttributeList["firstname"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, "-", "varchar");
            helper.SyncAttributeValue(addressAttributeList["lastname"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, "-", "varchar");

            helper.SyncAttributeValue(addressAttributeList["street"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, addressLines, "text");
            helper.SyncAttributeValue(addressAttributeList["postcode"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, addressNode.Element("ZipCode").Value, "varchar");
            helper.SyncAttributeValue(addressAttributeList["city"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, addressNode.Element("City").Value, "varchar");
            helper.SyncAttributeValue(addressAttributeList["country_id"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, addressNode.Element("Country").Value, "varchar");

            helper.SyncAttributeValue(addressAttributeList["telephone"].attribute_id, CUSTOMER_ADDRESS_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, addressEntity.entity_id, mainPhone, "varchar");


            return(addressEntity);
        }
        private void ProcessCustomerNode(List <string> emailAddressCodes, SortedDictionary <string, eav_attribute> attributeList, SortedDictionary <string, eav_attribute> addressAttributeList,
                                         Dictionary <int, customer_entity> existingCustomers, HashSet <string> existingEmailAddresses, CustomerHelper helper, CustomerXmlRecord record)
        {
            var customer = record.Node;

            int backendRelationId       = Convert.ToInt32(customer.Attribute("BackendRelationID").Value);
            int parentBackendRelationId = 0;

            if (record.Parent != null)
            {
                parentBackendRelationId = Convert.ToInt32(record.Parent.Node.Attribute("BackendRelationID").Value);
            }

            customer_entity entity = null;

            bool prefixEmailRecords = false;


            var electronicAddressesNode = customer.Element("Addresses").Elements("Address").Where(x => x.Element("ElectronicAddressType") != null &&
                                                                                                  emailAddressCodes.Contains(x.Element("ElectronicAddressType").Value)
                                                                                                  );

            //filter bas addresses
            electronicAddressesNode = electronicAddressesNode.Where(x =>
                                                                    !x.Element("ElectronicAddress").Value.Contains("basdistributie.") &&
                                                                    !x.Element("ElectronicAddress").Value.Contains("basdistribution.") &&
                                                                    !x.Element("ElectronicAddress").Value.Contains("basgroup."));



            if (electronicAddressesNode.Count() == 0)
            {
                if (parentBackendRelationId > 0)
                {
                    var parent = GetBillToAddress(record);
                    electronicAddressesNode = parent.Element("Addresses").Elements("Address").Where(x => x.Element("ElectronicAddressType") != null &&
                                                                                                    emailAddressCodes.Contains(x.Element("ElectronicAddressType").Value));

                    //filter bas addresses
                    electronicAddressesNode = electronicAddressesNode.Where(x =>
                                                                            !x.Element("ElectronicAddress").Value.Contains("basdistributie.") &&
                                                                            !x.Element("ElectronicAddress").Value.Contains("basdistribution.") &&
                                                                            !x.Element("ElectronicAddress").Value.Contains("basgroup."));

                    prefixEmailRecords = true;
                }

                if (electronicAddressesNode.Count() == 0)
                {
                    Logger.WarnFormat("Ignoring customer {0}, because no email address exists", backendRelationId);
                    return;
                }
            }


            string mainEmailAddress = electronicAddressesNode
                                      .OrderBy(e => emailAddressCodes.IndexOf(e.Element("ElectronicAddressType").Value)).FirstOrDefault().Try(x => x.Element("ElectronicAddress").Value, null);


            if (String.IsNullOrEmpty(mainEmailAddress))
            {
                if (parentBackendRelationId == 0)
                {
                    Logger.WarnFormat("Ignoring customer {0}, because primary email address is empty", backendRelationId);
                    return;
                }
                else
                {
                    // get parents address
                }
            }

            string financialEmailAddress = electronicAddressesNode.FirstOrDefault(x => x.Element("ElectronicAddressType").Value == "F").Try(x => x.Element("ElectronicAddress").Value, null);

            if (prefixEmailRecords)
            {
                mainEmailAddress      = String.Format("{0}_{1}", backendRelationId, mainEmailAddress);
                financialEmailAddress = String.Format("{0}_{1}", backendRelationId, financialEmailAddress);
            }


            if (!existingCustomers.TryGetValue(backendRelationId, out entity))
            {
                if (existingEmailAddresses.Contains(mainEmailAddress))
                {
                    Logger.WarnFormat("Ignoring customer {0}, because email address {1} is already exists", backendRelationId, mainEmailAddress);
                    return;
                }


                //create new
                entity = new customer_entity()
                {
                    entity_id        = backendRelationId,
                    entity_type_id   = CUSTOMER_ENTITY_TYPE_ID,
                    attribute_set_id = 0,
                    website_id       = 1,
                    group_id         = 1,
                    store_id         = 1,
                    created_at       = DateTime.Now,
                    updated_at       = DateTime.Now,
                    is_active        = true,
                    increment_id     = "",
                    email            = mainEmailAddress
                };

                helper.AddCustomer(entity);
            }
            else
            {
                if (mainEmailAddress != entity.email)
                {
                    Logger.WarnFormat("Cannot change email (for now), relation : {0}", backendRelationId);
                    return;
                }
            }


            #region Password

            string password = HttpUtility.HtmlDecode(customer.Element("Password").Value.Trim());
            var    hasher   = System.Security.Cryptography.MD5.Create();

            var bytes = hasher.ComputeHash(System.Text.Encoding.Default.GetBytes(password));

            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < bytes.Length; i++)
            {
                sBuilder.Append(bytes[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            helper.SyncAttributeValue(attributeList["password_hash"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, sBuilder.ToString());
            #endregion

            #region Entity Attributes


            helper.SyncAttributeValue(attributeList["company_name"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, customer.Element("Name").Value);

            helper.SyncAttributeValue(attributeList["firstname"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, "-");
            helper.SyncAttributeValue(attributeList["lastname"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, "-");

            helper.SyncAttributeValue(attributeList["account_number"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, backendRelationId, type: "int");

            helper.SyncAttributeValue(attributeList["created_in"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, "JD Edwards");


            string taxNumber = customer.Element("TaxNumber").Try(x => x.Value.Trim(), string.Empty);

            helper.SyncAttributeValue(attributeList["taxvat"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, taxNumber, type: "varchar");

            var accountManagerNode = customer.Element("AccountManager");

            string accountManagerName = String.Empty;

            if (accountManagerNode != null)
            {
                accountManagerName = accountManagerNode.Element("Name").Value;
            }


            helper.SyncAttributeValue(attributeList["account_manager_name"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, accountManagerName);

            #region Financial Attributes
            string  paymentInstrument = customer.Element("PaymentInstrument").Try(x => x.Value, string.Empty);
            string  paymentDays       = customer.Element("PaymentDays").Try(x => x.Value, string.Empty);
            string  routeCode         = customer.Element("RouteCode").Try(x => x.Value, string.Empty);
            decimal invoiceAmount     = customer.Element("InvoiceAmount").Try(x => Convert.ToDecimal(x.Value), 0);
            decimal invoiceAmountOpen = customer.Element("OpenInvoiceAmount").Try(x => Convert.ToDecimal(x.Value), 0);
            decimal creditLimit       = customer.Element("CreditLimit").Try(x => Convert.ToDecimal(x.Value), 0);

            helper.SyncAttributeValue(attributeList["payment_instrument"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, paymentInstrument, type: "varchar");
            helper.SyncAttributeValue(attributeList["payment_days"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, paymentDays, type: "varchar");

            helper.SyncAttributeValue(attributeList["credit_limit"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, creditLimit, type: "decimal");
            helper.SyncAttributeValue(attributeList["invoice_amount"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, invoiceAmount, type: "decimal");
            helper.SyncAttributeValue(attributeList["invoice_amount_open"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, invoiceAmountOpen, type: "decimal");

            helper.SyncAttributeValue(attributeList["route_code"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, routeCode, type: "varchar");

            #endregion

            #region Logistic Attributes

            int    defaultCarrierId   = customer.Element("DefaultCarrier").Try(x => Convert.ToInt32(x.Value), 0);
            string defaultCarrierName = customer.Element("DefaultCarrierName").Try(x => x.Value, string.Empty);

            helper.SyncAttributeValue(attributeList["default_carrier"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, defaultCarrierId, type: "int");
            helper.SyncAttributeValue(attributeList["default_carrier_name"].attribute_id, CUSTOMER_ENTITY_TYPE_ID, StoreList[CurrentStoreCode].store_id, backendRelationId, defaultCarrierName, type: "varchar");

            #endregion


            #endregion

            #region Addresses

            customer_address_entity addressEntity = SyncEntityAddress(addressAttributeList, helper, customer, entity, entity.entity_id);

            if (record.Children.Count() == 0) // no children, so default shipping remains here
            {
                helper.SyncAttributeValue(attributeList["default_shipping"].attribute_id, entity.entity_type_id, StoreList[CurrentStoreCode].store_id, entity.entity_id, addressEntity.entity_id, "int");
            }

            if (record.Parent == null)
            {
                //top level
                helper.SyncAttributeValue(attributeList["default_billing"].attribute_id, entity.entity_type_id, StoreList[CurrentStoreCode].store_id, entity.entity_id, addressEntity.entity_id, "int");
            }
            else
            {
                var billToAddress = GetBillToAddress(record);
                customer_address_entity billTo = SyncEntityAddress(addressAttributeList, helper, billToAddress,
                                                                   entity, address_line_id: Convert.ToInt32(billToAddress.Attribute("BackendRelationID").Value));

                helper.SyncAttributeValue(attributeList["default_billing"].attribute_id, entity.entity_type_id, StoreList[CurrentStoreCode].store_id, entity.entity_id, billTo.entity_id, "int");
            }

            if (record.Children.Count() > 0)
            {
                var shipToAddresses = GetChildAddresses(record.Children);

                foreach (var address in shipToAddresses)
                {
                    customer_address_entity childAddress = SyncEntityAddress(addressAttributeList, helper, address, entity, address_line_id: Convert.ToInt32(address.Attribute("BackendRelationID").Value));
                }
            }

            #endregion
        }