private async Task <HttpStatusCode> ScheduleNextJob(JobType jobType, IDictionary <string, string> jobPayload)
        {
            ScheduledJobInfo scheduledJobInfo = new ScheduledJobInfo
            {
                JobId            = Guid.NewGuid().ToString(),
                JobScheduledTime = DateTime.UtcNow,
                JobType          = jobType,
                JobPayload       = jobPayload
            };
            HttpStatusCode scheduleJobTask = await azureScheduler.ScheduleQueueTypeJobAsync(schedulerQueueInfo.AccountName, schedulerQueueInfo.QueueName, schedulerQueueInfo.SasToken,
                                                                                            JsonConvert.SerializeObject(scheduledJobInfo),
                                                                                            scheduledJobInfo.JobId);

            return(scheduleJobTask);
        }
Ejemplo n.º 2
0
        public async Task <IHttpActionResult> ImportMerchants([FromBody] ImportMerchantsModel merchantImportModel)
        {
            if (merchantImportModel == null)
            {
                return(BadRequest());
            }

            Log.Info($"MerchantController ImportMerchants. Payload {merchantImportModel.ToString()}");
            Guid guid;

            string errorMessage = null;

            if (string.IsNullOrWhiteSpace(merchantImportModel.ProviderId) || !Guid.TryParse(merchantImportModel.ProviderId, out guid))
            {
                errorMessage = "Invalid ProviderId";
                Log.Error(errorMessage);
                return(BadRequest(errorMessage));
            }

            if (string.IsNullOrWhiteSpace(merchantImportModel.FileName))
            {
                errorMessage = "Missing merchant file name";
                Log.Error(errorMessage);
                return(BadRequest(errorMessage));
            }

            if (!merchantImportModel.FileName.EndsWith(".xlsx", StringComparison.InvariantCultureIgnoreCase) &&
                !merchantImportModel.FileName.EndsWith(".csv", StringComparison.InvariantCultureIgnoreCase))
            {
                errorMessage = "Invalid file extension for merchant file";
                Log.Error(errorMessage);
                return(BadRequest(errorMessage));
            }

            try
            {
                var provider = (await EarnRepository.Instance.GetProviderAsync(merchantImportModel.ProviderId));
                if (provider == null)
                {
                    Log.Warn("Provider not found");
                    return(NotFound());
                }

                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2 subscriptionCertificate = store.Certificates.Find(X509FindType.FindByThumbprint, ConfigurationManager.AppSettings["SchedulerCertificateThumbprint"], false)[0];
                store.Close();

                AzureScheduler azureScheduler = new AzureScheduler(subscriptionCertificate,
                                                                   ConfigurationManager.AppSettings["SchedulerSubscriptionId"],
                                                                   ConfigurationManager.AppSettings["SchedulerCloudServiceId"],
                                                                   ConfigurationManager.AppSettings["SchedulerJobCollectionName"]);

                string           jobId            = Guid.NewGuid().ToString();
                ScheduledJobInfo scheduledJobInfo = new ScheduledJobInfo
                {
                    JobId            = jobId,
                    JobScheduledTime = DateTime.UtcNow,
                    JobPayload       = new Dictionary <string, string>
                    {
                        { JobConstants.ProviderId, merchantImportModel.ProviderId },
                        { JobConstants.ContainerName, ConfigurationManager.AppSettings["SchedulerStorageContainerName"] },
                        { JobConstants.BlobName, merchantImportModel.FileName },
                        { JobConstants.MerchantFileType, merchantImportModel.MerchantFileType.ToString() },
                        { JobConstants.Author, merchantImportModel.Author }
                    }
                };

                if (merchantImportModel.MerchantFileType == MerchantFileType.MasterCardAuth || merchantImportModel.MerchantFileType == MerchantFileType.MasterCardClearing)
                {
                    Log.Info($"Scheduling MasterCard Job for handling file type {merchantImportModel.MerchantFileType.ToString()}");
                    //Do not call visa MID lookup API if we are importing mastercard auth file. Merchant address from mastercard clearing file is always treated as ground truth
                    //Merchant address being the important parameter for MID lookup, it will be done at the time of clearing file import
                    string runVisaLookup = (merchantImportModel.MerchantFileType == MerchantFileType.MasterCardAuth) ? "false" : ConfigurationManager.AppSettings["RunVisaLookup"];

                    scheduledJobInfo.JobType = JobType.ProvisionMasterCardMid;
                    scheduledJobInfo.JobPayload.Add(JobConstants.RunVisaLookup, runVisaLookup);
                }
                else if (merchantImportModel.MerchantFileType == MerchantFileType.Visa)
                {
                    Log.Info($"Scheduling Visa Job for handling file type {merchantImportModel.MerchantFileType.ToString()}");
                    scheduledJobInfo.JobType = JobType.ProvisionRewardNetworkVisaMid;
                }
                else if (merchantImportModel.MerchantFileType == MerchantFileType.Amex)
                {
                    Log.Info($"Scheduling Amex Job for handling file type {merchantImportModel.MerchantFileType.ToString()}");
                    scheduledJobInfo.JobType = JobType.ProvisionAmexMid;
                }

                HttpStatusCode scheduleJobTask = await azureScheduler.ScheduleQueueTypeJobAsync(ConfigurationManager.AppSettings["SchedulerStorageAccountName"],
                                                                                                ConfigurationManager.AppSettings["SchedulerQueueName"],
                                                                                                ConfigurationManager.AppSettings["SchedulerSasToken"],
                                                                                                JsonConvert.SerializeObject(scheduledJobInfo),
                                                                                                jobId);

                if (scheduleJobTask == HttpStatusCode.OK || scheduleJobTask == HttpStatusCode.Created)
                {
                    Log.Info($"Successfully scheduled job");
                    return(Ok(jobId));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed processing MerchantController ImportMerchants");
                return(InternalServerError(ex));
            }

            return(InternalServerError());
        }
Ejemplo n.º 3
0
        public async Task <IHttpActionResult> CreateOrUpdate([FromBody] Offer offer, bool active = false)
        {
            Guid guid;

            if (string.IsNullOrWhiteSpace(offer.ProviderId) || !Guid.TryParse(offer.ProviderId, out guid))
            {
                Log.Warn("Invalid provider id");
                return(BadRequest("Invalid provider id"));
            }

            Log.Info("Serving OfferController CreateOrUpdate");
            try
            {
                Provider provider = (await EarnRepository.Instance.GetProviderAsync(offer.ProviderId));
                if (provider == null)
                {
                    Log.Warn("Provider not found");
                    return(NotFound());
                }

                bool result;
                bool isNew;

                if (active)
                {
                    offer.StartDate = DateTime.UtcNow;
                    offer.EndDate   = DateTime.MaxValue;
                }
                else
                {
                    offer.StartDate = offer.EndDate = DateTime.MinValue;
                }

                if (string.IsNullOrWhiteSpace(offer.Id))
                {
                    isNew    = true;
                    offer.Id = Guid.NewGuid().ToString();
                    result   = await EarnRepository.Instance.CreateAsync(new List <Offer> {
                        offer
                    });
                }
                else
                {
                    isNew = false;
                    if (!Guid.TryParse(offer.Id, out guid))
                    {
                        Log.Warn("Invalid offer id");
                        return(BadRequest("Invalid Offer Id"));
                    }

                    // check if this offer exists
                    Offer previousOffer = (await EarnRepository.Instance.GetOfferAsync(offer.Id));
                    if (previousOffer == null)
                    {
                        Log.Warn("Offer not found");
                        return(NotFound());
                    }

                    result = await EarnRepository.Instance.UpdateAsync(new List <Offer> {
                        offer
                    });
                }

                if (active)
                {
                    //If the offer is active, update the provider with the active offer
                    Log.Verbose("Setting offer {0} as active for the provider {1}", offer.Id, offer.ProviderId);
                    provider.OfferId = offer.Id;
                    result          &= await EarnRepository.Instance.UpdateAsync(new List <Provider> {
                        provider
                    });

                    Log.Verbose("Scheduling the job to register the offer with commerce");
                    //Schedule the job to register the offer, provider and merchant mids with commerce
                    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadOnly);
                    X509Certificate2 subscriptionCertificate = store.Certificates.Find(X509FindType.FindByThumbprint, ConfigurationManager.AppSettings["SchedulerCertificateThumbprint"], false)[0];
                    store.Close();

                    AzureScheduler azureScheduler = new AzureScheduler(subscriptionCertificate,
                                                                       ConfigurationManager.AppSettings["SchedulerSubscriptionId"],
                                                                       ConfigurationManager.AppSettings["SchedulerCloudServiceId"],
                                                                       ConfigurationManager.AppSettings["SchedulerJobCollectionName"]);

                    string           jobId            = Guid.NewGuid().ToString();
                    ScheduledJobInfo scheduledJobInfo = new ScheduledJobInfo
                    {
                        JobId            = jobId,
                        JobType          = JobType.SyncOfferWithCommerce,
                        JobScheduledTime = DateTime.UtcNow,
                        JobPayload       = new Dictionary <string, string>
                        {
                            { JobConstants.OfferId, offer.Id }
                        }
                    };

                    HttpStatusCode scheduleJobTask = await azureScheduler.ScheduleQueueTypeJobAsync(ConfigurationManager.AppSettings["SchedulerStorageAccountName"],
                                                                                                    ConfigurationManager.AppSettings["SchedulerQueueName"],
                                                                                                    ConfigurationManager.AppSettings["SchedulerSasToken"],
                                                                                                    JsonConvert.SerializeObject(scheduledJobInfo),
                                                                                                    jobId);

                    if (scheduleJobTask == HttpStatusCode.OK || scheduleJobTask == HttpStatusCode.Created)
                    {
                        Log.Verbose("Successfully scheduled the job to register the offer with commerce");
                    }
                }

                if (result)
                {
                    if (isNew)
                    {
                        Log.Verbose("Offer created - id {0}", offer.Id);
                        return(Created(result.ToString(), offer));
                    }

                    Log.Verbose("Offer updated - id {0}", offer.Id);

                    return(Ok(offer));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed processing OfferController CreateOrUpdate");
                return(InternalServerError(ex));
            }

            return(InternalServerError());
        }