Add history inserts, add controllers

This commit is contained in:
Jonathan Jenne 2023-11-02 16:30:57 +01:00
parent 3f4f4681b5
commit 47d02aefee
14 changed files with 428 additions and 135 deletions

View File

@ -8,12 +8,14 @@ Public Class EnvelopeModel
Private ReadOnly UserModel As UserModel
Private ReadOnly ReceiverModel As ReceiverModel
Private ReadOnly DocumentModel As DocumentModel
Public Sub New(pState As State)
MyBase.New(pState)
UserModel = New UserModel(pState)
ReceiverModel = New ReceiverModel(pState)
DocumentModel = New DocumentModel(pState)
End Sub
Private Function ToEnvelope(pRow As DataRow) As Envelope
@ -32,6 +34,7 @@ Public Class EnvelopeModel
oEnvelope.User = UserModel.SelectUser(oEnvelope.UserId)
oEnvelope.Receivers = ReceiverModel.ListEnvelopeReceivers(oEnvelope.Id)
oEnvelope.Documents = DocumentModel.List(oEnvelope.Id)
Return oEnvelope
End Function

View File

@ -0,0 +1,90 @@
using DigitalData.Modules.Logging;
using EnvelopeGenerator.Common;
using EnvelopeGenerator.Web.Services;
using Microsoft.AspNetCore.Mvc;
using System.Reflection.Metadata;
using static EnvelopeGenerator.Web.Handler.FileHandler;
namespace EnvelopeGenerator.Web.Controllers
{
public class DocumentController : Controller
{
private readonly DatabaseService database;
private readonly LoggingService logging;
private readonly Logger logger;
private readonly ApiService api;
public DocumentController(DatabaseService database, LoggingService logging, ApiService api)
{
this.database = database;
this.logging = logging;
this.logger = logging.LogConfig.GetLoggerFor(GetType().Name);
this.api = api;
}
[HttpGet]
[Route("api/document/{envelopeKey}")]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> Get(string envelopeKey)
{
try
{
logger.Info("Handling file download.");
EnvelopeResponse r = api.EnsureValidEnvelopeKey(envelopeKey);
var Request = ControllerContext.HttpContext.Request;
var document = api.GetDocument(Request, envelopeKey);
// Load the document from disk
var bytes = await System.IO.File.ReadAllBytesAsync(document.Filepath);
logger.Info("Serving file, size: [{0}]", bytes.Length);
// Return the document as bytes
return File(bytes, "application/octet-stream");
}
catch (Exception e)
{
// Better error handling & reporting
logger.Error(e);
return Problem(
statusCode: 500,
detail: e.Message,
type: ErrorType.ServerError.ToString());
}
}
[HttpPost]
[Route("api/document/{envelopeKey}")]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> Update(string envelopeKey)
{
try
{
logger.Info("Handling file update.");
api.EnsureValidEnvelopeKey(envelopeKey);
var Request = ControllerContext.HttpContext.Request;
var document = api.GetDocument(Request, envelopeKey);
if (!await api.UpdateDocument(Request.Body, document.Filepath))
{
throw new IOException("Document could not be saved to disk!");
}
return Ok();
}
catch (Exception e)
{
// Better error handling & reporting
logger.Error(e);
return Problem(
statusCode: 500,
detail: e.Message,
type: ErrorType.ServerError.ToString());
}
}
}
}

View File

