using System;
using System.Text;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Data.Entity.Validation;
using System.Collections.Generic;
using Neo.Afx.Mvc;
using Neo.Afx.ViewModels;
using Neo.Afx.ComponentModel;
using Neo.Afx.Services.Integration;
using Neo.Afx.Services.Workflows;
using Neo.Afx.Services.Workflows.Entities;
using Neo.Afx.Services.Forms.Entities;
using Neo.LegitimateLicences.Common;
using Neo.LegitimateLicences.Data.Models;
using Neo.LegitimateLicences.LicenceIssueRequest.Models;
using Neo.LegitimateLicences.Data;
using Neo.Afx.Services.Audits;
using Neo.LegitimateLicences.Common.Helpers;
using Neo.LegitimateLicences.LicenceIssueRequest.Models.Database;
using LicenceIssueDetail = Neo.LegitimateLicences.LicenceIssueRequest.Models.Database.LicenceIssueDetail;
using Vehicle = Neo.LegitimateLicences.LicenceIssueRequest.Models.Database.Vehicle;
using Licence = Neo.LegitimateLicences.LicenceIssueRequest.Models.Database.Licence;
using Member = Neo.LegitimateLicences.LicenceIssueRequest.Models.Database.Member;
using Neo.Afx.Common;
namespace Neo.LegitimateLicences.LicenceIssueRequest
{
public partial class LicenceIssueRequestController
{
#region Save
///
/// Save LicenceIssueRequest details
///
///
///
[HttpPost]
public JsonNetResult Save(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("#EXPOSE_ERROR#New licence records can not be created manually.");
}
else
{
try
{
var liDb = new LicenceIssueDatabase(); //don't use database as we need the values refreshed every time
var existingModel = liDb.GetLicenceIssueForm(value.LicenceIssueDetailID, Profile.UserID);
//if (existingModel != null && existingModel.UpdatedDate.ToLongTimeString() != value.UpdatedDate.ToLongTimeString())
//{
// return new JsonNetResult()
// {
// Data = new JsonBaseResult()
// {
// Success = false,
// ErrorCode = "CONFLICT",
// Error = "#EXPOSE_ERROR#The record has been modified by someone else. Please try again."
// }
// };
//}
value.UpdatedDate = DateTime.Now;
value.UpdatedByID = Profile.UserID;
#region Get active user task
var itemId = WebHelper.ItemID;
var taskId = WebHelper.TaskID;
Vw_WorkflowInstanceTask activeUserTask = null;
if (taskId != -1)
{
activeUserTask = WorkflowHelper.GetActiveUserUserTaskByID((long)EntityEnum.LicenceIssueDetails, itemId, taskId, Profile.UserID);
}
if (activeUserTask == null)
{
activeUserTask = WorkflowHelper.GetActiveUserTask(Profile.UserID, EntityEnum.LicenceIssueDetails, itemId);
}
#endregion
#region Check if can save
var canSubmit = (activeUserTask != null && activeUserTask.WorkflowTemplateStepTypeID == (short)WorkflowTemplateStepTypeEnum.DataCapture);
if (!canSubmit)
{
throw new Exception("#EXPOSE_ERROR#Security error");
}
#endregion
//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, Profile.UserID);
}
// 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.Application.ApplicationRequestTypeID == (short)Neo.LegitimateLicences.Common.ApplicationRequestTypeEnum.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("#EXPOSE_ERROR#A special licence duration is not allowed to exceed 14 days.");
}
else if (value.Licence.DateOfExpiry.Value < value.Licence.DateOfIssue)
{
throw new Exception("#EXPOSE_ERROR#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 Licence Issue Detail
Database.Update(current);
changes.AddRange(auditDb.GetEntityDifferences(existingModel, value, "LicenceIssueDetailID"));
#endregion
#region Do save
try
{
Database.Save();
Database.LicenceIssuePostSave(value.LicenceIssueDetailID, Profile.UserID);
if (changes.Count > 0)
{
auditDb.WriteEntries((short)AuditSourceEnum.Application, (short)AuditActionEnum.Updated, changes, (short)EntityEnum.LicenceIssueDetails, value.LicenceIssueDetailID, Profile.UserID);
}
if (memberChanges.Count > 0)
{
auditDb.WriteEntries((short)AuditSourceEnum.Application, (short)AuditActionEnum.Updated, memberChanges, (short)EntityEnum.LicenceIssueDetails, value.LicenceIssueDetailID, Profile.UserID);
auditDb.WriteEntries((short)AuditSourceEnum.Application, (short)AuditActionEnum.Updated, memberChanges, (short)EntityEnum.Members, value.Licence.MemberID, Profile.UserID);
}
if (licenceChanges.Count > 0)
{
auditDb.WriteEntries((short)AuditSourceEnum.Application, (short)AuditActionEnum.Updated, licenceChanges, (short)EntityEnum.LicenceIssueDetails, value.LicenceIssueDetailID, Profile.UserID);
auditDb.WriteEntries((short)AuditSourceEnum.Application, (short)AuditActionEnum.Updated, licenceChanges, (short)EntityEnum.OperatingLicences, value.Licence.LicenceID, Profile.UserID);
}
if (vehicleChanges.Count > 0)
{
auditDb.WriteEntries((short)AuditSourceEnum.Application, (short)AuditActionEnum.Updated, vehicleChanges, (short)EntityEnum.LicenceIssueDetails, value.LicenceIssueDetailID, Profile.UserID);
if (value.Licence != null && value.Licence.VehicleID.HasValue)
{
auditDb.WriteEntries((short)AuditSourceEnum.Application, (short)AuditActionEnum.Updated, vehicleChanges, (short)EntityEnum.Vehicles, value.Licence.VehicleID.Value, Profile.UserID);
}
}
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationError in dbEx.EntityValidationErrors.SelectMany(validationErrors => validationErrors.ValidationErrors))
{
return new JsonNetResult()
{
Data = new JsonBaseResult()
{
Success = false,
ErrorCode = "ERROR",
Error = string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage)
}
};
}
}
catch (Exception ex)
{
#region Error Handling
#region Error Additional Data
Dictionary additionalData = new Dictionary();
additionalData.Add("value", value);
#endregion
var errorMessage = ErrorHelper.ProcessError(ex, "LicenceIssueRequest", "Save", additionalData);
#endregion
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, Profile.UserID);
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, Profile.UserID);
}
}
return new JsonNetResult()
{
Data = new JsonBaseResult()
{
Success = false,
ErrorCode = "ERROR",
Error = string.Format("Error: {0}", message)
}
};
}
#endregion
}
catch (Exception ex)
{
#region Error Handling
#region Error Additional Data
Dictionary additionalData = new Dictionary();
additionalData.Add("value", value);
#endregion
var errorMessage = ErrorHelper.ProcessError(ex, "LicenceIssueRequest", "Save", additionalData);
#endregion
return new JsonNetResult()
{
Data = new JsonBaseResult()
{
Success = false,
ErrorCode = "ERROR",
Error = errorMessage
}
};
}
return new JsonNetResult()
{
Data = new JsonBaseResult()
{
Success = true,
Error = "",
ErrorCode = ""
}
};
}
#endregion
}
}
}