using System; using System.Collections.Generic; using System.Data; using System.Data.Entity.Validation; using System.Diagnostics; using System.Net; using System.Web.Mvc; using System.Xml.Linq; using System.Linq; using Pilotfish.Afx.ComponentModel; using Pilotfish.Afx.Mvc; using Pilotfish.Afx.Services.Integration; using Pilotfish.Afx.Services.Workflows; using Pilotfish.Afx.Services.Workflows.Entities; using Pilotfish.Afx.ViewModels; using Neo.Legitimate.LicenceIssueRequest.Models; using System.Text; using Neo.Legitimate.Data.Models; using Pilotfish.Afx.Services.Audits; using Neo.Legitimate.Common; using Xceed.Words.NET; using System.Drawing; using System.IO; using Pilotfish.Afx.Services.Documents; namespace Neo.Legitimate.LicenceIssueRequest.Controllers { public class LicenceIssueRequestController : Controller { #region Constructor public LicenceIssueRequestController() : base(new LicenceIssueDatabase()) { } #endregion #region Console public ActionResult Console(long workflowid, long itemid, string returnUrl) { var consoleUrl = "~/LicenceIssueRequest/Console?workflowid=" + workflowid + "&itemid=" + itemid + "&t=" + DateTime.Now.Ticks + (!string.IsNullOrEmpty(returnUrl) ? "&returnurl=" + returnUrl : ""); //ensure t (ticks) parameter is present to prevent caching if (Request.QueryString["t"] == null) { return Redirect(consoleUrl); } var workflowDatabase = new WorkflowsDatabase(); if (!workflowDatabase.CheckWorkflowInstanceSecurity(workflowid, itemid, Profile.UserName) || itemid <= 0) { return Redirect(Url.Content("~/Error/ShowSecurityError?error=WORKFLOWACCESSSECURITY&workflowid=" + workflowid + "&itemid=" + itemid + "&returnUrl=" + Convert.ToBase64String(Encoding.ASCII.GetBytes(consoleUrl)))); } return View("Console", GetViewModelInternal(workflowid, itemid)); } #endregion #region Save [HttpPost] public JsonResult Save(Neo.Legitimate.LicenceIssueRequest.Models.LicenceIssueDetail value) { var changes = new List(); var memberChanges = new List(); var licenceChanges = new List(); var vehicleChanges = new List(); var auditDb = new AuditsDatabase(); var legitimateDb = new LegitimateDatabase(); if (value.LicenceIssueDetailID == Database.NewID) { throw new Exception("New licence records can not be created manually."); } else { var projDb = new LicenceIssueDatabase(); //don't use database as we need the values refreshed every time var existingModel = projDb.GetLicenceIssueRequest(value.LicenceIssueDetailID, Profile.UserID); if (existingModel != null && existingModel.UpdatedDate.ToLongTimeString() != value.UpdatedDate.ToLongTimeString()) { return Json(new { Result = "CONFLICT", Message = "The record has been modified by someone else. Please try again." }); } #region Check if user is allowed to edit the record at this stage try { projDb.CheckSecurity(value.LicenceIssueDetailID, "Save", Profile.UserID); } catch (Exception ex) { return Json(new { Result = "ERROR", Message = new LegitimateDatabase().GetInnermostMessage(ex) }); } #endregion value.UpdatedDate = DateTime.Now; value.UpdatedByID = Profile.UserID; try { //make sure the VIN number is not linked to any other licence before saving if (value.Licence != null && value.Vehicle != null && !string.IsNullOrEmpty(value.Vehicle.VIN)) { legitimateDb.CheckIfvehicleIsInUse(value.Licence.OperatingLicenceNumber, value.Vehicle.VIN); } //No changes is allowed once the licence has been printed if (value.Licence != null && !string.IsNullOrEmpty(value.Licence.CertificateNumber)) { //but do silent fall through as save is called automatically when submitting tasks return Json(new WorkflowSaveResult { Id = value.LicenceIssueDetailID, WorkflowInstanceID = (value.WorkflowInstanceID ?? 0) }); } // Make sure the object we are saving is the same is in the current context var current = Database.Context.LicenceIssueDetails.Where(a => a.LicenceIssueDetailID == value.LicenceIssueDetailID).FirstOrDefault(); Database.Context.Entry(current).CurrentValues.SetValues(value); Database.Context.Entry(current).State = System.Data.Entity.EntityState.Modified; #region Vehicle current.Vehicle = value.Vehicle; if (current.Vehicle == null || current.Vehicle.VehicleID == Database.NewID) { Database.Insert(current.Vehicle); changes.Add(string.Format("{0}, Added vehicle {1}, {2}", "Vehicles", current.Vehicle.VIN, current.Vehicle.RegistrationNumber)); } else { Database.Update(current.Vehicle); vehicleChanges.AddRange(auditDb.GetEntityDifferences(existingModel.Vehicle, current.Vehicle, "VehicleID")); } #endregion #region Licence if (value.ApplicationRequestDetail.ApplicationRequestTypeID == (short)Neo.Legitimate.Common.ApplicationRequestType.TemporarySpecialLicence) { //this logic must be updated in the APP save as well if you adjust it if (((TimeSpan)(value.Licence.DateOfExpiry - value.Licence.DateOfIssue)).TotalDays > 14) { throw new Exception("A special licence duration is not allowed to exceed 14 days."); } else if (value.Licence.DateOfExpiry.Value < value.Licence.DateOfIssue) { throw new Exception("The issue date must be before or the same as the expiry date."); } Database.Update(value.Licence); licenceChanges.AddRange(auditDb.GetEntityDifferences(existingModel.Licence, value.Licence, "LicenceID")); } #endregion #region Member Database.Update(value.Licence.Member); memberChanges.AddRange(auditDb.GetEntityDifferences(existingModel.Licence.Member, value.Licence.Member, "MemberID")); #endregion #region value.Documents foreach (var document in value.Documents) { Database.Update(document); var existingDocument = existingModel.Documents.Where(a => a.LicenceIssueDocumentID == document.LicenceIssueDocumentID).FirstOrDefault(); if (existingDocument != null) { changes.AddRange(auditDb.GetEntityDifferences(existingDocument, document, "LicenceIssueDocumentID")); } } #endregion #region Licence Issue Detail Database.Update(current); changes.AddRange(auditDb.GetEntityDifferences(existingModel, value, "LicenceIssueDetailID")); #endregion } catch (Exception ex) { return Json(new { Result = "ERROR", Message = string.Format("Error: {0}", legitimateDb.GetInnermostMessage(ex)) }); } } try { Database.Save(); Database.Context.Pr_LicenceIssuePostSaveProcess(value.LicenceIssueDetailID); if (changes.Count > 0) { auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, changes, 1014 /*Licence Issue Details*/, value.LicenceIssueDetailID, Profile.UserID); } if (memberChanges.Count > 0) { auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, memberChanges, 1014 /*Licence Issue Details*/, value.LicenceIssueDetailID, Profile.UserID); auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, memberChanges, 1009 /*Member*/, value.Licence.MemberID, Profile.UserID); } if (licenceChanges.Count > 0) { auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, licenceChanges, 1014 /*Licence Issue Details*/, value.LicenceIssueDetailID, Profile.UserID); auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, licenceChanges, 1011 /*Operating Licence*/, value.Licence.LicenceID, Profile.UserID); } if (vehicleChanges.Count > 0) { auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, vehicleChanges, 1014 /*Licence Issue Details*/, value.LicenceIssueDetailID, Profile.UserID); if (value.Licence != null && value.Licence.VehicleID.HasValue) { auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, vehicleChanges, 1012 /*Vehicle Details*/, value.Licence.VehicleID.Value, Profile.UserID); } } } catch (DbEntityValidationException dbEx) { foreach (var validationError in dbEx.EntityValidationErrors.SelectMany(validationErrors => validationErrors.ValidationErrors)) { return Json(new { Result = "ERROR", Message = string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) }); } } catch (Exception ex) { var message = (ex.InnerException != null && ex.InnerException.InnerException != null) ? ex.InnerException.InnerException.Message : ex.Message; if (!string.IsNullOrEmpty(message) && message.ToLower().Contains("ix_vehicles")) { var chassis = (value.Vehicle != null && !string.IsNullOrEmpty(value.Vehicle.VIN)) ? value.Vehicle.VIN : "blank"; var linkedLicences = Database.GetLicencesLinkedByVIN(value.Vehicle.VIN); if (string.IsNullOrEmpty(linkedLicences)) { Database.CleanseUnusedVehicleData(); message = "The specified chassis number (" + chassis + ") is currently locked. A cleanup process has been started to see if the vehicle can be re-used. Please try again in 5 minutes time. If the problem persists contact the system administrator.;"; } else { message = "The specified chassis number (" + chassis + ") is already linked to the following application(s): " + Database.GetLicencesLinkedByVIN(value.Vehicle.VIN); } } return Json(new { Result = "ERROR", Message = string.Format("Error: {0}", message) }); } return Json(new WorkflowSaveResult { Id = value.LicenceIssueDetailID, WorkflowInstanceID = (value.WorkflowInstanceID ?? 0) }); } #endregion #region PrintAnnexure [HttpGet] public FileResult PrintAnnexure(long licenceIssueDetailID, long licenceId) { if (!SecurityHelper.UserHasAccessToSecurable(Profile.Securables.ToList(), Common.Securable.OperatingLicencesModule_Issuing_LicencesAwaitingVerificationandPrinting)) { throw new Exception("Security error"); } var db = new LegitimateDatabase(); var licenceIssueDetail = db.GetLicenceIssueDetailsReport(licenceIssueDetailID, Profile.UserID); var lirRoutes = db.GetVerifiedLicenceRoutes(licenceId); string fileMain = Server.MapPath(@"~\Content\Annexure Documents\Main.docx"); var doc = DocX.Load(fileMain); #region Annexure 1 foreach (var route in lirRoutes) { var table = doc.AddTable(7, 2); table.Alignment = Alignment.left; table.SetColumnWidth(0, 2500); table.SetColumnWidth(1, 6500); table.Rows[0].Cells[0].Paragraphs.First().Append("Natonal Route Code:").Bold(); table.Rows[0].Cells[1].Paragraphs.First().Append(route.NationalRouteNumber); table.Rows[1].Cells[0].Paragraphs.First().Append("Board Route Code:").Bold(); table.Rows[1].Cells[1].Paragraphs.First().Append(route.BoardRouteNumber); table.Rows[2].Cells[0].Paragraphs.First().Append("Route Name:").Bold(); table.Rows[2].Cells[1].Paragraphs.First().Append(route.RouteName); table.Rows[3].Cells[0].Paragraphs.First().Append("Route Type:").Bold(); table.Rows[3].Cells[1].Paragraphs.First().Append(route.RouteType); table.Rows[4].Cells[0].Paragraphs.First().Append("Operating licence:").Bold(); table.Rows[4].Cells[1].Paragraphs.First().Append(licenceIssueDetail.OperatingLicenceNumber); table.Rows[5].Cells[0].Paragraphs.First().Append("Description:").Bold(); table.Rows[5].Cells[1].Paragraphs.First().Append(route.Description); var blankBorder = new Border(BorderStyle.Tcbs_none, 0, 0, Color.White); table.SetBorder(TableBorderType.Bottom, blankBorder); table.SetBorder(TableBorderType.Top, blankBorder); table.SetBorder(TableBorderType.Left, blankBorder); table.SetBorder(TableBorderType.Right, blankBorder); table.SetBorder(TableBorderType.InsideV, blankBorder); table.SetBorder(TableBorderType.InsideH, blankBorder); doc.InsertTable(table); if (route.TimeTableDocumentID.HasValue) { try { doc.InsertSectionPageBreak(); var docDatabase = new DocumentsDatabase(); var timeTableDocument = docDatabase.GetDocumentObject(route.TimeTableDocumentID.Value); Stream timeTableStream = new MemoryStream(timeTableDocument.Content); var templateTimeTableDoc = DocX.Load(timeTableStream); doc.InsertDocument(templateTimeTableDoc, true); } catch { throw new Exception("Error loading timetable annexure for route " + route.NationalRouteNumber + ". Please ensure that the file is uploaded as a .docx file"); } } if (route.FareScheduleDocumentID.HasValue) { try { doc.InsertSectionPageBreak(); var docDatabase = new DocumentsDatabase(); var fareScheduleDocument = docDatabase.GetDocumentObject(route.FareScheduleDocumentID.Value); Stream fareScheduleStream = new MemoryStream(fareScheduleDocument.Content); var fareScheduleDoc = DocX.Load(fareScheduleStream); doc.InsertDocument(fareScheduleDoc, true); } catch { throw new Exception("Error loading fare schedule annexure for route " + route.NationalRouteNumber + ". Please ensure that the file is uploaded as a .docx file"); } } } doc.InsertSectionPageBreak(); #endregion #region Annexure 2 // Insert a Paragraph into this document. Paragraph p = doc.InsertParagraph(); // Append some text and add formatting. p.Append("Annexure 2 \n") .Font("Arial") .FontSize(12) .Color(Color.Black) .UnderlineStyle(UnderlineStyle.singleLine) .Bold(); if (licenceIssueDetail.ShowBusAnnexure == 1) { string fileLicenceConditionsBuses = Server.MapPath(@"~\Content\Annexure Documents\LicenceConditionsBuses.docx"); var TemplateLicenceConditionsBuses = DocX.Load(fileLicenceConditionsBuses); doc.InsertDocument(TemplateLicenceConditionsBuses, true); doc.InsertSectionPageBreak(); } if (licenceIssueDetail.ShowMidiBusAnnexure == 1) { string fileLicenceConditionsMidiBus = Server.MapPath(@"~\Content\Annexure Documents\LicenceConditionsMidiBus.docx"); var TemplateLicenceConditionsMidiBus = DocX.Load(fileLicenceConditionsMidiBus); doc.InsertDocument(TemplateLicenceConditionsMidiBus, true); doc.InsertSectionPageBreak(); } if (licenceIssueDetail.ShowMinibusAnnexure == 1) { string fileLicenceConditionsMinibu = Server.MapPath(@"~\Content\Annexure Documents\LicenceConditionsMinibus.docx"); var TemplateLicenceConditionsMinibu = DocX.Load(fileLicenceConditionsMinibu); doc.InsertDocument(TemplateLicenceConditionsMinibu, true); doc.InsertSectionPageBreak(); } if (licenceIssueDetail.ShowMeteredTaxiAnnexure == 1) { string fileLicenceConditionsMeteredTaxi = Server.MapPath(@"~\Content\Annexure Documents\LicenceConditionsMeteredTaxi.docx"); var TemplateLicenceConditionsMeteredTaxi = DocX.Load(fileLicenceConditionsMeteredTaxi); doc.InsertDocument(TemplateLicenceConditionsMeteredTaxi, true); doc.InsertSectionPageBreak(); } if (licenceIssueDetail.ShowEHailingAnnexure == 1) { string fileLicenceConditionsEHailing = Server.MapPath(@"~\Content\Annexure Documents\LicenceConditionsEHailing.docx"); var TemplateLicenceConditionsEHailing = DocX.Load(fileLicenceConditionsEHailing); doc.InsertDocument(TemplateLicenceConditionsEHailing, true); doc.InsertSectionPageBreak(); } if (licenceIssueDetail.ShowScholarAnnexure == 1) { string fileLicenceConditionsScholarTransport = Server.MapPath(@"~\Content\Annexure Documents\LicenceConditionsScholarTransport.docx"); var TemplateLicenceConditionsScholarTransport = DocX.Load(fileLicenceConditionsScholarTransport); doc.InsertDocument(TemplateLicenceConditionsScholarTransport, true); doc.InsertSectionPageBreak(); } if (licenceIssueDetail.ShowStaffServiceAnnexure == 1) { string fileLicenceConditionsStaffService = Server.MapPath(@"~\Content\Annexure Documents\LicenceConditionsStaffService.docx"); var TemplateLicenceConditionsStaffServices = DocX.Load(fileLicenceConditionsStaffService); doc.InsertDocument(TemplateLicenceConditionsStaffServices, true); doc.InsertSectionPageBreak(); } #endregion #region Annexure 3 string fileAnnexure3 = Server.MapPath(@"~\Content\Annexure Documents\Annexure3.docx"); var TemplateAnnexure3 = DocX.Load(fileAnnexure3); TemplateAnnexure3.ReplaceText("[OperatingLicenceNumber]", licenceIssueDetail.OperatingLicenceNumber, false); doc.InsertDocument(TemplateAnnexure3, true); #endregion #region Footer doc.ReplaceText("[OperatingLicenceNumber]", licenceIssueDetail.OperatingLicenceNumber, false); doc.ReplaceText("[CertificateNumber]", licenceIssueDetail.CertificateNumber, false); #endregion #region Add protection to document EditRestrictions erReadOnly = EditRestrictions.readOnly; doc.AddProtection(erReadOnly); #endregion var populatedFileStream = new MemoryStream(); doc.SaveAs(populatedFileStream); return File(populatedFileStream.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingm", "APP" + licenceIssueDetail.ApplicationRequestDetailID + "_" + licenceIssueDetail.CertificateNumber + ".docx"); } #endregion #region GetViewModelInternal private WorkflowConsoleViewModelBase GetViewModelInternal(long workflowid, long itemid, bool includeLookups = true) { var projDb = new LicenceIssueDatabase(); //don't use database as we need the values refreshed every time var workflowDatabase = new WorkflowsDatabase(); var value = projDb.GetLicenceIssueRequest(itemid, Profile.UserID); if (value == null) { throw new Exception("Error initialising object data"); } if (Profile.Roles == null) { throw new Exception("Current user does not have any roles."); } //recalculate any exceptions var database = new LegitimateDatabase(); database.RecalculateLicenceExceptions(value.VerifiedLicenceID); //Re-assign the current task to the user if a) it is assigned to the system and b) the user is in the role linked to the task if (value.WorkflowInstanceID.HasValue) { workflowDatabase.ReAssignWorkflowInstanceGroupTask(value.WorkflowInstanceID.Value, Profile.UserID, "", Profile.UserID); } var vm = workflowDatabase.GetWorkflowConsoleViewModel(workflowid, (value.WorkflowInstanceID.HasValue ? value.WorkflowInstanceID.Value : -1), itemid, Profile.UserID, Profile.Roles, Profile.WorkflowBuddies); if (vm == null) { throw new Exception("Error initialising view model data"); } if (itemid < 0) { SetWorkflowTemplateDefaults(value, (IEnumerable)vm.WorkflowTemplateDefaults); } #region get defaults if new request if (itemid < 0) { //var integrationStore = new SqlIntegrationStore(); //try //{ // integrationStore.Open(); // var employee = integrationStore.GetData("Employees", "EmployeeNumber=" + Profile.UserID).FirstNode; // if (employee != null) // { // value.RequestedBy = employee.ToString(SaveOptions.DisableFormatting); // } //} //finally //{ // integrationStore.Close(); //} } #endregion #region load lookups var lookups = new List(); if (includeLookups) { var integrationStore = new SqlIntegrationStore(); try { integrationStore.Open(); lookups.Add(new LookupList("NewOLVehicleTypes", integrationStore.GetDataEntities("VehicleTypes", string.Empty))); lookups.Add(new LookupList("NewOLIDTypes", integrationStore.GetDataEntities("IDTypes", string.Empty))); lookups.Add(new LookupList("NewOLBusinessTypes", integrationStore.GetDataEntities("BusinessTypes", string.Empty))); lookups.Add(new LookupList("NewOLCarryingCapacities", integrationStore.GetDataEntities("CarryingCapacities", string.Empty))); } finally { integrationStore.Close(); } } #endregion vm.Lookups = lookups; vm.Value = value; ViewBag.Title = "Licence Issue Workflow Console"; return vm; } #endregion #region GetViewModel [HttpGet] public string GetViewModel(long workflowid, long itemid) { var workflowDatabase = new WorkflowsDatabase(); if (!workflowDatabase.CheckWorkflowInstanceSecurity(workflowid, itemid, Profile.UserName)) { throw new Exception("Security error trying to access GetViewModel"); } return GetViewModelInternal(workflowid, itemid, false).ToJson(JsonSerializerOptions.FormatDateTime); } #endregion #region SetWorkflowTemplateDefaults static void SetWorkflowTemplateDefaults(Neo.Legitimate.LicenceIssueRequest.Models.LicenceIssueDetail value, IEnumerable defaults) { } #endregion #region JSON endpoints #region GetVerifiedOperatingLicence [HttpPost] public JsonResult GetVerifiedOperatingLicence(long licenceID, string documentNumber, bool isReprint, string reprintReason) { if (!isReprint) { if (!SecurityHelper.UserHasAccessToSecurable(Profile.Securables.ToList(), Securable.OperatingLicencesModule_LicenceIssueRequest_PrintLicence_Actual) && !SecurityHelper.UserHasAccessToSecurable(Profile.Securables.ToList(), Securable.OperatingLicencesModule_LicenceIssueRequest_PrintLicence_Test)) { throw new Exception("Security error"); } } else { if (!SecurityHelper.UserHasAccessToSecurable(Profile.Securables.ToList(), Securable.OperatingLicencesModule_LicenceIssueRequest_RePrintLicence)) { throw new Exception("Security error"); } } if (isReprint && string.IsNullOrEmpty(reprintReason)) { throw new Exception("No reprint reason specified"); } var database = new LegitimateDatabase(); var errorMessage = ""; var ol = database.UpdateOperatingLicence(licenceID, documentNumber, isReprint, reprintReason, Profile.UserID, out errorMessage); if (isReprint) { database.WriteAuditEntry((int)Profile.UserID, "Application", "LIR Reprint", reprintReason, false, false, "licence", licenceID); } else { database.WriteAuditEntry((int)Profile.UserID, "Application", "LIR Print", reprintReason, false, false, "licence", licenceID); } if (errorMessage == "" && !string.IsNullOrEmpty(ol.LicenceExceptions)) { errorMessage = ol.LicenceExceptions; ol = null; } var result = new { OperatingLicence = ol, ServerDate = DateTime.Now.ToString("dd MMM yyyy HH:mm"), ErrorMessage = errorMessage }; return Json(result, JsonSerializerOptions.None); } #endregion #region GetOperatingLicenceDetails [HttpPost] public JsonResult GetOperatingLicenceDetails(long licenceID) { var database = new LegitimateDatabase(); var licence = database.GetVerifiedOperatingLicence(licenceID); var result = new { OperatingLicence = (string.IsNullOrEmpty(licence.LicenceExceptions)) ? licence : null, ServerDate = DateTime.Now.ToString("dd MMM yyyy HH:mm"), ErrorMessage = licence.LicenceExceptions }; return Json(result, JsonSerializerOptions.None); } #endregion #region RecalculateExceptions [HttpPost] public JsonResult RecalculateExceptions(long licenceID) { var database = new LegitimateDatabase(); var errorMessage = ""; try { database.RecalculateLicenceExceptions(licenceID); } catch (Exception ex) { errorMessage = database.GetInnermostMessage(ex); } var result = new { ErrorMessage = errorMessage }; return Json(result, JsonSerializerOptions.None); } #endregion #region AddRouteToVerifiedLicence [HttpPost] public JsonResult AddRouteToLicence(long licenceID, long routeID) { if (!SecurityHelper.UserHasAccessToSecurable(Profile.Securables.ToList(), Securable.OperatingLicencesModule_LicenceIssueRequest_AmendRoutes)) { throw new Exception("Security error"); } var database = new LegitimateDatabase(); var errorMessage = ""; try { var licence = database.GetVerifiedOperatingLicence(licenceID); if (!string.IsNullOrEmpty(licence.CertificateNumber)) { throw new Exception("No changes can be made to the licence as it has already been printed"); } database.AddRouteToVerifiedLicence(licenceID, routeID, Profile.UserID); } catch (Exception ex) { errorMessage = database.GetInnermostMessage(ex); } var result = new { ErrorMessage = errorMessage }; return Json(result, JsonSerializerOptions.None); } #endregion #region RemoveRouteFromVerifiedLicence [HttpPost] public JsonResult RemoveRouteFromVerifiedLicence(long licenceID, long routeID) { if (!SecurityHelper.UserHasAccessToSecurable(Profile.Securables.ToList(), Securable.OperatingLicencesModule_LicenceIssueRequest_AmendRoutes)) { throw new Exception("Security error"); } var database = new LegitimateDatabase(); var errorMessage = ""; try { var licence = database.GetVerifiedOperatingLicence(licenceID); if (!string.IsNullOrEmpty(licence.CertificateNumber)) { throw new Exception("No changes can be made to the licence as it has already been printed"); } database.RemoveRouteFromVerifiedLicence(licenceID, routeID, Profile.UserID); } catch (Exception ex) { errorMessage = database.GetInnermostMessage(ex); } var result = new { ErrorMessage = errorMessage }; return Json(result, JsonSerializerOptions.None); } #endregion #region IssueWithoutPrint [HttpPost] public JsonResult IssueWithoutPrint(long licenceID, string reason) { var database = new LegitimateDatabase(); var errorMessage = ""; if (!SecurityHelper.UserHasAccessToSecurable(Profile.Securables.ToList(), Securable.OperatingLicencesModule_LicenceIssueRequest_IssueWithoutPrint)) { throw new Exception("Security error"); } try { database.IssueLicenceWithoutPrint(licenceID, reason, Profile.UserID); } catch (Exception ex) { errorMessage = database.GetInnermostMessage(ex); } var result = new { ErrorMessage = errorMessage }; return Json(result, JsonSerializerOptions.None); } #endregion #endregion } }