@ -0,0 +1,98 @@
using EnvelopeGenerator.Common;
using EnvelopeGenerator.Web.Services;
using Microsoft.AspNetCore.Mvc;
using NLog;
using static EnvelopeGenerator.Web.Handler.FileHandler;
namespace EnvelopeGenerator.Web.Controllers
{
public class EnvelopeController : Controller
{
private readonly DatabaseService database;
private readonly LoggingService logging;
private readonly Logger logger;
private readonly ApiService api;
public EnvelopeController(DatabaseService database, LoggingService logging, ApiService api)
{
this.database = database;
this.logging = logging;
this.logger = logging.LogConfig.GetLoggerFor(GetType().Name);
this.api = api;
}
[HttpGet]
[Route("api/envelope/{envelopeKey}")]
[IgnoreAntiforgeryToken]
public IActionResult Get(string envelopeKey)
{
try
{
logger.Info("Handling envelope loading.");
EnvelopeResponse r = api.EnsureValidEnvelopeKey(envelopeKey);
// Return the envelope and additional data as json
return Json(r);
}
catch (Exception e)
{
// Better error handling & reporting
logger.Error(e);
return Problem(
statusCode: 500,
detail: e.Message,
type: ErrorType.ServerError.ToString());
}
}
[HttpPost]
[Route("api/envelope/{envelopeKey}")]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> Update(string envelopeKey)
{
try
{
logger.Info("Handling envelope saving.");
api.EnsureValidEnvelopeKey(envelopeKey);
EnvelopeResponse r = database.LoadEnvelope(envelopeKey);
var Request = ControllerContext.HttpContext.Request;
var document = api.GetDocument(Request, envelopeKey);
string? annotationData = await api.EnsureValidAnnotationData(Request);
if (annotationData == null)
{
throw new ArgumentNullException("AnnotationData");
}
State state = api.GetState(logging.LogConfig, database.MSSQL);
DocumentStatusModel model = new(state);
model.InsertOrUpdate(new DocumentStatus()
{
EnvelopeId = r.Envelope.Id,
ReceiverId = r.ReceiverId,
Value = annotationData,
Status = Common.Constants.DocumentStatus.Signed
});
return Ok();
}
catch (Exception e)
{
// Better error handling & reporting
logger.Error(e);
return Problem(
statusCode: 500,
detail: e.Message,
type: ErrorType.ServerError.ToString());
}
}
}
}

View File

@ -9,25 +9,28 @@ namespace EnvelopeGenerator.Web.Controllers
{
public class HistoryController : Controller
{
private DatabaseService database;
private LoggingService logging;
private Logger logger;
private ApiService api;
private readonly DatabaseService database;
private readonly LoggingService logging;
private readonly Logger logger;
private readonly ApiService api;
public HistoryController(DatabaseService database, LoggingService logging, ApiService api)
{
this.database = database;
this.logging = logging;
this.logger = logging.LogConfig.GetLoggerFor("HistoryController");
this.logger = logging.LogConfig.GetLoggerFor(GetType().Name);
this.api = api;
}
[HttpPost]
[Route("api/history/{envelopeKey}")]
public IActionResult Create(HttpContext ctx, string envelopeKey)
[IgnoreAntiforgeryToken]
public IActionResult Create(string envelopeKey, [FromBody] ActionObject action)
{
try
{
var Request = ControllerContext.HttpContext.Request;
api.EnsureValidEnvelopeKey(envelopeKey);
EnvelopeResponse r = database.LoadEnvelope(envelopeKey);
var receiver = r.Envelope.Receivers.Where(receiver => receiver.Id == r.ReceiverId).SingleOrDefault();
@ -37,8 +40,8 @@ namespace EnvelopeGenerator.Web.Controllers
return BadRequest();
}
string actionTypeString = EnsureValidQueryField(ctx.Request, "actionType");
string actionDescription = EnsureValidQueryField(ctx.Request, "actionDescription");
string actionTypeString = action.actionType;
string actionDescription = action.actionDescription;
if (!Enum.TryParse<EnvelopeHistoryActionType>(actionTypeString, out var actionType))
{
@ -54,7 +57,7 @@ namespace EnvelopeGenerator.Web.Controllers
UserReference = receiver.Email
});
return Json(new { });
return Ok();
}
catch (Exception e)
{
@ -63,23 +66,10 @@ namespace EnvelopeGenerator.Web.Controllers
}
}
private string EnsureValidQueryField(HttpRequest request, string fieldName)
public class ActionObject
{
if (request.Query.TryGetValue(fieldName, out StringValues documentIndexString))
{
try
{
return documentIndexString.First();
}
catch (Exception e)
{
throw new ArgumentNullException(fieldName, e);
}
}
else
{
throw new ArgumentNullException(fieldName);
}
public string actionType { get; set; }
public string actionDescription { get; set; }
}
}
}

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>

View File

@ -34,7 +34,8 @@ namespace EnvelopeGenerator.Web.Handler
public enum ErrorType
{
None,
ServerError
ServerError,
FilesystemError
}
/// <summary>

View File

