public async Task <dynamic> Get(string companyName)
        {
            if (CheckClientSecret())
            {
                using (HttpClient client = new HttpClient())
                    using (Entities db = new Entities())
                    {
                        if (db.StoreCustomDatas.Any(x => x.StoreName == companyName) &&
                            db.StoreCustomDatas.FirstOrDefault(x => x.StoreName == companyName).ShopifyID != null)
                        {
                            StoreCustomData store = db.StoreCustomDatas.FirstOrDefault(x => x.StoreName == companyName);

                            ShopifyCredential credentials = db
                                                            .ShopifyCredentials
                                                            .Where(x => x.ID == store.ShopifyID)
                                                            .FirstOrDefault();

                            client.DefaultRequestHeaders.Add("X-Shopify-Access-Token", credentials.Password);

                            string shopifyAPIVersion = ConfigDictionary.Config()["ShopifyAdminAPIVersion"];

                            DateTimeOffset thisMonth = new DateTimeOffset(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1, 0, 0, 0, TimeSpan.Zero);

                            DateTimeOffset lastMonth = thisMonth.AddMonths(-1);

                            DateTimeOffset monthBeforeLast = thisMonth.AddMonths(-2);

                            try
                            {
                                int?ordersThisMonth = await OrdersMethods.OrdersCount(client, credentials.HostName, shopifyAPIVersion, thisMonth.ToString("yyyy-MM-ddTHH:mm:ss zzz"));

                                int?ordersLastMonth = await OrdersMethods.OrdersCount(client, credentials.HostName, shopifyAPIVersion, lastMonth.ToString("yyyy-MM-ddTHH:mm:ss zzz"));

                                int?ordersMonthBeforeLast = await OrdersMethods.OrdersCount(client, credentials.HostName, shopifyAPIVersion, monthBeforeLast.ToString("yyyy-MM-ddTHH:mm:ss zzz"));

                                return(new OrdersCountDTO(ordersThisMonth, ordersLastMonth, ordersMonthBeforeLast));
                            }
                            catch (Exception ex)
                            {
                                return(ex);
                            }
                        }
                        else
                        {
                            return(new ArgumentException($"No store was found with the name {companyName}"));
                        }
                    }
            }
            else
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden));
            }
        }
Пример #2
0
        public static async Task <dynamic> PerformBulkAction(HttpClient client, string companyName, Entities db, string shopifyAdminAPIVersion)
        {
            try
            {
                //Check Shopify credentials exist in database
                if (db.StoreCustomDatas.Any(x => x.StoreName == companyName) &&
                    db.StoreCustomDatas.FirstOrDefault(x => x.StoreName == companyName).ShopifyID != null)
                {
                    StoreCustomData store = db.StoreCustomDatas.FirstOrDefault(x => x.StoreName == companyName);

                    ShopifyCredential credentials = db
                                                    .ShopifyCredentials
                                                    .Where(x => x.ID == store.ShopifyID)
                                                    .FirstOrDefault();

                    //Create request
                    client.DefaultRequestHeaders.Add("X-Shopify-Access-Token", credentials.Password);

                    string url = $"https://{credentials.HostName}/admin/api/{shopifyAdminAPIVersion}/graphql.json";

                    StringContent query;

                    if (db.SalesDatas.Any(x => x.StoreID == store.StoreID))
                    {
                        //Some sales data for store already in database
                        DateTimeOffset mostRecent = db.LastShopifyDataUpdates.FirstOrDefault(x => x.StoreID == store.StoreID).LastUpdate;

                        //query = new StringContent($"mutation{{ bulkOperationRunQuery ( query: \"\"\" {{orders(query:\"updated_at:>'{mostRecent:yyyy-MM-ddTHH:mm:ssZ}'\") {{pageInfo {{hasNextPage}}edges {{node {{createdAt updatedAt totalPriceSet {{shopMoney {{amount}}}} refunds {{totalRefundedSet {{shopMoney {{amount}}}}}}}}cursor}}}}}}\"\"\"){{bulkOperation {{ id status}}}}}}", Encoding.UTF8, "application/graphql");
                        query = new StringContent($"mutation{{ bulkOperationRunQuery ( query: \"\"\" {{tenderTransactions(query:\"processed_at:>'{mostRecent:yyyy-MM-ddTHH:mm:ssZ}'\") {{ edges {{node {{ processedAt amount {{amount}}}}}}}}}}\"\"\"){{bulkOperation {{ id status}}}}}}", Encoding.UTF8, "application/graphql");
                    }
                    else
                    {
                        //'New' store with no sales data in database
                        //query = new StringContent($"mutation{{ bulkOperationRunQuery ( query: \"\"\" {{orders {{pageInfo {{hasNextPage}}edges {{node {{createdAt updatedAt displayFinancialStatus totalPriceSet {{shopMoney {{amount}}}} refunds {{totalRefundedSet {{shopMoney {{amount}}}}}}}}cursor}}}}}}\"\"\"){{bulkOperation {{ id status}}}}}}", Encoding.UTF8, "application/graphql");
                        query = new StringContent($"mutation{{ bulkOperationRunQuery ( query: \"\"\" {{tenderTransactions {{ edges {{ node {{ processedAt amount {{amount}}}}}}}}}}\"\"\"){{bulkOperation {{ id status}}}}}}", Encoding.UTF8, "application/graphql");
                    }

                    HttpResponseMessage response = await client.PostAsync(url, query);

                    Debug.WriteLine($"{DateTime.Now} - Response received for Graph QL query on {companyName}...");

                    if (response.IsSuccessStatusCode)
                    {
                        Debug.WriteLine("Polling...");

                        dynamic downloadURL = await PollBulkAction(client, url, db, shopifyAdminAPIVersion);

                        //Await return of JSONL file download URL in polling response
                        while (downloadURL.GetType() != typeof(string))
                        {
                            downloadURL = await PollBulkAction(client, url, db, shopifyAdminAPIVersion);
                        }

                        if (!string.IsNullOrEmpty(downloadURL))
                        {
                            return(DownloadJSONL(downloadURL, companyName));
                        }
                        else
                        {
                            return(db.SalesDatas.Where(x => x.StoreID == store.StoreID).OrderByDescending(x => x.Date));
                        }
                    }
                    else
                    {
                        return(new ArgumentException("Request to create bulk operation failed"));
                    }
                }
                else
                {
                    return(new ArgumentException($"No store was found with the name {companyName}"));
                }
            }
            catch (Exception ex)
            {
                return(ex);
            }
        }