public bool UpdateOrders(DateTime?startDate, int orderLimit = 0)
        {
            Log("\nLoading Orders from Shopify");
            object ordersJson = shop.GetOrders(startDate);
            //Log(ordersJson.ToString());

            JObject             ordersJ = JsonConvert.DeserializeObject <JObject>(ordersJson.ToString());
            List <ShopifyOrder> orders  = JsonConvert.DeserializeObject <List <ShopifyOrder> >(ordersJ["orders"].ToString());

            Log(string.Format("{0} orders loaded.", orders.Count));
            StatusUpdate(string.Format("Updating {0} orders.", orders.Count));


            for (int i = 0; i < orders.Count; i++)
            {
                ShopifyOrder order = orders[i];

                DataSet.OrderDataTable orderDT = orderTA.GetDataByOrderID(shop.ID, order.id);

                if ((orderDT.Count == 0)) // && (order.order_number == 1008)
                {
                    int salesOrderType = 0;
                    // Order Type - different values for pending and paid
                    if (order.financial_status == "pending")
                    {
                        salesOrderType = shop.data.OrderTypePending;
                    }
                    else
                    {
                        salesOrderType = shop.data.OrderType;
                    }

                    SalesOrder sales = SalesOrder.CreateNew(visma._context, 0); // Create with type 0 and update it later in the code, otherwise we might get exception from VismaSDK
                    sales.YourOrderNumber = order.name;
                    sales.OrderDate       = order.created_at;
                    sales.OrderType       = salesOrderType;


                    // Terms of Payment
                    int?termsOfPayment = shop.GetValueIDFromShopData(shop.termsOfPayment, order.gateway);
                    if (termsOfPayment.HasValue)
                    {
                        sales.TermsOfPaymentId = termsOfPayment.Value;
                    }

                    // Delivery Method
                    int?deliveryMethod = order.shipping_lines.Count() > 0 ? shop.GetValueIDFromShopData(shop.deliveryMethods, order.shipping_lines[0].code) : null;
                    if (deliveryMethod.HasValue)
                    {
                        sales.DeliveryMethodId = deliveryMethod.Value;
                    }


                    //Log(string.Format("  {0} > {1}", order.gateway, termsOfPayment.ToString()));
                    //Log(string.Format("  {0} > {1}", order.shipping_lines.Count() > 0 ? order.shipping_lines[0].code : "", deliveryMethod.ToString()));

                    // Customer
                    Customer orderCustomer = null;
                    if (order.customer != null)
                    {
                        string customerTags = order.customer.tags;
                        //Log(customerTags);
                        if (!string.IsNullOrEmpty(customerTags))
                        {
                            string customerTag = customerTags.Split(',').Where(x => x.Trim().StartsWith("+C")).FirstOrDefault();
                            customerTag = (!string.IsNullOrEmpty(customerTag)) ? customerTag.Replace("+C", "") : customerTag;
                            int customerID = -1;
                            if (int.TryParse(customerTag, out customerID))
                            {
                                // Use existing customer from Visma
                                orderCustomer        = visma.GetCustomerByNumber(customerID);
                                sales.CustomerNumber = customerID;
                            }
                            else
                            {
                                DataSet.CustomerDataTable customerDT = customerTA.GetDataByShopifyCustomerID(shop.ID, order.customer.id);

                                if (customerDT.Count > 0)
                                {
                                    customerID           = customerDT[0].VismaCustomerNumber;
                                    orderCustomer        = visma.GetCustomerByNumber(customerID);
                                    sales.CustomerNumber = customerID;

                                    Log(string.Format("   - Order customer [#{0}] already exists in Visma as Customer {1}", order.customer.id, orderCustomer.Number));
                                }
                            }
                        }


                        if (orderCustomer == null)
                        {
                            // Create new customer in Visma
                            orderCustomer = Customer.CreateNew(visma._context);
                            string orderCustomerName = string.Format("{0} {1}", order.customer.first_name, order.customer.last_name);
                            orderCustomer.Name1 = orderCustomerName;

                            orderCustomer.SellerID        = shop.data.Seller;
                            orderCustomer.CustomerGroupID = shop.customerGroup;

                            //orderCustomer.InvoiceEmail = order.customer.email;

                            Contact orderContact = orderCustomer.Contacts.AddNew();
                            orderContact.Email = order.customer.email;

                            // Default address
                            long addressID = 0;
                            if (order.customer.default_address != null)
                            {
                                ShopifyAddress address = order.customer.default_address;
                                addressID = address.id.HasValue ? address.id.Value : 0;
                                orderCustomer.StreetAddress = string.Format("{0} {1}", address.address1, address.address2).Trim();
                                orderCustomer.City          = string.Format("{0} {1}", address.zip, address.city).Trim();
                                orderCustomer.Country       = address.country_code;

                                // If customer has a company name -> store it as the main visma Customer name
                                if (!string.IsNullOrEmpty(address.company))
                                {
                                    orderContact.Name   = orderCustomerName;
                                    orderCustomer.Name1 = address.company;
                                }

                                orderCustomer.PhoneNumber = address.phone;
                                orderContact.Phone        = address.phone;
                            }

                            // Save additional customer tags such as VAT number


                            orderCustomer.Save();
                            sales.CustomerNumber = orderCustomer.Number;

                            // Save new customer mapping to ShopifyVisma database
                            customerTA.InsertCustomer(shop.ID, order.customer.id, orderCustomer.Number, addressID, 1);

                            Log(string.Format("   - Order customer [#{0}] saved to Visma as Customer {1}", order.customer.id, orderCustomer.Number));
                        }
                    }


                    sales.TermsOfDeliveryId = shop.data.TermsOfDelivery;
                    sales.SellerId          = orderCustomer != null ? orderCustomer.SellerID : shop.data.Seller;


                    // Order delivery date
                    DateTime orderDeliveryDate = order.created_at.AddYears(1);
                    sales.DeliveryDate = orderDeliveryDate;


                    // Unifaun
                    string locationIDText = order.GetNoteAttribute("Unifaun Location ID");
                    int    locationID     = 0;
                    if (int.TryParse(locationIDText, out locationID))
                    {
                        //sales.DriverId = locationID;
                        //sales.OrdererNumber = locationID;
                    }

                    string locationName          = order.GetNoteAttribute("Unifaun Location Name");
                    string locationStreetAddress = order.GetNoteAttribute("Unifaun Location Street");
                    string locationCity          = order.GetNoteAttribute("Unifaun Location City");
                    string locationZIP           = order.GetNoteAttribute("Unifaun Location ZIP");

                    //sales.OrdererNumber



                    // Billing address
                    if (order.billing_address != null)
                    {
                        ShopifyAddress address = order.billing_address;

                        sales.CustomerName          = sales.OrdererName;
                        sales.CustomerStreetAddress = sales.OrdererStreetAddress;
                        sales.CustomerCity          = sales.OrdererCity;

                        if (orderCustomer != null)
                        {
                            //sales.OrdererNumber = orderCustomer.Number;
                            sales.CustomerNumber = orderCustomer.Number;
                        }
                    }



                    // Shipping address
                    if (order.shipping_address != null)
                    {
                        ShopifyAddress address = order.shipping_address;
                        sales.DeliveryName          = string.Format("{0} {1}", address.first_name, address.last_name).Trim();
                        sales.DeliveryStreetAddress = string.Format("{0} {1}", address.address1, address.address2).Trim();
                        sales.DeliveryCity          = string.Format("{0} {1}", address.zip, address.city).Trim();

                        sales.OrdererName          = string.Format("{0} {1}", address.first_name, address.last_name).Trim();
                        sales.OrdererStreetAddress = string.Format("{0} {1}", address.address1, address.address2).Trim();
                        sales.OrdererCity          = string.Format("{0} {1}", address.zip, address.city).Trim();

                        if (locationID > 0)
                        {
                            sales.OrdererName  = locationID.ToString();
                            sales.OrdererName2 = locationName;
                        }

                        // Unifaun shipping address
                        if (!string.IsNullOrEmpty(locationStreetAddress) && !string.IsNullOrEmpty(locationCity))
                        {
                            sales.OrdererStreetAddress = string.Format("{0}", locationStreetAddress);
                            sales.OrdererCity          = string.Format("{0} {1}", locationZIP, locationCity);
                        }

                        if (orderCustomer != null)
                        {
                            sales.DeliveryNumber = orderCustomer.Number;
                        }
                    }


                    // Order items
                    foreach (var lineItem in order.line_items)
                    {
                        SalesOrderRow salesRow = sales.SalesorderRows.AddNew();
                        salesRow.ArticleCode   = lineItem.sku;
                        salesRow.ArticleName   = lineItem.title;
                        salesRow.Amount        = lineItem.quantity;
                        salesRow.DeliveryStart = orderDeliveryDate;
                        //salesRow.VatPercent = 0;
                        if (lineItem.price.HasValue)
                        {
                            salesRow.UnitPrice = visma.ToPrice(lineItem.price.Value);
                        }
                    }

                    // Shipping items
                    foreach (var lineItem in order.shipping_lines)
                    {
                        SalesOrderRow salesRow = sales.SalesorderRows.AddNew();
                        salesRow.ArticleCode   = "207";
                        salesRow.ArticleName   = lineItem.title.Length <= 50 ? lineItem.title : lineItem.title.Substring(0, 50);
                        salesRow.Amount        = 1; // lineItem.quantity;
                        salesRow.DeliveryStart = orderDeliveryDate;
                        salesRow.VatPercent    = shop.VatRate;
                        if (lineItem.price.HasValue)
                        {
                            salesRow.UnitPrice = visma.ToPrice(lineItem.price.Value);
                        }
                    }

                    // CoD payment method
                    if (sales.TermsOfPaymentId == 20) // TODO: Move value to Shop table
                    {
                        SalesOrderRow salesRow = sales.SalesorderRows.AddNew();
                        salesRow.ArticleCode   = "204";
                        salesRow.ArticleName   = order.gateway.Length <= 50 ? order.gateway : order.gateway.Substring(0, 50);
                        salesRow.Amount        = 1; // lineItem.quantity;
                        salesRow.DeliveryStart = orderDeliveryDate;
                        salesRow.VatPercent    = shop.VatRate;
                        salesRow.UnitPrice     = 5; // TODO: Move value to Shop table
                    }



                    if (orderCustomer == null)
                    {
                    }


                    sales.Save();
                    Log(string.Format(" - Sales Order {0} created from order {1} ({2}). ", sales.Number, order.id, order.name));

                    orderTA.InsertOrder(shop.ID, order.id, sales.Number);
                }
                else
                {
                    Log(string.Format(" - Order {0} ({1}) is already in Visma.", order.id, order.name));
                }
            }

            return(true);
        }