@ -1,69 +0,0 @@
using EnvelopeGenerator.Common;
using EnvelopeGenerator.Web.Services;
using Microsoft.Extensions.Primitives;
using NLog;
namespace EnvelopeGenerator.Web.Handler
{
public class HistoryHandler
{
private DatabaseService database;
private LoggingService logging;
private ApiService api;
public HistoryHandler(DatabaseService database, LoggingService logging, ApiService api)
{
this.database = database;
this.logging = logging;
this.api = api;
}
public IResult HandlePostHistoryEntry(HttpContext ctx)
{
try
{
//
// Load Envelope from EnvelopeKey
string envelopeKey = api.EnsureValidEnvelopeKey(ctx.Request);
EnvelopeResponse r = database.LoadEnvelope(envelopeKey);
var receiver = r.Envelope.Receivers.Where(receiver => receiver.Id == r.ReceiverId).SingleOrDefault();
EnvelopeHistoryEntry historyEntry = new()
{
EnvelopeId = r.Envelope.Id,
UserReference = receiver.Email
};
database.InsertHistoryEntry(historyEntry);
return Results.Ok();
}
catch (Exception)
{
return Results.Problem();
}
}
private int EnsureValidHistoryEntry(Logger logger, HttpRequest request)
{
if (request.Query.TryGetValue("index", out StringValues documentIndexString))
{
try
{
return int.Parse(documentIndexString.First());
}
catch (Exception e)
{
throw new ArgumentNullException("DocumentIndex", e);
}
}
else
{
throw new ArgumentNullException("DocumentIndex");
}
}
}
}

View File

@ -3,9 +3,11 @@
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<html lang="de">
<head>
<meta charset="utf-8" />
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />

View File

@ -1,8 +1,4 @@
using EnvelopeGenerator.Web.Handler;
using EnvelopeGenerator.Web.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
var builder = WebApplication.CreateBuilder(args);
@ -38,13 +34,8 @@ app.UseStaticFiles();
// Add a router
app.UseRouting();
// Add file download endpoint
FileHandler handler = new();
app.MapGet("/api/document/{envelopeKey}", handler.HandleGetDocument);
app.MapPost("/api/document/{envelopeKey}", handler.HandlePostDocument);
app.MapGet("/api/envelope/{envelopeKey}", handler.HandleGetEnvelope);
app.MapPost("/api/envelope/{envelopeKey}", handler.HandlePostEnvelope);
// Add controller routes
app.MapControllers();
// Blazor plumbing
app.MapBlazorHub();

View File

