using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Hangfire;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.DynamicLinq;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using PaperPlate.Application.Common.Exceptions;
using PaperPlate.Application.Common.Interfaces;
using PaperPlate.Application.Common.Models;
using PaperPlate.Application.Notifications.Commands.SendGeneralNotification;
using PaperPlate.Domain.Entities;
using PaperPlate.Domain.Enums;
public InsertFormDataCommandHandler(
IApplicationDbContext context,
IPdfFileBuilder fileBuilder,
IWorkflowService workflowService,
IBGWorkflowService bGWorkflowService,
ICurrentUserService currentUserService,
IPdfGenerationService pdfGenerationService,
IDateTime dateTime,
IIdentityService identityService,
IPermissionService permissionService,
IAutoIncrementService autoincrementService,
IIndexResolverService indexResolverService,
IDynamicQueueServiceFactory dynamicQueueServiceFactory,
IWfQueueServiceFactory queueServiceFactory,
IMediator mediator,
ILogger<InsertFormDataCommandHandler> logger,
IBackgroundJobRunner bgJobRunner)
{
_context = context;
_fileBuilder = fileBuilder;
_workflowService = workflowService;
_bGWorkflowService = bGWorkflowService;
_currentUserService = currentUserService;
_pdfGenerationService = pdfGenerationService;
_dateTime = dateTime;
_identityService = identityService;
_permissionService = permissionService;
_autoincrementService = autoincrementService;
_indexResolverService = indexResolverService;
_dynamicQueueServiceFactory = dynamicQueueServiceFactory;
_queueServiceFactory = queueServiceFactory;
_mediator = mediator;
_logger = logger;
_bgJobRunner = bgJobRunner;
}
public async Task<InsertFormDataCommandVm> Handle(InsertFormDataCommand request, CancellationToken ctx)
{
_logger.LogDebug("{DocumentId}, {@request}", request.DocumentId, request);
var document = await _context.ApplicationData.AsNoTracking()
.Include(x => x.AppTemplate)
.FirstOrDefaultAsync(x => x.ApplicationDataId == request.DocumentId, ctx);
if (document is null)
{
_logger.LogDebug("{DocumentId} not found", request.DocumentId);
throw new NotFoundException(nameof(ApplicationData), request.DocumentId);
}
var isCompletedDocument = false;
long? workflowId = null;
var applicationWfList = await _context.ApplicationWf.AsNoTracking().Where(x => x.ApplicationDataId == request.DocumentId).ToListAsync();
if (applicationWfList.Any())
{
workflowId = applicationWfList
.FirstOrDefault()
.ApplicationWfId;
}
if (workflowId != null)
{
decimal completedLevelId = await _context
.ApplicationWfQueue.AsNoTracking()
.Where(awfq => awfq.ApplicationWfId == workflowId &&
awfq.Status == WorkflowStatus
.Completed
.ToString())
.OrderByDescending(awfq => awfq.Level)
.Select(awfq => awfq.Level)
.FirstOrDefaultAsync(ctx);
//Checking if the document is completed or not
isCompletedDocument = completedLevelId != default &&
!await _context.ApplicationWfQueue.AsNoTracking()
.AnyAsync(awfq => awfq.ApplicationWfId == workflowId
&& awfq.Level > completedLevelId
&& awfq.Status != WorkflowStatus.Completed.ToString());
}
if (isCompletedDocument)
{
throw new ValidationException("Cannot edit completed Form.");
}
if (document.CreatedBy != _currentUserService.UserId && !request.UpdateEditableFields)
{
bool valid = await _permissionService.HasApplicationPermissionAsync(document, ApplicationDataPermissionType.Update);
if (!valid)
{
_logger.LogDebug("User {UserId} does not have permission to update document {DocumentId}",
_currentUserService.UserId, request.DocumentId);
throw new AccessDeniedException();
}
}
var entities = await _context.WfTemplateDynamicQueue
.Where(x => x.WfTemplateId == document.AppTemplate.WfTemplateId)
.Select(x => new { x.IsGroup, x.EntityId })
.ToListAsync(ctx);
string currentUserName = await _identityService.GetUserNameAsync(_currentUserService.UserId);
var template = await _context.AppTemplate.AsNoTracking()
.Where(c => c.AppTemplateId == document.AppTemplateId)
.FirstOrDefaultAsync();
string title = document.TemplateName;
var templateTitle = FindTitleField(request.Data, template.TitleField) ?? template.TitleField;
if (!string.IsNullOrEmpty(request.Data))
{
if (document.Status == nameof(WorkflowStatus.Draft))
{
document.Title = !string.IsNullOrEmpty(templateTitle) ? templateTitle : document.Title;
}
if (request.UpdateEditableFields)
{
JObject json = JObject.Parse(document.AppForm);
SetKeysFromEditableFields(json["components"].ToArray());
JObject data = JObject.Parse(document.AppFormdata);
JObject dataFromRequest = JObject.Parse(request.Data);
keys.ForEach(key =>
{
if (dataFromRequest.ContainsKey(key))
{
data[key] = dataFromRequest[key];//.ToString();
}
});
document.AppFormdata = data.ToString();
}
else
{
JObject formDataObject = JObject.Parse(request.Data); // Using Newtonsoft.Json.Linq.JObject for parsing
formDataObject["karyaflowStatus"] = "Completed";
document.AppFormdata = formDataObject.ToString();
}
var formIndexes = await
_indexResolverService.ResolveInternalFormIndexes(document.ApplicationDataId, template.IndexList, document.AppFormdata);
foreach (var item in formIndexes)
{
document.ApplicationDataIndexList.Add(item);
}
}
//Log
ApplicationDataLog applog = new ApplicationDataLog
{
Type = LogType.Info,
Description = string.Format("Document {0} is updated by the userId {1}.",
document.ApplicationDataId,
_currentUserService.UserId),
Date = _dateTime.Now,
User = currentUserName
};
document.ApplicationDataLogList.Add(applog);
_logger.LogDebug("Document {DocumentId} updated by the userId {UserId}, Log {@Log}",
request.DocumentId, _currentUserService.UserId, applog);
if (document.Status == nameof(WorkflowStatus.Draft))
{
_context.ApplicationData.Update(document);
await _context.SaveChangesAsync(ctx);
if (template.BackgroundProcess)
{
//Initiate
BackgroundJob.Enqueue(() => InitiateWorkflow(
request.DocumentId,
_currentUserService.UserId,
_currentUserService.UserToken
));
}
else
{
await _bGWorkflowService.InitiateWorkflow(request.DocumentId, _currentUserService.UserId, ctx);
}
}
else
{
if (!string.IsNullOrEmpty(document.OutputUrl))
{
var pdf = await _pdfGenerationService.GeneratePdf(request.DocumentId, _currentUserService.UserId, true, ctx);
document.Data = pdf.Data;
await _workflowService.RemoveSignatures(request.DocumentId, ctx);
}
_context.ApplicationData.Update(document);
await _context.SaveChangesAsync(ctx);
if (request.UpdateEditableFields)
{
IWfQueueService queue = await _queueServiceFactory.CreateWfQueueServiceAsync(request.DocumentId, ctx);
List<string> userIds = queue.GetAll().Where(x => x.Status.Equals("completed", StringComparison.InvariantCultureIgnoreCase))
.Select(x => x.UserId)
.ToList();
string userName = await _identityService.GetUserNameAsync(_currentUserService.UserId);
for (int i = 0; i < userIds.Count; i++)
{
var cmd = new SendGeneralNotificationCommand()
{
Model = new GeneralNotificationModel()
{
UserId = userIds[i],
Category = "Information",
Title = "Editable fields updated sucessfully.",
Icon = "info",
Url = $"/applications/view/{request.DocumentId}",
Date = _dateTime.Now,
Description = "The editable fields are updated sucessfully by the user " + userName,
IsRead = false,
Priority = 2,
}
};
await _mediator.Send(cmd, ctx);
}
}
}
return new InsertFormDataCommandVm
{
ApplicationId = document.ApplicationDataId,
BackgroundProcess = template.BackgroundProcess
};
}
public async Task InitiateWorkflow(long appDataId, string userId, string userToken)
{
await _bgJobRunner.Run(
userId,
userToken,
(IBGWorkflowService wf) => wf.InitiateWorkflow(appDataId, userId, CancellationToken.None)
);
}
private void SetKeysFromEditableFields(JToken[] components)
{
foreach (var comp in components)
{
JToken isEditable = comp["attributes"] != null ? comp["attributes"]["isEditable"] : null;
if (isEditable != null && isEditable.ToString() == "true")
{
keys.Add(comp["key"].ToString());
}
if (comp["components"] != null && comp["components"].ToArray().Length > 0)
{
this.SetKeysFromEditableFields(comp["components"].ToArray());
}
if (comp["columns"] != null && comp["columns"].ToArray().Length > 0)
{
this.SetKeysFromEditableFields(comp["columns"].ToArray());
}
}
}
private string FindTitleField(string formData, string key)
{
if (string.IsNullOrEmpty(key?.Trim()))
{
return string.Empty;
}
JToken data = JToken.Parse(formData ?? "{}");
return data?.SelectToken($"..{key}")?.Value<string>() ?? string.Empty;
}
}
}
This is a complex command handler for inserting/updating form data in a workflow system. Here are my observations and suggestions for improvement:
Major Issues & Improvements
1. Too Many Dependencies (15+ constructor parameters)
This violates the Single Responsibility Principle. Consider using:
Facade Pattern: Group related services
Aggregate Services: Create higher-level services that encapsulate related functionality
csharp
public class WorkflowServices
{
public IWorkflowService WorkflowService { get; set; }
public IBGWorkflowService BGWorkflowService { get; set; }
public IWfQueueServiceFactory QueueServiceFactory { get; set; }
// ... other workflow-related services
}
2. Method Complexity
The Handle method is too long (~200 lines). Break it down into smaller, focused methods:
csharp
public async Task<InsertFormDataCommandVm> Handle(InsertFormDataCommand request, CancellationToken ctx)
{
var document = await GetDocumentWithValidation(request.DocumentId, ctx);
await ValidateDocumentEditPermissions(document, request, ctx);
var isCompleted = await IsDocumentCompleted(request.DocumentId, ctx);
if (isCompleted)
throw new ValidationException("Cannot edit completed Form.");
await UpdateDocumentData(document, request, ctx);
await ProcessWorkflowIfNeeded(document, request, ctx);
return CreateResponse(document);
}
3. Database Query Optimization
Multiple separate queries could be combined:
csharp
// Instead of multiple queries, use a single query with projections
var documentData = await _context.ApplicationData
.Where(x => x.ApplicationDataId == request.DocumentId)
.Select(x => new
{
Document = x,
Template = x.AppTemplate,
WorkflowQueues = x.ApplicationWfList
.SelectMany(wf => wf.ApplicationWfQueueList)
.ToList()
})
.FirstOrDefaultAsync(ctx);
4. Potential Null Reference Issues
csharp
// Current code doesn't check if template is null
var template = await _context.AppTemplate.AsNoTracking()
.Where(c => c.AppTemplateId == document.AppTemplateId)
.FirstOrDefaultAsync();
// Should be:
var template = await _context.AppTemplate.AsNoTracking()
.Where(c => c.AppTemplateId == document.AppTemplateId)
.FirstOrDefaultAsync(ctx)
?? throw new NotFoundException(nameof(AppTemplate), document.AppTemplateId);
5. State Management Issue
The keys field is a class-level list that's modified during execution. This can cause issues with concurrent requests:
csharp
// Instead of class field:
private List<string> keys = new List<string>();
// Use local variable or return from method:
private List<string> ExtractEditableFieldKeys(JToken[] components)
{
var keys = new List<string>();
ExtractKeysRecursively(components, keys);
return keys;
}
6. Public Method Should Be Private
csharp
// This should be private or moved to a service
private async Task InitiateWorkflow(long appDataId, string userId, string userToken)