Exemple #2
0
        /// <summary>
        /// Converts Visma Customer object into Customer JSON accepted by SHopify.
        /// </summary>
        /// <param name="article">Visma Customer object</param>
        /// <returns>Customer JSON string</returns>
        public string GetCustomerDataFromVismaCustomer(Customer customer, Contact contact, Customer invoiceCustomer, long?addressID)
        {
            Customer addressCustomer = (invoiceCustomer == null) ? customer : invoiceCustomer;

            ShopifyCustomerSimple obj = new ShopifyCustomerSimple();

            string name = customer.Name1;

            string[] nameParts = name.Split(new char[] { ' ' }, 2);
            string   firstName = nameParts[0];
            string   lastName  = (nameParts.Length > 1) ? nameParts[1] : "";
            string   email     = contact.Email;
            string   tags      = string.Format("+C{0}", customer.Number);

            if (customer.PricelistId > 0)
            {
                tags += string.Format(", +P{0}", customer.PricelistId);
            }

            obj.first_name = firstName;
            obj.last_name  = lastName;
            obj.email      = email;
            obj.tags       = tags;

            //if (id.HasValue)
            //    obj.id = id.Value;


            ShopifyAddress[] addresses = new ShopifyAddress[1];

            ShopifyAddress adr = new ShopifyAddress();

            string[] contactNameParts = contact.Name.Split(new char[] { ' ' }, 2);
            string   contactFirstName = contactNameParts[0];
            string   contactLastName  = (contactNameParts.Length > 1) ? contactNameParts[1] : "";

            string[] cityParts = addressCustomer.City.Split(new char[] { ' ' }, 2);
            string   zip       = cityParts[0];
            string   city      = (cityParts.Length > 1) ? cityParts[1] : "";
            long     zipNumber;

            string phone = (!string.IsNullOrEmpty(contact.Phone)) ? contact.Phone : contact.MobilePhone;

            if (!long.TryParse(zip, out zipNumber))
            {
                zip  = "";
                city = addressCustomer.City;
            }

            adr.first_name = contactFirstName;
            adr.last_name  = contactLastName;
            // Save company name if different than conact name
            if (contact.Name != customer.Name1)
            {
                adr.company = customer.Name1;
            }
            adr.address1 = addressCustomer.StreetAddress;
            adr.city     = city;
            adr.zip      = zip;
            if (!string.IsNullOrEmpty(addressCustomer.Country))
            {
                if (addressCustomer.Country.Length == 2)
                {
                    adr.country_code = addressCustomer.Country;
                }
                else
                {
                    // Try to convert country name to country code
                    string countryName   = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(addressCustomer.Country.ToLower());
                    var    regions       = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(x => new RegionInfo(x.LCID));
                    var    englishRegion = regions.FirstOrDefault(region => region.EnglishName.Contains(countryName));
                    if (englishRegion != null)
                    {
                        adr.country_code = englishRegion.TwoLetterISORegionName;
                    }
                }
            }

            adr.phone    = phone;
            adr.@default = true;

            if ((!string.IsNullOrEmpty(contactFirstName)) && (!string.IsNullOrEmpty(contactLastName)))
            {
                obj.first_name = contactFirstName;
                obj.last_name  = contactLastName;
            }

            if (addressID.HasValue)
            {
                adr.id = addressID.Value;
            }

            addresses[0] = adr;


            obj.default_address = addresses[0];
            obj.addresses       = addresses;


            // Serialize to Shopify JSON string
            string data = JsonConvert.SerializeObject(obj, Formatting.Indented);

            data = "{ \"customer\": " + data + "}";
            return(data);
        }