@ -1,4 +1,4 @@
import PSPDFKitType, { AnnotationsUnion, SignatureFormField as SignatureFormFieldType } from "./index";
import PSPDFKitType, { Action, AnnotationsUnion, SignatureFormField as SignatureFormFieldType } from "./index";
import { Instance, WidgetAnnotation, ToolbarItem } from "./index";
import { EnvelopeResponse, Envelope, User, Element, Document, IFunction } from "./interfaces";
@ -10,6 +10,17 @@ const { SignatureFormField } = PSPDFKit.FormFields;
const { DRAW, TYPE } = PSPDFKit.ElectronicSignatureCreationMode;
const { DISABLED } = PSPDFKit.AutoSaveMode;
enum ActionType {
Created = 0,
Saved = 1,
Sent = 2,
EmailSent = 3,
Delivered = 4,
Seen = 5,
Signed = 6,
Rejected = 7,
}
export class App {
public static Instance: Instance;
public static currentDocument: Document;
@ -56,6 +67,9 @@ export class App {
console.debug("Loading annotations..")
const annotations = App.Annotation.createAnnotations(App.currentDocument)
const createdAnnotations = await App.Instance.create(annotations)
const description = "Umschlag wurde geöffnet"
await App.Network.postHistory(App.envelopeKey, ActionType.Seen, description);
}
public static async handleClick(eventType: string) {
@ -125,6 +139,14 @@ export class App {
return false;
}
try {
const description = "Dokument wurde signiert"
await App.Network.postHistory(App.envelopeKey, ActionType.Signed, description);
} catch (e) {
console.error(e);
return false;
}
return true;
}
@ -242,7 +264,7 @@ class Network {
}
public postDocument(envelopeKey: string, documentId: number, buffer: ArrayBuffer): Promise<any> {
const url = `/api/document/${envelopeKey}/${documentId}`;
const url = `/api/document/${envelopeKey}?index=${documentId}`;
const options: RequestInit = {
credentials: "include",
method: "POST",
@ -279,6 +301,34 @@ class Network {
});
}
public postHistory(envelopeKey: string, actionType: ActionType, actionDescription: string): Promise<boolean> {
const url = `/api/history/${envelopeKey}`;
const data = {
actionDescription: actionDescription,
actionType: actionType.toString()
}
const options: RequestInit = {
credentials: "include",
method: "POST",
headers: {
'Content-Type': "application/json; charset=utf-8"
},
body: JSON.stringify(data)
}
console.debug("PostHistory/Calling url: " + url)
return fetch(url, options)
.then(this.handleResponse)
.then((res: Response) => {
if (!res.ok) {
return false;
};
return true;
});
}
private handleResponse(res: Response) {
if (!res.ok) {
console.log(`Request failed with status ${res.status}`)

View File

@ -1,31 +1,37 @@
using DigitalData.Modules.Logging;
using DigitalData.Modules.Database;
using DigitalData.Modules.Logging;
using EnvelopeGenerator.Common;
using Microsoft.Extensions.Primitives;
using System.Reflection.Metadata;
using System.Text;
namespace EnvelopeGenerator.Web.Services
{
public class ApiService
{
private LogConfig _logConfig;
private Logger _logger;
private readonly DatabaseService database;
private readonly LogConfig logConfig;
private readonly Logger logger;
public ApiService(LoggingService Logging, IConfiguration Config)
public ApiService(LoggingService Logging, DatabaseService database, IConfiguration Config)
{
_logConfig = Logging.LogConfig;
_logger = Logging.LogConfig.GetLogger();
this.database = database;
this.logConfig = Logging.LogConfig;
this.logger = Logging.LogConfig.GetLogger();
_logger.Debug("Initializing ApiService");
logger.Debug("Initializing ApiService");
}
public string EnsureValidEnvelopeKey(string envelopeKey)
public EnvelopeResponse EnsureValidEnvelopeKey(string envelopeKey)
{
_logger.Debug("Parsing EnvelopeKey..");
logger.Debug("Parsing EnvelopeKey..");
if (string.IsNullOrEmpty(envelopeKey))
throw new ArgumentNullException("EnvelopeKey");
Tuple<string, string> result = Helpers.DecodeEnvelopeReceiverId(envelopeKey);
_logger.Debug("EnvelopeUUID: [{0}]", result.Item1);
_logger.Debug("ReceiverSignature: [{0}]", result.Item2);
logger.Debug("EnvelopeUUID: [{0}]", result.Item1);
logger.Debug("ReceiverSignature: [{0}]", result.Item2);
if (string.IsNullOrEmpty(result.Item1))
throw new ArgumentNullException("EnvelopeUUID");
@ -33,13 +39,96 @@ namespace EnvelopeGenerator.Web.Services
if (string.IsNullOrEmpty(result.Item2))
throw new ArgumentNullException("ReceiverSignature");
return envelopeKey;
EnvelopeResponse r = database.LoadEnvelope(envelopeKey);
return r;
}
public string EnsureValidEnvelopeKey(HttpRequest request)
{
var envelopeKey = request.RouteValues["envelopeKey"] as string;
return EnsureValidEnvelopeKey(envelopeKey);
public async Task<string?> EnsureValidAnnotationData(HttpRequest request)
{
logger.Debug("Parsing AnnotationData..");
try
{
using MemoryStream ms = new();
await request.BodyReader.CopyToAsync(ms);
var bytes = ms.ToArray();
return Encoding.UTF8.GetString(bytes);
}
catch (Exception e)
{
logger.Error(e);
return null;
}
}
public int EnsureValidDocumentIndex(HttpRequest request)
{
if (request.Query.TryGetValue("index", out StringValues documentIndexString))
{
try
{
return int.Parse(documentIndexString.First());
}
catch (Exception e)
{
throw new ArgumentNullException("DocumentIndex", e);
}
}
else
{
throw new ArgumentNullException("DocumentIndex");
}
}
public EnvelopeDocument GetDocument(HttpRequest request, string envelopeKey)
{
EnvelopeResponse r = database.LoadEnvelope(envelopeKey);
int documentId = EnsureValidDocumentIndex(request);
var document = r.Envelope.Documents.
Where(d => d.Id == documentId).
FirstOrDefault();
if (document == null)
throw new ArgumentException("DocumentId");
return document;
}
public async Task<bool> UpdateDocument(Stream fileStream, string filePath)
{
try
{
using FileStream fs = new(filePath, FileMode.Open);
await fileStream.CopyToAsync(fs);
fs.Flush();
return true;
}
catch (Exception ex)
{
logger.Error(ex);
return false;
}
}
public State GetState(LogConfig LogConfig, MSSQLServer Database)
{
return new State
{
LogConfig = LogConfig,
Database = Database,
};
}
}
}

View File

@ -60,15 +60,12 @@ namespace EnvelopeGenerator.Web.Services
public EnvelopeResponse LoadEnvelope(string pEnvelopeKey)
{
Tuple<string, string> result = Helpers.DecodeEnvelopeReceiverId(pEnvelopeKey);
Tuple<string, string> result = Helpers.DecodeEnvelopeReceiverId(pEnvelopeKey);
var envelopeUuid = result.Item1;
var receiverSignature = result.Item2;
var receiverId = receiverModel.GetReceiverIdBySignature(receiverSignature);
Envelope envelope = envelopeModel.GetByUuid(envelopeUuid);
List<EnvelopeDocument> documents = (List<EnvelopeDocument>)documentModel.List(envelope.Id, receiverId);
envelope.Documents = documents;
return new()
{

View File

@ -39,6 +39,17 @@ var Rect = PSPDFKit.Geometry.Rect;
var SignatureFormField = PSPDFKit.FormFields.SignatureFormField;
var _a = PSPDFKit.ElectronicSignatureCreationMode, DRAW = _a.DRAW, TYPE = _a.TYPE;
var DISABLED = PSPDFKit.AutoSaveMode.DISABLED;
var ActionType;
(function (ActionType) {
ActionType[ActionType["Created"] = 0] = "Created";
ActionType[ActionType["Saved"] = 1] = "Saved";
ActionType[ActionType["Sent"] = 2] = "Sent";
ActionType[ActionType["EmailSent"] = 3] = "EmailSent";
ActionType[ActionType["Delivered"] = 4] = "Delivered";
ActionType[ActionType["Seen"] = 5] = "Seen";
ActionType[ActionType["Signed"] = 6] = "Signed";
ActionType[ActionType["Rejected"] = 7] = "Rejected";
})(ActionType || (ActionType = {}));
var App = /** @class */ (function () {
function App() {
}
@ -46,7 +57,7 @@ var App = /** @class */ (function () {
// and will trigger loading of the Editor Interface
App.init = function (container, envelopeKey) {
return __awaiter(this, void 0, void 0, function () {
var envelopeObject, arrayBuffer, e_1, _a, annotations, createdAnnotations;
var envelopeObject, arrayBuffer, e_1, _a, annotations, createdAnnotations, description;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
@ -90,6 +101,10 @@ var App = /** @class */ (function () {
return [4 /*yield*/, App.Instance.create(annotations)];
case 7:
createdAnnotations = _b.sent();
description = "Umschlag wurde geöffnet";
return [4 /*yield*/, App.Network.postHistory(App.envelopeKey, ActionType.Seen, description)];
case 8:
_b.sent();
return [2 /*return*/];
}
});
@ -136,7 +151,7 @@ var App = /** @class */ (function () {
};
App.handleFinish = function (event) {
return __awaiter(this, void 0, void 0, function () {
var e_2, json, postEnvelopeResult, e_3, buffer, postDocumentResult, e_4;
var e_2, json, postEnvelopeResult, e_3, buffer, postDocumentResult, e_4, description, e_5;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
@ -181,7 +196,18 @@ var App = /** @class */ (function () {
e_4 = _a.sent();
console.error(e_4);
return [2 /*return*/, false];
case 11: return [2 /*return*/, true];
case 11:
_a.trys.push([11, 13, , 14]);
description = "Dokument wurde signiert";
return [4 /*yield*/, App.Network.postHistory(App.envelopeKey, ActionType.Signed, description)];
case 12:
_a.sent();
return [3 /*break*/, 14];
case 13:
e_5 = _a.sent();
console.error(e_5);
return [2 /*return*/, false];
case 14: return [2 /*return*/, true];
}
});
});
@ -318,7 +344,7 @@ var Network = /** @class */ (function () {
.then(function (res) { return res.arrayBuffer(); });
};
Network.prototype.postDocument = function (envelopeKey, documentId, buffer) {
var url = "/api/document/".concat(envelopeKey, "/").concat(documentId);
var url = "/api/document/".concat(envelopeKey, "?index=").concat(documentId);
var options = {
credentials: "include",
method: "POST",
@ -353,6 +379,31 @@ var Network = /** @class */ (function () {
return true;
});
};
Network.prototype.postHistory = function (envelopeKey, actionType, actionDescription) {
var url = "/api/history/".concat(envelopeKey);
var data = {
actionDescription: actionDescription,
actionType: actionType.toString()
};
var options = {
credentials: "include",
method: "POST",
headers: {
'Content-Type': "application/json; charset=utf-8"
},
body: JSON.stringify(data)
};
console.debug("PostHistory/Calling url: " + url);
return fetch(url, options)
.then(this.handleResponse)
.then(function (res) {
if (!res.ok) {
return false;
}
;
return true;
});
};
Network.prototype.handleResponse = function (res) {
if (!res.ok) {
console.log("Request failed with status ".concat(res.status));

File diff suppressed because one or more lines are too long