Files
raven/server/AyaNova/biz/NotifyEventProcessor.cs
2020-07-16 23:44:37 +00:00

220 lines
11 KiB
C#

using System;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using AyaNova.Util;
using AyaNova.Models;
//using System.Diagnostics;
namespace AyaNova.Biz
{
//This class handles word breaking, processing keywords and searching for results
internal static class NotifyEventProcessor
{
private static ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger("NotifyEventProcessor");
//Add operations message
internal static async Task AddOpsProblemEvent(string message, Exception ex = null)
{
if (string.IsNullOrWhiteSpace(message) && ex == null)
return;
//Log as a backup in case there is no one to notify and also for the record and support
if (ex != null)
{
log.LogError(ex, $"Ops problem notification: \"{message}\"");
message += $"\nException error: {ExceptionUtil.ExtractAllExceptionMessages(ex)}";
}
else
log.LogWarning($"Ops problem notification: \"{message}\"");
await AddGeneralNotifyEvent(NotifyEventType.ServerOperationsProblem, message);
}
//This handles general notification events not requiring a decision or tied to an object that are basically just a immediate message to the user
//e.g. ops problems, DefaultNotification, NotifyHealthCheck etc
//optional user id to send directly to them
internal static async Task AddGeneralNotifyEvent(NotifyEventType eventType, string message, long userId = 0)
{
log.LogTrace($"AddGeneralNotifyEvent processing: [type:{eventType}, userId:{userId}, message:{message}]");
#if (DEBUG)
switch (eventType)
{
case NotifyEventType.BackupStatus:
case NotifyEventType.DefaultNotification:
case NotifyEventType.NotifyHealthCheck:
case NotifyEventType.ServerOperationsProblem:
break;
default://this will likely be a development error, not a production error so no need to log etc
throw (new System.NotSupportedException($"NotifyEventProcessor:AddGeneralNotifyEvent - Type of event {eventType} is unexpected and not supported"));
}
if (eventType != NotifyEventType.DefaultNotification && userId != 0)
{
throw (new System.NotSupportedException($"NotifyEventProcessor:AddGeneralNotifyEvent - event {eventType} was specified with user id {userId} which is unexpected and not supported"));
}
#endif
try
{
using (AyContext ct = AyaNova.Util.ServiceProviderProvider.DBContext)
{
//Default notification goes to a specific user only
//no need to consult subscriptions
if (eventType == NotifyEventType.DefaultNotification)
{
if (userId == 0)
{
//this will likely be a development error, not a production error so no need to log etc
throw new System.ArgumentException("NotifyEventProcessor:AddGeneralNotifyEvent: DefaultNotification requires a user id but none was specified");
}
NotifyEvent n = new NotifyEvent() { EventType = eventType, UserId = userId, Message = message, SubscriptionId = 0 };
await ct.NotifyEvent.AddAsync(n);
await ct.SaveChangesAsync();
return;
}
//check subscriptions for event and send accordingly
var subs = ct.NotifySubscription.Where(z => z.EventType == eventType)
}
}
catch (Exception ex)
{
log.LogError(ex, $"Error adding general notify event [type:{eventType}, userId:{userId}, message:{message}]");
}
}//eom
//This is told about an event and then determines if there are any subscriptions related to that event and proceses them accordingly
//todo: this should take some kind of general event type like the AyaEvent types (i.e. which CRUD operation is in effect if relevant)
//and also a biz object before and after or just before if not a change and also a AyaType
//then *this* code will go through and look for subscriptions related to that event
//this way the biz object code can be "dumb" about notifications in general and just let this code handle it as needed
//will iterate the subscriptions and see if any apply here
internal static async Task HandlePotentialNotificationEvent(AyaType ayaType, AyaEvent ayaEvent, BizObject newObject, BizObject currentObject, )
{
log.LogTrace($"UpsertEvent processing: [{ev.ToString()}]");
try
{
var HasTags = inTags != null && inTags.Count > 0;
using (AyContext ct = AyaNova.Util.ServiceProviderProvider.DBContext)
{
//find all the Notification subscription subs that are relevant
//this first query ensures that the equality matching conditions of AyaType and EventType and idValue are matched leaving only more complex matches to rectify below
var subs = await ct.NotifySubscription.AsNoTracking().Where(z => z.EventType == ev.EventType && z.AyaType == ev.AyaType && z.IdValue == ev.IdValue).ToListAsync();
foreach (var sub in subs)
{
//CONDITION CHECK Tags condition
if (sub.Tags.Count > 0)
{
if (!HasTags)
continue;//not a match, this sub needs tags and we don't have any
//bool existsCheck = list1.All(x => list2.Any(y => x.SupplierId == y.SupplierId));
//would tell you if all of list1's items are in list2.
if (!sub.Tags.All(z => inTags.Any(x => x == z)))
continue;
}
//CONDITION CHECK Decimal value, so far only for "The Andy" so the only condition is that the event value be greater than or equal to subscription setting
if (ev.EventType == NotifyEventType.WorkorderTotalExceedsThreshold && ev.DecValue < sub.DecValue)
continue;
//Here ready for delivery
//HANDLE RELATED INDIRECT EVENTS AND CLEANUP
//some event types create related events here automatically (e.g. WorkorderStatusChange in turn will trigger workorderstatusage if subbed here)
//Deleting an object or changing status etc will affect other events in turn so clean up for them here
switch (ev.EventType)
{
case NotifyEventType.ObjectDeleted:
{
//object is deleted so remove any other events pending for it
//current working concept is there is no reason to keep any event related to a freshly deleted object
var deleteEventList = await ct.NotifyEvent.Where(z => z.ObjectId == ev.ObjectId && z.AyaType == ev.AyaType).ToListAsync();
ct.NotifyEvent.RemoveRange(deleteEventList);
await ct.SaveChangesAsync();
}
break;
case NotifyEventType.WorkorderStatusChange:
{
//Workorder status changed so remove any other prior workorderstatuschanged events and
//remove any prior workorderstatusAge events for this object id
var deleteEventList = await ct.NotifyEvent.Where(z => z.ObjectId == ev.ObjectId && z.AyaType == ev.AyaType && ev.EventType == NotifyEventType.WorkorderStatusChange).ToListAsync();
ct.NotifyEvent.RemoveRange(deleteEventList);
await ct.SaveChangesAsync();
}
break;
case NotifyEventType.WorkorderStatusAge://delete any workorder status age ones because there is potentially a new status invalidating the old status
case NotifyEventType.QuoteStatusAge:
//Delete any existing ones
var StaleAgedEvents = await ct.NotifyEvent.Where(z => z.EventType == ev.EventType && z.ObjectId == ev.ObjectId && z.AyaType == ev.AyaType).ToListAsync();
break;
}
//AgeValue refresh?
//Age based ones need to replace any prior existing age based ones made for the same object as they are the only ones that can sit in the queue for any length of time
//and become invalidated (i.e. deadman type deliveries that sb removed if no longer applicable e.g. WorkorderStatusAge)
switch (ev.EventType)
{
case NotifyEventType.ObjectAge://this is set on creation so it will never change unless the object is deleted
case NotifyEventType.WorkorderStatusAge://delete any workorder status age ones because there is potentially a new status invalidating the old status
case NotifyEventType.QuoteStatusAge:
//Delete any existing ones
var StaleAgedEvents = await ct.NotifyEvent.Where(z => z.EventType == ev.EventType && z.ObjectId == ev.ObjectId && z.AyaType == ev.AyaType).ToListAsync();
break;
}
//Here we know the sub matches the event and passes all the conditions so set the deliver date if necessary and save the NotifyEvent here
//todo: create message here (delivery thing?)
//todo: Attach report here or is that a delivery thing (delivery thing)
}
}
}
catch (Exception ex)
{
log.LogError(ex, $"Error adding notification event: [{ev.ToString()}]");
}
finally
{
log.LogTrace($"Notify event processed: [{ev.ToString()}]");
}
}
}//eoc
}//eons