using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System.Linq; using Sockeye.Util; using Sockeye.Api.ControllerHelpers; using Sockeye.Models; using Newtonsoft.Json.Linq; using System.Collections.Generic; using Newtonsoft.Json; namespace Sockeye.Biz { internal class SubscriptionBiz : BizObject, IJobObject, ISearchAbleObject, IReportAbleObject, IExportAbleObject, INotifiableObject { internal SubscriptionBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles) { ct = dbcontext; UserId = currentUserId; UserTranslationId = userTranslationId; CurrentUserRoles = UserRoles; BizType = SockType.Subscription; } internal static SubscriptionBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null) { if (httpContext != null) return new SubscriptionBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items)); else return new SubscriptionBiz(ct, 1, ServerBootConfig.SOCKEYE_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdmin); } //////////////////////////////////////////////////////////////////////////////////////////////// //EXISTS internal async Task ExistsAsync(long id) { return await ct.Subscription.AnyAsync(z => z.Id == id); } //////////////////////////////////////////////////////////////////////////////////////////////// //CREATE // internal async Task CreateAsync(Subscription newObject) { await ValidateAsync(newObject, null); if (HasErrors) return null; else { newObject.Tags = TagBiz.NormalizeTags(newObject.Tags); await ct.Subscription.AddAsync(newObject); await ct.SaveChangesAsync(); await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, SockEvent.Created), ct); await SearchIndexAsync(newObject, true); await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null); await HandlePotentialNotificationEvent(SockEvent.Created, newObject); await PopulateVizFields(newObject); return newObject; } } //////////////////////////////////////////////////////////////////////////////////////////////// //GET // internal async Task GetAsync(long id, bool logTheGetEvent = true) { var ret = await ct.Subscription.Include(z => z.Items.OrderByDescending(x => x.Active).ThenBy(x => x.ExpireDate)).AsNoTracking().SingleOrDefaultAsync(z => z.Id == id); if (logTheGetEvent && ret != null) await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, SockEvent.Retrieved), ct); await PopulateVizFields(ret); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////// //UPDATE // internal async Task PutAsync(Subscription putObject) { var dbObject = await GetAsync(putObject.Id, false); if (dbObject == null) { AddError(ApiErrorCode.NOT_FOUND, "id"); return null; } if (dbObject.Concurrency != putObject.Concurrency) { AddError(ApiErrorCode.CONCURRENCY_CONFLICT); return null; } putObject.Tags = TagBiz.NormalizeTags(putObject.Tags); await ValidateAsync(putObject, dbObject); if (HasErrors) return null; ct.Replace(dbObject, putObject); try { await ct.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!await ExistsAsync(putObject.Id)) AddError(ApiErrorCode.NOT_FOUND); else AddError(ApiErrorCode.CONCURRENCY_CONFLICT); return null; } await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, putObject.Id, BizType, SockEvent.Modified), ct); await SearchIndexAsync(putObject, false); await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, putObject.Tags, dbObject.Tags); await HandlePotentialNotificationEvent(SockEvent.Modified, putObject, dbObject); await PopulateVizFields(putObject); return putObject; } //////////////////////////////////////////////////////////////////////////////////////////////// //DELETE // internal async Task DeleteAsync(long id) { using (var transaction = await ct.Database.BeginTransactionAsync()) { Subscription dbObject = await GetAsync(id, false); if (dbObject == null) { AddError(ApiErrorCode.NOT_FOUND); return false; } await ValidateCanDeleteAsync(dbObject); if (HasErrors) return false; { var IDList = await ct.Review.AsNoTracking().Where(x => x.SockType == SockType.Subscription && x.ObjectId == id).Select(x => x.Id).ToListAsync(); if (IDList.Count() > 0) { ReviewBiz b = new ReviewBiz(ct, UserId, UserTranslationId, CurrentUserRoles); foreach (long ItemId in IDList) if (!await b.DeleteAsync(ItemId, transaction)) { AddError(ApiErrorCode.CHILD_OBJECT_ERROR, null, $"Review [{ItemId}]: {b.GetErrorsAsString()}"); return false; } } } ct.Subscription.Remove(dbObject); await ct.SaveChangesAsync(); //Log event await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, "subscription", ct); await Search.ProcessDeletedObjectKeywordsAsync(dbObject.Id, BizType, ct); await TagBiz.ProcessDeleteTagsInRepositoryAsync(ct, dbObject.Tags); await FileUtil.DeleteAttachmentsForObjectAsync(BizType, dbObject.Id, ct); await transaction.CommitAsync(); await HandlePotentialNotificationEvent(SockEvent.Deleted, dbObject); return true; } } //////////////////////////////////////////////////////////////////////////////////////////////// //SEARCH // private async Task SearchIndexAsync(Subscription obj, bool isNew) { var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType); DigestSearchText(obj, SearchParams); if (isNew) await Search.ProcessNewObjectKeywordsAsync(SearchParams); else await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams); } public async Task GetSearchResultSummary(long id, SockType specificType) { var obj = await GetAsync(id, false); var SearchParams = new Search.SearchIndexProcessObjectParameters(); DigestSearchText(obj, SearchParams); return SearchParams; } public void DigestSearchText(Subscription obj, Search.SearchIndexProcessObjectParameters searchParams) { if (obj != null) { searchParams.AddText(obj.Subsite) .AddText(obj.Tags) .AddText(obj.Notes); foreach (var item in obj.Items) { searchParams.AddText(item.OriginalOrderNumber); } } } //////////////////////////////////////////////////////////////////////////////////////////////// //VALIDATION // private async Task ValidateAsync(Subscription proposedObj, Subscription currentObj) { bool isNew = currentObj == null; //Name required if (string.IsNullOrWhiteSpace(proposedObj.Subsite)) AddError(ApiErrorCode.VALIDATION_REQUIRED, "SubSite"); //MISC / NOTSET product group are not valid for keys if (proposedObj.PGroup == ProductGroup.Misc || proposedObj.PGroup == ProductGroup.NotSet) { AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "pGroup"); return; } await Task.CompletedTask; } private async Task ValidateCanDeleteAsync(Subscription inObj) { await Task.CompletedTask; } //////////////////////////////////////////////////////////////////////////////////////////////// //REPORTING // public async Task GetReportData(DataListSelectedRequest dataListSelectedRequest, Guid jobId) { if (dataListSelectedRequest.SockType == SockType.Subscription) return await GetSubscriptionsReportData(dataListSelectedRequest, jobId); else //subscription items return await GetSubscriptionItemsReportData(dataListSelectedRequest, jobId); } public async Task GetSubscriptionsReportData(DataListSelectedRequest dataListSelectedRequest, Guid jobId) { var idList = dataListSelectedRequest.SelectedRowIds; JArray ReportData = new JArray(); List batchResults = new List(); while (idList.Any()) { if (!ReportRenderManager.KeepGoing(jobId)) return null; var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE); idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray(); batchResults.Clear(); foreach (long batchId in batch) { if (!ReportRenderManager.KeepGoing(jobId)) return null; //var subId = await ct.SubscriptionItem.AsNoTracking().Where(z => z.Id == id).Select(z => z.SubscriptionId).FirstOrDefaultAsync(); batchResults.Add(await GetAsync(batchId, false)); } //these are individually fetched so there's no need to re-order like most other object types foreach (Subscription w in batchResults) { if (!ReportRenderManager.KeepGoing(jobId)) return null; var jo = JObject.FromObject(w); ReportData.Add(jo); } } vc.Clear(); return ReportData; } public async Task GetSubscriptionItemsReportData(DataListSelectedRequest dataListSelectedRequest, Guid jobId) { var idList = dataListSelectedRequest.SelectedRowIds; JArray ReportData = new JArray(); List batchResults = new List(); while (idList.Any()) { if (!ReportRenderManager.KeepGoing(jobId)) return null; var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE); idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray(); batchResults.Clear(); foreach (long batchId in batch) { if (!ReportRenderManager.KeepGoing(jobId)) return null; //var subId = .Select(z => z.SubscriptionId).FirstOrDefaultAsync(); var subItem = await ct.SubscriptionItem.AsNoTracking().Where(z => z.Id == batchId).FirstOrDefaultAsync(); await PopulateItemVizFields(subItem); batchResults.Add(subItem); } //these are individually fetched so there's no need to re-order like most other object types foreach (SubscriptionItem w in batchResults) { if (!ReportRenderManager.KeepGoing(jobId)) return null; var jo = JObject.FromObject(w); ReportData.Add(jo); } } vc.Clear(); return ReportData; } private VizCache vc = new VizCache(); //populate viz fields from provided object private async Task PopulateVizFields(Subscription o) { if (!vc.Has("customer", o.CustomerId)) { vc.Add(await ct.Customer.AsNoTracking().Where(x => x.Id == o.CustomerId).Select(x => x.Name).FirstOrDefaultAsync(), "customer", o.CustomerId); } o.CustomerViz = vc.Get("customer", o.CustomerId); foreach (var item in o.Items)//some subscriptions have a bunch of the same monthly or yearly raven user in them so this will save in that case { await PopulateItemVizFields(item, o); // if (!vc.Has("productname", item.ProductId)) // { // var productInfo = await ct.Product.AsNoTracking().Where(x => x.Id == item.ProductId).FirstOrDefaultAsync(); // vc.Add(productInfo.Name, "productname", item.ProductId); // vc.Add(productInfo.InitialPrice.ToString(), "productinitialprice", item.ProductId); // vc.Add(productInfo.RenewPrice.ToString(), "productrenewprice", item.ProductId); // } // item.ProductViz = vc.Get("productname", item.ProductId); // item.RenewPriceViz = vc.GetAsDecimal("productrenewprice", item.ProductId) ?? 0; // item.InitialPriceViz = vc.GetAsDecimal("productinitialprice", item.ProductId) ?? 0; } } //populate viz fields from provided object private async Task PopulateItemVizFields(SubscriptionItem o, Subscription sub = null) { if (sub == null) sub = await ct.Subscription.AsNoTracking().Where(z => z.Id == o.SubscriptionId).FirstOrDefaultAsync(); o.SubscriptionEmailViz = sub.FetchEmail; if (!vc.Has("customername", sub.CustomerId)) { var custInfo = await ct.Customer.AsNoTracking().Where(x => x.Id == sub.CustomerId).FirstOrDefaultAsync(); vc.Add(custInfo.Name, "customername", sub.CustomerId); vc.Add(custInfo.EmailAddress, "customeremail", sub.CustomerId); } o.CustomerViz = vc.Get("customername", sub.CustomerId); o.CustomerEmailViz = vc.Get("customeremail", sub.CustomerId); if (!vc.Has("productname", o.ProductId)) { var productInfo = await ct.Product.AsNoTracking().Where(x => x.Id == o.ProductId).FirstOrDefaultAsync(); vc.Add(productInfo.Name, "productname", o.ProductId); vc.Add(productInfo.InitialPrice.ToString(), "productinitialprice", o.ProductId); vc.Add(productInfo.RenewPrice.ToString(), "productrenewprice", o.ProductId); } o.ProductViz = vc.Get("productname", o.ProductId); o.RenewPriceViz = vc.GetAsDecimal("productrenewprice", o.ProductId) ?? 0; o.InitialPriceViz = vc.GetAsDecimal("productinitialprice", o.ProductId) ?? 0; } //////////////////////////////////////////////////////////////////////////////////////////////// // IMPORT EXPORT // public async Task GetExportData(DataListSelectedRequest dataListSelectedRequest, Guid jobId) { return await GetReportData(dataListSelectedRequest, jobId); } //////////////////////////////////////////////////////////////////////////////////////////////// //JOB / OPERATIONS // public async Task HandleJobAsync(OpsJob job) { //Hand off the particular job to the corresponding processing code //NOTE: If this code throws an exception the caller (JobsBiz::ProcessJobsAsync) will automatically set the job to failed and log the exeption so //basically any error condition during job processing should throw up an exception if it can't be handled switch (job.JobType) { case JobType.BatchCoreObjectOperation: await ProcessBatchJobAsync(job); break; default: throw new System.ArgumentOutOfRangeException($"SubscriptionBiz.HandleJob-> Invalid job type{job.JobType.ToString()}"); } } private async Task ProcessBatchJobAsync(OpsJob job) { await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Running); await JobsBiz.LogJobAsync(job.GId, $"LT:StartJob {job.SubType}"); List idList = new List(); long FailedObjectCount = 0; JObject jobData = JObject.Parse(job.JobInfo); if (jobData.ContainsKey("idList")) idList = ((JArray)jobData["idList"]).ToObject>(); else idList = await ct.Subscription.AsNoTracking().Select(z => z.Id).ToListAsync(); bool SaveIt = false; //--------------------------------- //case 4192 TimeSpan ProgressAndCancelCheckSpan = new TimeSpan(0, 0, ServerBootConfig.JOB_PROGRESS_UPDATE_AND_CANCEL_CHECK_SECONDS); DateTime LastProgressCheck = DateTime.UtcNow.Subtract(new TimeSpan(1, 1, 1, 1, 1)); var TotalRecords = idList.LongCount(); long CurrentRecord = -1; //--------------------------------- foreach (long id in idList) { try { //-------------------------------- //case 4192 //Update progress / cancel requested? CurrentRecord++; if (DateUtil.IsAfterDuration(LastProgressCheck, ProgressAndCancelCheckSpan)) { await JobsBiz.UpdateJobProgressAsync(job.GId, $"{CurrentRecord}/{TotalRecords}"); if (await JobsBiz.GetJobStatusAsync(job.GId) == JobStatus.CancelRequested) break; LastProgressCheck = DateTime.UtcNow; } //--------------------------------- SaveIt = false; ClearErrors(); Subscription o = null; //save a fetch if it's a delete if (job.SubType != JobSubType.Delete) o = await GetAsync(id, false); switch (job.SubType) { case JobSubType.TagAddAny: case JobSubType.TagAdd: case JobSubType.TagRemoveAny: case JobSubType.TagRemove: case JobSubType.TagReplaceAny: case JobSubType.TagReplace: SaveIt = TagBiz.ProcessBatchTagOperation(o.Tags, (string)jobData["tag"], jobData.ContainsKey("toTag") ? (string)jobData["toTag"] : null, job.SubType); break; case JobSubType.Delete: if (!await DeleteAsync(id)) { await JobsBiz.LogJobAsync(job.GId, $"LT:Errors {GetErrorsAsString()} id {id}"); FailedObjectCount++; } break; default: throw new System.ArgumentOutOfRangeException($"ProcessBatchJobAsync -> Invalid job Subtype{job.SubType}"); } if (SaveIt) { o = await PutAsync(o); if (o == null) { await JobsBiz.LogJobAsync(job.GId, $"LT:Errors {GetErrorsAsString()} id {id}"); FailedObjectCount++; } } //delay so we're not tying up all the resources in a tight loop await Task.Delay(Sockeye.Util.ServerBootConfig.JOB_OBJECT_HANDLE_BATCH_JOB_LOOP_DELAY); } catch (Exception ex) { await JobsBiz.LogJobAsync(job.GId, $"LT:Errors id({id})"); await JobsBiz.LogJobAsync(job.GId, ExceptionUtil.ExtractAllExceptionMessages(ex)); } } //--------------------------------- //case 4192 await JobsBiz.UpdateJobProgressAsync(job.GId, $"{++CurrentRecord}/{TotalRecords}"); //--------------------------------- await JobsBiz.LogJobAsync(job.GId, $"LT:BatchJob {job.SubType} {idList.Count}{(FailedObjectCount > 0 ? " - LT:Failed " + FailedObjectCount : "")}"); await JobsBiz.UpdateJobStatusAsync(job.GId, JobStatus.Completed); } //////////////////////////////////////////////////////////////////////////////////////////////// // NOTIFICATION PROCESSING // public async Task HandlePotentialNotificationEvent(SockEvent ayaEvent, ICoreBizObjectModel proposedObj, ICoreBizObjectModel currentObj = null) { if (ServerBootConfig.MIGRATING) return; ILogger log = Sockeye.Util.ApplicationLogging.CreateLogger(); log.LogDebug($"HandlePotentialNotificationEvent processing: [SockType:{this.BizType}, AyaEvent:{ayaEvent}]"); bool isNew = currentObj == null; //STANDARD EVENTS FOR ALL OBJECTS await NotifyEventHelper.ProcessStandardObjectEvents(ayaEvent, proposedObj, ct); //SPECIFIC EVENTS FOR THIS OBJECT Subscription o = (Subscription)proposedObj; //## DELETED EVENTS //any event added below needs to be removed, so //just blanket remove any event for this object of eventtype that would be added below here //do it regardless any time there's an update and then //let this code below handle the refreshing addition that could have changes //await NotifyEventHelper.ClearPriorEventsForObject(ct, SockType.Subscription, o.Id, NotifyEventType.ContractExpiring); //## CREATED / MODIFIED EVENTS if (ayaEvent == SockEvent.Created || ayaEvent == SockEvent.Modified) { } }//end of process notifications ///////////////////////////////////////////////////////////////////// }//eoc }//eons