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;
}
}
}
The InsertFormDataCommandHandler class is a part of a larger application that handles the insertion and updating of form data within a document management system. This handler is designed to work with the MediatR library, which is used for handling commands and queries in a decoupled manner. Below is a detailed breakdown of the key components and functionalities of this class:
Dependencies and Constructor
The class depends on several services and interfaces, which are injected via the constructor. These include:
Database Context (IApplicationDbContext): For interacting with the database.
PDF and Workflow Services: For generating PDFs and managing workflows.
User and Permission Services: For handling user authentication and permissions.
Mediator (IMediator): For sending commands and queries.
Logger (ILogger): For logging debug information.
Background Job Runner (IBackgroundJobRunner): For running background jobs.
Handle Method
The Handle method is the core method that processes the InsertFormDataCommand. It performs the following steps:
Logging and Validation:
Logs the request details.
Retrieves the document from the database.
Checks if the document exists and throws a NotFoundException if it doesn't.
Workflow Status Check:
Checks if the document is completed by examining the workflow status.
Throws a ValidationException if the document is already completed.
Permission Check:
Checks if the current user has permission to update the document.
Throws an AccessDeniedException if the user does not have the necessary permissions.
Data Processing:
Parses the form data and updates the document's form data.
Resolves internal form indexes and adds them to the document.
Logs the update operation.
Document Status Handling:
If the document is in draft status, it updates the document and initiates the workflow.
If the document is not in draft status, it generates a PDF, updates the document, and sends notifications if editable fields are updated.
Returning the Result:
Returns a InsertFormDataCommandVm containing the application ID and background process status.
Helper Methods
InitiateWorkflow: Runs a background job to initiate the workflow.
SetKeysFromEditableFields: Recursively sets keys from editable fields in the form data.
FindTitleField: Finds the title field in the form data.
Key Points
Error Handling: The method includes error handling for scenarios like document not found, access denied, and validation errors.
Logging: Extensive logging is used to track the flow of the method and capture important information.
Background Jobs: Background jobs are used for initiating workflows, ensuring that the main thread is not blocked.
Permissions and Security: The method checks user permissions before allowing updates, ensuring that only authorized users can modify the document.
Example Usage
To use this handler, you would typically send a InsertFormDataCommand to the IMediator instance, which would then invoke the Handle method of this handler.
csharp
var command = new InsertFormDataCommand
{
DocumentId = 123,
Data = "{\"key1\": \"value1\", \"key2\": \"value2\"}",
UpdateEditableFields = true
};
var result = await _mediator.Send(command);
This command would be processed by the InsertFormDataCommandHandler, and the result would be returned as a InsertFormDataCommandVm.
Conclusion
The InsertFormDataCommandHandler is a well-structured and robust handler that manages the insertion and updating of form data within a document management system. It leverages various services and libraries to ensure that the operation is performed efficiently, securely, and with proper logging and error handling.