Exemplo n.º 1
0
        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);
        }