using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using System.Linq; using AyaNova.Util; using AyaNova.Api.ControllerHelpers; using Microsoft.Extensions.Logging; using AyaNova.Models; using Newtonsoft.Json.Linq; using System.Collections.Generic; using Newtonsoft.Json; namespace AyaNova.Biz { internal class CustomerServiceRequestBiz : BizObject, IJobObject, ISearchAbleObject, IReportAbleObject, IExportAbleObject, IImportAbleObject, INotifiableObject { internal CustomerServiceRequestBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles) { ct = dbcontext; UserId = currentUserId; UserTranslationId = userTranslationId; CurrentUserRoles = UserRoles; BizType = AyaType.CustomerServiceRequest; } internal static CustomerServiceRequestBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null) { if (httpContext != null) return new CustomerServiceRequestBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items)); else return new CustomerServiceRequestBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdmin); } //////////////////////////////////////////////////////////////////////////////////////////////// //EXISTS internal async Task ExistsAsync(long id) { return await ct.CustomerServiceRequest.AnyAsync(z => z.Id == id); } //////////////////////////////////////////////////////////////////////////////////////////////// //CREATE // internal async Task CreateAsync(CustomerServiceRequest newObject) { await ValidateAsync(newObject, null); if (HasErrors) return null; else { newObject.Tags = TagBiz.NormalizeTags(newObject.Tags); newObject.CustomFields = JsonUtil.CompactJson(newObject.CustomFields); await ct.CustomerServiceRequest.AddAsync(newObject); await ct.SaveChangesAsync(); await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct); await SearchIndexAsync(newObject, true); await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null); await HandlePotentialNotificationEvent(AyaEvent.Created, newObject); return newObject; } } // //////////////////////////////////////////////////////////////////////////////////////////////// // //DUPLICATE // // // internal async Task DuplicateAsync(long id) // { // CustomerServiceRequest dbObject = await GetAsync(id, false); // if (dbObject == null) // { // AddError(ApiErrorCode.NOT_FOUND, "id"); // return null; // } // CustomerServiceRequest newObject = new CustomerServiceRequest(); // CopyObject.Copy(dbObject, newObject, "Wiki"); // string newUniqueName = string.Empty; // bool NotUnique = true; // long l = 1; // do // { // newUniqueName = Util.StringUtil.UniqueNameBuilder(dbObject.Name, l++, 255); // NotUnique = await ct.CustomerServiceRequest.AnyAsync(m => m.Name == newUniqueName); // } while (NotUnique); // newObject.Name = newUniqueName; // newObject.Id = 0; // newObject.Concurrency = 0; // await ct.CustomerServiceRequest.AddAsync(newObject); // await ct.SaveChangesAsync(); // await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct); // await SearchIndexAsync(newObject, true); // await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, newObject.Tags, null); // await HandlePotentialNotificationEvent(AyaEvent.Created, newObject); // return newObject; // } //////////////////////////////////////////////////////////////////////////////////////////////// //GET // internal async Task GetAsync(long id, bool logTheGetEvent = true) { var ret = await ct.CustomerServiceRequest.AsNoTracking().SingleOrDefaultAsync(m => m.Id == id); if (logTheGetEvent && ret != null) await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, AyaEvent.Retrieved), ct); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////// //UPDATE // internal async Task PutAsync(CustomerServiceRequest putObject) { var dbObject = await GetAsync(putObject.Id, false); if (dbObject == null) { AddError(ApiErrorCode.NOT_FOUND, "id"); return null; } putObject.Tags = TagBiz.NormalizeTags(putObject.Tags); putObject.CustomFields = JsonUtil.CompactJson(putObject.CustomFields); 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, dbObject.Id, BizType, AyaEvent.Modified), ct); await SearchIndexAsync(putObject, false); await TagBiz.ProcessUpdateTagsInRepositoryAsync(ct, putObject.Tags, dbObject.Tags); await HandlePotentialNotificationEvent(AyaEvent.Modified, putObject, dbObject); return dbObject; } //////////////////////////////////////////////////////////////////////////////////////////////// //DELETE // internal async Task DeleteAsync(long id) { using (var transaction = await ct.Database.BeginTransactionAsync()) { try { CustomerServiceRequest dbObject = await GetAsync(id, false); if (dbObject == null) { AddError(ApiErrorCode.NOT_FOUND); return false; } ValidateCanDelete(dbObject); if (HasErrors) return false; if (HasErrors) return false; ct.CustomerServiceRequest.Remove(dbObject); await ct.SaveChangesAsync(); //Log event await EventLogProcessor.DeleteObjectLogAsync(UserId, BizType, dbObject.Id, dbObject.Name, 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(AyaEvent.Deleted, dbObject); } catch { //Just re-throw for now, let exception handler deal, but in future may want to deal with this more here throw; } return true; } } //////////////////////////////////////////////////////////////////////////////////////////////// //ACCEPT // internal async Task AcceptAsync(long csrId, long workorderId) //MIGRATE_OUTSTANDING waiting for workorder to be completed or at least have a customerid which it currently doesn't { var dbObject = await GetAsync(csrId, false); if (dbObject == null) { AddError(ApiErrorCode.NOT_FOUND, "id"); return null; } throw new System.NotImplementedException("//MIGRATE_OUTSTANDING CustomerServiceRequestBiz::AcceptAsync - awaiting workorder completion "); // WorkOrder w=null; //if (workorderId==0){WorkOrderBiz.GenerateWorkOrder()} //this is how it would work in theory } //////////////////////////////////////////////////////////////////////////////////////////////// //REJECT // internal async Task RejectAsync(long csrId) { var dbObject = await GetAsync(csrId, false); if (dbObject == null) { AddError(ApiErrorCode.NOT_FOUND, "id"); return null; } //Nothing to validate as it just came from the db and rejecting doesn't require validation dbObject.Status = CustomerServiceRequestStatus.Declined; await PutAsync(dbObject); return dbObject; } //////////////////////////////////////////////////////////////////////////////////////////////// //SEARCH // private async Task SearchIndexAsync(CustomerServiceRequest 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) { var obj = await GetAsync(id, false); var SearchParams = new Search.SearchIndexProcessObjectParameters(); DigestSearchText(obj, SearchParams); return SearchParams; } public void DigestSearchText(CustomerServiceRequest obj, Search.SearchIndexProcessObjectParameters searchParams) { if (obj != null) searchParams.AddText(obj.Notes) .AddText(obj.Name) .AddText(obj.Wiki) .AddText(obj.Tags) .AddText(obj.CustomerReferenceNumber) .AddCustomFields(obj.CustomFields); } //////////////////////////////////////////////////////////////////////////////////////////////// //VALIDATION // private async Task ValidateAsync(CustomerServiceRequest proposedObj, CustomerServiceRequest currentObj) { bool isNew = currentObj == null; if (!isNew) { //if it was already accepted then it must stay accepted if (currentObj.Status == CustomerServiceRequestStatus.Accepted && proposedObj.Status != CustomerServiceRequestStatus.Accepted) { AddError(ApiErrorCode.INVALID_OPERATION, "generalerror", "Already accepted, can't be changed");//User should never see this but an api user might as it's a form locked thing } } //Name required BUT NOT REQUIRED TO BE UNIQUE if (string.IsNullOrWhiteSpace(proposedObj.Name)) AddError(ApiErrorCode.VALIDATION_REQUIRED, "name"); //if unit, it must both exist and belong to this CustomerId if (proposedObj.UnitId != null) { if (!await ct.Unit.AnyAsync(z => z.Id == proposedObj.UnitId && z.CustomerId == proposedObj.CustomerId)) { AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "unitId", "Unit is not valid, it must exist and belong to the Customer");//no need to localize, this is for api users only as the UI should never allow this } } //Any form customizations to validate? var FormCustomization = await ct.FormCustom.AsNoTracking().SingleOrDefaultAsync(x => x.FormKey == AyaType.CustomerServiceRequest.ToString()); if (FormCustomization != null) { //Yeppers, do the validation, there are two, the custom fields and the regular fields that might be set to required //validate users choices for required non custom fields RequiredFieldsValidator.Validate(this, FormCustomization, proposedObj); //validate custom fields CustomFieldsValidator.Validate(this, FormCustomization, proposedObj.CustomFields); } } private void ValidateCanDelete(CustomerServiceRequest inObj) { //whatever needs to be check to delete this object //can't delete if it's accepted } //////////////////////////////////////////////////////////////////////////////////////////////// //REPORTING // public async Task GetReportData(DataListSelectedRequest dataListSelectedRequest) { var idList = dataListSelectedRequest.SelectedRowIds; JArray ReportData = new JArray(); while (idList.Any()) { var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE); idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray(); //query for this batch, comes back in db natural order unfortunately var batchResults = await ct.CustomerServiceRequest.AsNoTracking().Where(z => batch.Contains(z.Id)).ToArrayAsync(); //order the results back into original var orderedList = from id in batch join z in batchResults on id equals z.Id select z; //cache frequent viz data //usertypes var CustomerServiceRequestStatusEnumList = await AyaNova.Api.Controllers.EnumListController.GetEnumList( StringUtil.TrimTypeName(typeof(CustomerServiceRequestStatus).ToString()), UserTranslationId, CurrentUserRoles); var CustomerServiceRequestPriorityEnumList = await AyaNova.Api.Controllers.EnumListController.GetEnumList( StringUtil.TrimTypeName(typeof(CustomerServiceRequestPriority).ToString()), UserTranslationId, CurrentUserRoles); foreach (CustomerServiceRequest w in orderedList) { await PopulateVizFields(w, CustomerServiceRequestStatusEnumList, CustomerServiceRequestPriorityEnumList); var jo = JObject.FromObject(w); if (!JsonUtil.JTokenIsNullOrEmpty(jo["CustomFields"])) jo["CustomFields"] = JObject.Parse((string)jo["CustomFields"]); ReportData.Add(jo); } } return ReportData; } //populate viz fields from provided object private async Task PopulateVizFields(CustomerServiceRequest o, List customerServiceRequestStatusEnumList, List customerServiceRequestPriorityEnumList) { if (o.UnitId != null) o.UnitViz = await ct.Unit.AsNoTracking().Where(x => x.Id == o.UnitId).Select(x => x.Serial).FirstOrDefaultAsync(); o.CustomerViz = await ct.Customer.AsNoTracking().Where(x => x.Id == o.CustomerId).Select(x => x.Name).FirstOrDefaultAsync(); //MIGRATE_OUTSTANDING routine to get wo id from the WorkorderItemId o.WorkorderItemViz = "MIGRATE_OUTSTANDING woitem display value"; // if (o.WorkorderItemId != null) // o.WorkorderItemViz = await ct.WorkorderItem.AsNoTracking().Where(x=>x.Id==o.WorkorderItemId).Select(x => x.Name).FirstOrDefaultAsync(); o.RequestedByUserViz = await ct.User.AsNoTracking().Where(x => x.Id == o.RequestedByUserId).Select(x => x.Name).FirstOrDefaultAsync(); o.StatusViz = customerServiceRequestStatusEnumList.Where(x => x.Id == (long)o.Status).Select(x => x.Name).First(); o.PriorityViz = customerServiceRequestPriorityEnumList.Where(x => x.Id == (long)o.Priority).Select(x => x.Name).First(); } //////////////////////////////////////////////////////////////////////////////////////////////// // IMPORT EXPORT // public async Task GetExportData(DataListSelectedRequest dataListSelectedRequest) { //for now just re-use the report data code //this may turn out to be the pattern for most biz object types but keeping it seperate allows for custom usage from time to time return await GetReportData(dataListSelectedRequest); } public async Task> ImportData(JArray ja) { List ImportResult = new List(); string ImportTag = $"imported-{FileUtil.GetSafeDateFileName()}"; var jsset = JsonSerializer.CreateDefault(new JsonSerializerSettings { ContractResolver = new AyaNova.Util.JsonUtil.ShouldSerializeContractResolver(new string[] { "Concurrency", "Id", "CustomFields" }) }); foreach (JObject j in ja) { var w = j.ToObject(jsset); if (j["CustomFields"] != null) w.CustomFields = j["CustomFields"].ToString(); w.Tags.Add(ImportTag);//so user can find them all and revert later if necessary var res = await CreateAsync(w); if (res == null) { ImportResult.Add($"* {w.Name} - {this.GetErrorsAsString()}"); this.ClearErrors(); } else { ImportResult.Add($"{w.Name} - ok"); } } return ImportResult; } //////////////////////////////////////////////////////////////////////////////////////////////// //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($"CustomerServiceRequestBiz.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.CustomerServiceRequest.AsNoTracking().Select(z => z.Id).ToListAsync(); bool SaveIt = false; foreach (long id in idList) { try { SaveIt = false; ClearErrors(); CustomerServiceRequest 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++; } } } catch (Exception ex) { await JobsBiz.LogJobAsync(job.GId, $"LT:Errors id({id})"); await JobsBiz.LogJobAsync(job.GId, ExceptionUtil.ExtractAllExceptionMessages(ex)); } } 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(AyaEvent ayaEvent, ICoreBizObjectModel proposedObj, ICoreBizObjectModel currentObj = null) { ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger(); if (ServerBootConfig.SEEDING) return; log.LogDebug($"HandlePotentialNotificationEvent processing: [AyaType:{this.BizType}, AyaEvent:{ayaEvent}]"); bool isNew = currentObj == null; //STANDARD EVENTS FOR ALL OBJECTS await NotifyEventHelper.ProcessStandardObjectEvents(ayaEvent, proposedObj, ct); //SPECIFIC EVENTS FOR THIS OBJECT var o = (CustomerServiceRequest)proposedObj; //CSR ACCEPTED { var subs = await ct.NotifySubscription.Where(z => z.EventType == NotifyEventType.CSRAccepted).ToListAsync(); string SourceName = string.Empty; if (subs.Count > 0) SourceName = BizObjectNameFetcherDirect.Name(BizType, o.Id, ct); foreach (var sub in subs) { //not for inactive users if (!await UserBiz.UserIsActive(sub.UserId)) continue; NotifyEvent n = new NotifyEvent() { EventType = NotifyEventType.CSRAccepted, UserId = sub.UserId, AyaType = BizType, ObjectId = o.Id, NotifySubscriptionId = sub.Id, Name = SourceName }; await ct.NotifyEvent.AddAsync(n); log.LogDebug($"Adding NotifyEvent: [{n.ToString()}]"); await ct.SaveChangesAsync(); } } //CSR REJECTED { var subs = await ct.NotifySubscription.Where(z => z.EventType == NotifyEventType.CSRRejected).ToListAsync(); string SourceName = string.Empty; if (subs.Count > 0) SourceName = BizObjectNameFetcherDirect.Name(BizType, o.Id, ct); foreach (var sub in subs) { //not for inactive users if (!await UserBiz.UserIsActive(sub.UserId)) continue; NotifyEvent n = new NotifyEvent() { EventType = NotifyEventType.CSRRejected, UserId = sub.UserId, AyaType = BizType, ObjectId = o.Id, NotifySubscriptionId = sub.Id, Name = SourceName }; await ct.NotifyEvent.AddAsync(n); log.LogDebug($"Adding NotifyEvent: [{n.ToString()}]"); await ct.SaveChangesAsync(); } } }//end of process notifications ///////////////////////////////////////////////////////////////////// }//eoc }//eons