static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(logPath)
                         .CreateLogger();
            Log.Information("Program started");

            try
            {
                // Call the Orders API to get orders that are in 'Awaiting Fulfillment' status
                JArray ordersAwaitingFulfillment = BigCommerceController.GetOrdersAwaitingFulfillment();

                if (ordersAwaitingFulfillment.Count() == 0)
                {
                    Log.Information("No orders to import");
                    return;
                }

                ImportOrdersToNetSuite(ordersAwaitingFulfillment);

                if (ordersMissingProId.Count > 0)
                {
                    AlertB2BTeam();
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Error: {ex}");
                string      title        = "Error in NestProOrderImporter";
                string      text         = $"Error message: {ex.Message}";
                string      color        = "red";
                TeamsHelper teamsMessage = new TeamsHelper(title, text, color, errorLogsUrl);
                teamsMessage.LogToMicrosoftTeams(teamsMessage);
            }
        }
        public void WillParsePackQuantity()
        {
            ProductOptions productOptionOne = new ProductOptions();

            productOptionOne.display_name  = "Material";
            productOptionOne.display_value = "Brass";

            ProductOptions productOptionTwo = new ProductOptions();

            productOptionTwo.display_name  = "Value Pack Options";
            productOptionTwo.display_value = "4 Pack - $215.00 / Each - Best Value";

            List <ProductOptions> productOptions = new List <ProductOptions>()
            {
                productOptionOne, productOptionTwo
            };

            Product product = new Product();

            product.ProductOptions = productOptions;

            int packQuantity         = BigCommerceController.ParsePackQuantity(product);
            int expectedPackQuantity = 4;

            Assert.Equal(expectedPackQuantity, packQuantity);
        }
        public void WillCreateAShipmentRequestWithPromoBundle()
        {
            BigCommerceController.bigCommerceOrderId = 2244;

            var kitId = 3854675;
            ItemFulfillmentLine        itemFulfillmentLineOne = CreateItemFulfillmentLine(itemFulfillmentIdOne, carrierOne, itemSkuOne, trackingNumberOne, itemQuantityOne, kitId);
            ItemFulfillmentLine        itemFulfillmentLineTwo = CreateItemFulfillmentLine(itemFulfillmentIdOne, carrierOne, itemSkuTwo, trackingNumberOne, itemQuantityOne, kitId);
            List <ItemFulfillmentLine> itemFulfillments       = new List <ItemFulfillmentLine>()
            {
                itemFulfillmentLineOne, itemFulfillmentLineTwo
            };

            var itemFulfillmentGroups = itemFulfillments.GroupBy(itfil => itfil.ItemFulfillmentId);

            foreach (var itemFulfillmentGroup in itemFulfillmentGroups)
            {
                BigCommerceController.currentItemFulfillment = itemFulfillmentGroup;

                Shipment shipmentToCreate = BigCommerceController.CreateShipmentRequest(itemFulfillmentGroup);

                Assert.Single(shipmentToCreate.Items);
                Assert.Equal(2287, shipmentToCreate.Items[0].order_product_id);
                Assert.Equal(1, shipmentToCreate.Items[0].quantity);
            }
        }
        public void WillGetBasePriceAndQuantityOfProductsOnOrder()
        {
            string productsUrl = $"{BigCommerceHelper.baseUrl}/{bigCommerceOrderId}/products";

            List <Product> productsOnOrder = BigCommerceController.GetProductsOnOrder(productsUrl);

            foreach (var product in productsOnOrder)
            {
                if (product.id < 36 && product.id > 38)
                {
                    throw new Exception($"Unexpected product ID {product.id}");
                }
                else if (product.id == 36)
                {
                    Assert.Equal("149.0000", product.BasePrice);
                    Assert.Equal("149.0000", product.BaseTotal);
                    Assert.Equal(1, product.Quantity);
                    Assert.Equal("T3019US", product.Sku);
                }
                else if (product.id == 37)
                {
                    Assert.Equal("860.0000", product.BasePrice);
                    Assert.Equal("2580.0000", product.BaseTotal);
                    Assert.Equal(3, product.Quantity);
                    Assert.Equal("T3032US", product.Sku);
                }
                else if (product.id == 38)
                {
                    Assert.Equal("221.4500", product.BasePrice);
                    Assert.Equal("1107.2500", product.BaseTotal);
                    Assert.Equal(5, product.Quantity);
                    Assert.Equal("T3016US", product.Sku);
                }
            }
        }
        private static void ImportOrdersToNetSuite(JArray ordersAwaitingFulfillment)
        {
            try
            {
                foreach (var order in ordersAwaitingFulfillment)
                {
                    Order parsedOrder = JsonConvert.DeserializeObject <Order>(order.ToString());

                    if (parsedOrder.is_deleted == true)
                    {
                        Log.Information($"Skipping order {parsedOrder.customer_id} because it is marked as deleted/archived.");
                        continue;
                    }

                    BigCommerceController.customerId = parsedOrder.customer_id;
                    int bigCommerceOrderId = parsedOrder.id;
                    Log.Information($"bigCommerceOrderId Id {bigCommerceOrderId}");

                    // Get the shipping information
                    string          shippingAddressUrl      = parsedOrder.shipping_addresses.url;
                    ShippingAddress customerShippingAddress = BigCommerceController.GetCustomerShippingAddress(shippingAddressUrl);

                    // Format the request object to send to CreateCustomerRESTlet
                    OrderToImport netsuiteRequest = NetSuiteController.CreateNetSuiteRequest(parsedOrder, customerShippingAddress);

                    if (netsuiteRequest.NestProId == "")
                    {
                        // We alert these to B2B so they can contact the customer
                        ordersMissingProId.Add(bigCommerceOrderId);
                        continue;
                    }

                    netsuiteCustomerId         = NetSuiteController.GetNetSuiteCustomerId(netsuiteRequest);
                    netsuiteRequest.CustomerId = Convert.ToInt32(netsuiteCustomerId);

                    // Call the Products API to get the products on the order
                    string productsUrl = parsedOrder.products.url;
                    netsuiteRequest.Items = BigCommerceController.GetProductsOnOrder(productsUrl);

                    NetSuiteController.SetNetSuiteItemIdAndPersonalItemFlag(netsuiteRequest);

                    // Import order to Netsuite
                    string netsuiteOrderId = NetSuiteController.ImportOrderToNetSuite(netsuiteRequest);

                    // Set the Big Commerce status to 'awaiting shipment' and add the NetSuite order ID to 'staff notes'
                    BigCommerceController.SetOrderStatus(bigCommerceOrderId, netsuiteOrderId);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Error: {ex}");
                string      title        = "Error in ImportOrdersToNetSuite";
                string      text         = $"Error message: {ex.Message}";
                string      color        = "red";
                TeamsHelper teamsMessage = new TeamsHelper(title, text, color, errorLogsUrl);
                teamsMessage.LogToMicrosoftTeams(teamsMessage);
            }
        }
        public void WillGetNestProId()
        {
            BigCommerceController.customerId = 2;
            string expectedNestProId = "BB1-866";

            string nestProId = BigCommerceController.GetNestProId();

            Assert.Equal(expectedNestProId, nestProId);
        }
        public void WillGetCustomerName()
        {
            BigCommerceController.customerId = 2;

            var customerData = BigCommerceController.GetCustomerData();

            Assert.Equal("Michael", customerData.first_name);
            Assert.Equal("Owens", customerData.last_name);
        }
        public void WillGetProductsOnOrder()
        {
            string productsApiUrl       = $"{BigCommerceHelper.baseUrl}/{bigCommerceOrderId}/products";
            int    expectedProductCount = 3;

            List <Product> productsOnOrder = BigCommerceController.GetProductsOnOrder(productsApiUrl);

            Assert.Equal(expectedProductCount, productsOnOrder.Count);
        }
        public void WillGetTaxStatusOfNonExemptCustomer()
        {
            BigCommerceController.customerId = 33;
            string expectedTaxExemptionCategory = "";

            var customerData = BigCommerceController.GetCustomerData();

            Assert.Equal(expectedTaxExemptionCategory, customerData.tax_exempt_category);
        }
        public void WillSetMultipleTrackingNumbers()
        {
            string itemFulfillmentId      = "71973675";
            string expectedTrackingNumber = "1Z7849523049857 1Z3897341903472";

            string trackingNumber = BigCommerceController.GetTrackingNumbers(itemFulfillmentId);

            Assert.Equal(expectedTrackingNumber, trackingNumber);
        }
        public void WillGetOrdersAwaitingFulfillment()
        {
            JArray ordersAwaitingFulfillment = BigCommerceController.GetOrdersAwaitingFulfillment();

            foreach (var order in ordersAwaitingFulfillment)
            {
                Order parsedOrder = JsonConvert.DeserializeObject <Order>(order.ToString());
                Assert.Equal("Awaiting Fulfillment", parsedOrder.status);
            }
        }
        public void WillGetOrderProductIdOfKit()
        {
            string itemSku        = "NC5100US";
            int    orderId        = 1021;
            bool   isKit          = true;
            bool   isPersonal     = false;
            int    orderProductId = BigCommerceController.GetOrderProductId(itemSku, isKit, isPersonal, orderId);

            Assert.Equal(99, orderProductId);
        }
        public void WillGetOrderProductIdOfNonPersonalItem()
        {
            string itemSku        = "T4001ES";
            int    orderId        = 1086;
            bool   isKit          = false;
            bool   isPersonal     = false;
            int    orderProductId = BigCommerceController.GetOrderProductId(itemSku, isKit, isPersonal, orderId);

            Assert.Equal(205, orderProductId);
        }
        public void WillGetKitQuantity()
        {
            string itemSku = "T3032US";

            BigCommerceController.bigCommerceOrderId = 130;

            int kitQuantity         = BigCommerceController.GetKitQuantity(itemSku);
            int expectedKitQuantity = 4;

            Assert.Equal(expectedKitQuantity, kitQuantity);
        }
        public void WillGetItemQuantity()
        {
            BigCommerceController.bigCommerceOrderId = 130;
            var itemFulfillment = new ItemFulfillmentLine();

            itemFulfillment.KitId    = 3022285;
            itemFulfillment.Quantity = 12;
            int expectedItemQuantity = 3;

            int itemQuantity = BigCommerceController.GetItemQuantity(itemFulfillment);

            Assert.Equal(expectedItemQuantity, itemQuantity);
        }
        public void WillPostShipmentToBigCommerce()
        {
            BigCommerceController.bigCommerceOrderId = bigCommerceOrderId;
            Shipment shipmentToCreate = new Shipment(expectedCarrierOne, orderAddressId, itemFulfillmentIdOne, trackingNumberOne);
            Item     itemOne          = new Item(expectedOrderProductIdOne, itemQuantityOne);
            Item     itemTwo          = new Item(expectedOrderProductIdTwo, itemQuantityTwo);
            Item     itemThree        = new Item(expectedOrderProductIdThree, itemQuantityThree);

            shipmentToCreate.Items = new List <Item>()
            {
                itemOne, itemTwo, itemThree
            };

            Shipment shipmentCreated = BigCommerceController.PostShipmentToBigCommerce(shipmentToCreate);

            Assert.Null(shipmentCreated.Status);
            Assert.Equal(itemFulfillmentIdOne, shipmentCreated.NetSuiteItemFulfillmentId);
            Assert.Equal(trackingNumberOne, shipmentCreated.TrackingNumber);
            Assert.Equal(expectedCarrierOne, shipmentCreated.ShippingProvider);
            Assert.Equal(orderAddressId, shipmentCreated.OrderAddressId);

            foreach (var item in shipmentCreated.Items)
            {
                int orderProductId = item.order_product_id;

                if (orderProductId != expectedOrderProductIdOne && orderProductId != expectedOrderProductIdTwo && orderProductId != expectedOrderProductIdThree)
                {
                    throw new Exception($"Unexpected order product id {orderProductId}");
                }
                else if (orderProductId == expectedOrderProductIdOne)
                {
                    Assert.Equal(itemQuantityOne, item.quantity);
                }
                else if (orderProductId == expectedOrderProductIdTwo)
                {
                    Assert.Equal(itemQuantityTwo, item.quantity);
                }
                else if (orderProductId == expectedOrderProductIdThree)
                {
                    Assert.Equal(itemQuantityThree, item.quantity);
                }
            }

            // Get the status and assert that it is marked as shipped
            string orderStatus = GetOrderStatus();

            Assert.Equal("Shipped", orderStatus);

            DeleteShipment(shipmentCreated.ShipmentId);
        }
        public void WillParsePersonalItemValueForPersonalItem()
        {
            ProductOptions productOption = new ProductOptions();

            productOption.display_value = "1 Item - Personal Use - $129 / Each";
            List <ProductOptions> productOptions = new List <ProductOptions>()
            {
                productOption
            };

            bool isPersonal = BigCommerceController.isItemPersonal(productOptions);

            Assert.True(isPersonal);
        }
        public void WillSetOrderStatusToAwaitingShipmentAndNetSuiteOrderId()
        {
            string netsuiteOrderId = "70169180";

            var exception = Record.Exception(() => BigCommerceController.SetOrderStatus(bigCommerceOrderId, netsuiteOrderId));

            string[] results = GetOrderStatusAndNetSuiteOrderId(bigCommerceOrderId);

            Assert.Null(exception);
            Assert.Equal(netsuiteOrderId, results[0]);
            Assert.Equal("Awaiting Shipment", results[1]);

            ResetOrderStatusAndNetSuiteOrderId(bigCommerceOrderId, netsuiteOrderId);
        }
        public void WillGetImportedItemFulfillmentIds()
        {
            int orderId    = 126;
            int shipmentId = 10;

            SetItemFulfillmentIdOnShipment(orderId, shipmentId);

            BigCommerceController.bigCommerceOrderId = orderId;
            List <string> importedItemFulfillmentIds = BigCommerceController.GetImportedItemFulfillments();

            Assert.Equal(itemFulfillmentId, importedItemFulfillmentIds[0]);
            Assert.Equal("Janes Order", importedItemFulfillmentIds[1]);

            RemoveItemFulfillmentId(orderId, shipmentId);
        }
        public void WillGetShippingProviderFromCarrierName()
        {
            string carrier          = "UPS GROUND";
            string shippingProvider = BigCommerceController.GetShippingProviderFromCarrierName(carrier);

            Assert.Equal(expectedCarrierOne, shippingProvider);

            carrier          = "FedEx 2-Day Priority";
            shippingProvider = BigCommerceController.GetShippingProviderFromCarrierName(carrier);
            Assert.Equal(expectedCarrierTwo, shippingProvider);

            carrier          = "USPS Standard";
            shippingProvider = BigCommerceController.GetShippingProviderFromCarrierName(carrier);
            Assert.Equal(expectedCarrierThree, shippingProvider);
        }
        public void WillGetCustomerShippingAddress()
        {
            string shippingAddressUrl = $"{BigCommerceHelper.baseUrl}/{bigCommerceOrderId}/shippingaddresses";

            ShippingAddress customerShippingAddress = BigCommerceController.GetCustomerShippingAddress(shippingAddressUrl);

            Assert.Equal(31, customerShippingAddress.id);
            Assert.Equal(bigCommerceOrderId, customerShippingAddress.order_id);
            Assert.Equal("Barry", customerShippingAddress.first_name);
            Assert.Equal("Block", customerShippingAddress.last_name);
            Assert.Equal("998 Hollywood Blvd", customerShippingAddress.street_1);
            Assert.Equal("Apt D", customerShippingAddress.street_2);
            Assert.Equal("Beverly Hills", customerShippingAddress.city);
            Assert.Equal("California", customerShippingAddress.state);
            Assert.Equal("90210", customerShippingAddress.zip);
        }
        public void WillParsePersonalItemValueForNonPersonalItem()
        {
            ProductOptions productOptionOne = new ProductOptions();

            productOptionOne.display_value = "Stainless Steel";

            ProductOptions productOptionTwo = new ProductOptions();

            productOptionTwo.display_value = "4 Pack - $215.00 / Each - Best Value";

            List <ProductOptions> productOptions = new List <ProductOptions>();

            bool isPersonal = BigCommerceController.isItemPersonal(productOptions);

            Assert.False(isPersonal);
        }
        static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File(logPath)
                         .CreateLogger();
            Log.Information("Program started");

            try
            {
                // Pull orders in 'Awaiting Shipment' and 'Partially Shipped' status
                JArray ordersAwaitingShipment = BigCommerceController.GetOrdersByStatus(awaitingShipmentStatusId);
                JArray partiallyShippedOrders = BigCommerceController.GetOrdersByStatus(partiallyShippedStatusId);

                // Merge the two JArray's
                JArray allOrdersAwaitingShipments = MergeJArrays(ordersAwaitingShipment, partiallyShippedOrders);

                // Create shipments in Big Commerce if any new item fulfillments are found in NetSuite
                if (allOrdersAwaitingShipments.Count() == 0)
                {
                    Log.Information("No shipments to import");
                    return;
                }

                ImportShipmentsToBigCommerce(allOrdersAwaitingShipments);

                return;
            }
            catch (Exception ex)
            {
                Log.Error("Error: {@ex}", ex);
                string      title        = "Error in NestProShipments";
                string      text         = $"Error message: {ex.Message}";
                string      color        = "red";
                TeamsHelper teamsMessage = new TeamsHelper(title, text, color, teamsUrl);
                teamsMessage.LogToMicrosoftTeams(teamsMessage);
            }
        }
        public static void ImportShipmentsToBigCommerce(JArray allOrdersAwaitingShipments)
        {
            try
            {
                foreach (var order in allOrdersAwaitingShipments)
                {
                    Order parsedOrder = JsonConvert.DeserializeObject <Order>(order.ToString());
                    BigCommerceController.bigCommerceOrderId = parsedOrder.id;
                    Log.Information($"Big Commerce Order Id: {BigCommerceController.bigCommerceOrderId}");

                    // Query NetSuite to get any matching item fulfillments
                    string netsuiteSalesOrderId = parsedOrder.staff_notes;

                    /* Get a list of NetSuite item fulfillment ids (partially shipped orders only) that already exist
                     *  in Big Commerce to exclude so we do not create duplicate shipments.
                     */
                    List <string> importedItemFulfillmentIds = new List <string>();
                    if (parsedOrder.status.ToLower() == "partially shipped")
                    {
                        importedItemFulfillmentIds = BigCommerceController.GetImportedItemFulfillments();
                    }

                    var itemFulfillmentGroupsToImport = NetSuiteController.GetItemFulfillmentsNotImported(netsuiteSalesOrderId, importedItemFulfillmentIds);

                    // Skip line if no item fulfillments are found
                    if (itemFulfillmentGroupsToImport.Count() == 0)
                    {
                        Log.Information($"No item fulfillments to import.");
                        continue;
                    }

                    // Send each item fulfillment group to Big Commerce as a Shipment
                    foreach (var itemFulfillmentGroupToImport in itemFulfillmentGroupsToImport)
                    {
                        Log.Information($"Itfil ID: {itemFulfillmentGroupToImport.Key}");

                        BigCommerceController.currentItemFulfillment = itemFulfillmentGroupToImport;

                        Shipment shipmentToCreate = BigCommerceController.CreateShipmentRequest(itemFulfillmentGroupToImport);

                        // Big Commerce will throw exception if shipment does not have a tracking number
                        if (shipmentToCreate.TrackingNumber == "")
                        {
                            Log.Warning($"No tracking numbers found. Shipment not created.");
                            continue;
                        }

                        // Create the Shipment in Big Commerce
                        try
                        {
                            Shipment shipmentCreated = BigCommerceController.PostShipmentToBigCommerce(shipmentToCreate);
                            Log.Information($"shipment id {shipmentCreated.ShipmentId} created.");
                        }
                        catch (Exception ex)
                        {
                            string errorMessage = $"Error Posting Shipment To Big Commerce. Error: {ex}";
                            Log.Error(errorMessage);
                            string      title        = "Error in NestProShipments PostShipmentToBigCommerce";
                            string      text         = errorMessage;
                            string      color        = "yellow";
                            TeamsHelper teamsMessage = new TeamsHelper(title, text, color, Program.teamsUrl);
                            teamsMessage.LogToMicrosoftTeams(teamsMessage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMessage = $"Error in ImportShipmentsToBigCommerce. Error: {ex}";
                Log.Error(errorMessage);
                string      title        = "Error in NestProShipments ImportShipmentsToBigCommerce";
                string      text         = errorMessage;
                string      color        = "red";
                TeamsHelper teamsMessage = new TeamsHelper(title, text, color, Program.teamsUrl);
                teamsMessage.LogToMicrosoftTeams(teamsMessage);
            }
        }
        public void WillCreateAShipmentRequest()
        {
            BigCommerceController.bigCommerceOrderId = 130;

            ItemFulfillmentLine        itemFulfillmentLineOne   = CreateItemFulfillmentLine(itemFulfillmentIdOne, carrierOne, itemSkuOne, trackingNumberOne, itemQuantityOne, null);
            ItemFulfillmentLine        itemFulfillmentLineTwo   = CreateItemFulfillmentLine(itemFulfillmentIdTwo, carrierTwo, itemSkuTwo, trackingNumberTwo, itemQuantityTwo, null);
            ItemFulfillmentLine        itemFulfillmentLineThree = CreateItemFulfillmentLine(itemFulfillmentIdTwo, carrierTwo, itemSkuThree, trackingNumberTwo, itemQuantityThree, null);
            List <ItemFulfillmentLine> itemFulfillments         = new List <ItemFulfillmentLine>()
            {
                itemFulfillmentLineOne, itemFulfillmentLineTwo, itemFulfillmentLineThree
            };


            var itemFulfillmentGroups = itemFulfillments.GroupBy(itfil => itfil.ItemFulfillmentId);

            foreach (var itemFulfillmentGroup in itemFulfillmentGroups)
            {
                BigCommerceController.currentItemFulfillment = itemFulfillmentGroup;

                Shipment shipmentToCreate = BigCommerceController.CreateShipmentRequest(itemFulfillmentGroup);

                Assert.Equal(orderAddressId, shipmentToCreate.OrderAddressId);

                if (shipmentToCreate.NetSuiteItemFulfillmentId == itemFulfillmentIdOne)
                {
                    Assert.Equal(trackingNumberOne, shipmentToCreate.TrackingNumber);
                    Assert.Equal(expectedCarrierOne, shipmentToCreate.ShippingProvider);

                    // Items
                    foreach (var item in shipmentToCreate.Items)
                    {
                        Assert.Equal(expectedOrderProductIdOne, item.order_product_id);
                        Assert.Equal(itemQuantityOne, item.quantity);
                    }
                }
                else if (shipmentToCreate.NetSuiteItemFulfillmentId == itemFulfillmentIdTwo)
                {
                    Assert.Equal(trackingNumberTwo, shipmentToCreate.TrackingNumber);
                    Assert.Equal(expectedCarrierTwo, shipmentToCreate.ShippingProvider);

                    // Items
                    foreach (var item in shipmentToCreate.Items)
                    {
                        if (item.order_product_id == expectedOrderProductIdTwo)
                        {
                            Assert.Equal(expectedOrderProductIdTwo, item.order_product_id);
                            Assert.Equal(itemQuantityTwo, item.quantity);
                        }
                        else if (item.order_product_id == expectedOrderProductIdThree)
                        {
                            Assert.Equal(expectedOrderProductIdThree, item.order_product_id);
                            Assert.Equal(itemQuantityThree, item.quantity);
                        }
                        else
                        {
                            throw new Exception($"Unexpected order product id {item.order_product_id}");
                        }
                    }
                }
                else
                {
                    throw new Exception($"Unexpected item fulfillment id {shipmentToCreate.NetSuiteItemFulfillmentId}");
                }
            }
        }
        public void WillGetOrderAddressId()
        {
            int getOrderAddressIdResult = BigCommerceController.GetOrderAddressId(bigCommerceOrderId);

            Assert.Equal(orderAddressId, getOrderAddressIdResult);
        }