using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using NHibernate; using NHibernate.Linq; using Sleis.Models; using Sleis.ViewModels; using Sleis.Infrastructure; using log4net; using Sleis.Utility; using Sleis.Data; using System.ComponentModel; using Sleis.Models.CustomFields; using Ionic.Zip; using System.IO; using System.Web; namespace Sleis.Service { public abstract class BaseService : Sleis.Service.IBaseService { internal static ILog Log; internal static ILog SleisAuditLog; public IPropertyPlaceholder Properties { get; set; } public EventData EventData { get; set; } public EncryptionUtility EncryptionUtility { get; set; } public IFacilityData FacilityData { get; set; } public CustomFieldData CustomFieldData { get; set; } public CustomFieldValueData CustomFieldValueData { get; set; } public RepudiationData RepudiationData { get; set; } public AmendmentRequestData AmendmentRequestData { get; set; } public SimpleLookupItemData SimpleLookupItemData { get; set; } public IUserData UserData { get; set; } public EpaData EpaData { get; set; } public EmailUtility EmailUtility { get; set; } public string AgencyResponseToRepudiationEmailTemplate { get; set; } public string AgencyResponseToAmendmentEmailTemplate { get; set; } public PageService PageService { get; set; } public BaseService() { Log = LogManager.GetLogger(this.GetType()); SleisAuditLog = LogManager.GetLogger("SleisAudit"); } public virtual void Init() { ArgumentValidationUtility.ThrowOnNull(Properties, "Properties"); ArgumentValidationUtility.ThrowOnNull(EventData, "EventData"); ArgumentValidationUtility.ThrowOnNull(EncryptionUtility, "EncryptionUtility"); //ArgumentValidationUtility.ThrowOnNull(FacilityData, "FacilityData"); ArgumentValidationUtility.ThrowOnNull(CustomFieldData, "CustomFieldData"); ArgumentValidationUtility.ThrowOnNull(CustomFieldValueData, "CustomFieldValueData"); ArgumentValidationUtility.ThrowOnNull(RepudiationData, "RepudiationData"); ArgumentValidationUtility.ThrowOnNull(AmendmentRequestData, "AmendmentRequestData"); ArgumentValidationUtility.ThrowOnNull(SimpleLookupItemData, "SimpleLookupItemData"); ArgumentValidationUtility.ThrowOnNull(EpaData, "EpaData"); ArgumentValidationUtility.ThrowOnNull(PageService, "PageService"); } public int GetDefaultPageSize() { int size = 0; Int32.TryParse(Properties.Get(Constants.DefaultPageSize), out size); return size; } public void Audit(AppEventModel audit) { ArgumentValidationUtility.ThrowOnNull(audit, "audit"); Log.DebugFormat("Audit: {0}", audit); if (audit != null) { var a = EventData.Create(audit); SleisAuditLog.Info(String.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}", a.Id, a.Type, a.On, a.Username, a.Text, a.Data, a.RecordType, a.RecordId, a.Source)); } } public override string ToString() { return Utility.ReflectionUtility.GetPublicPropertiesString(this); } public AmendmentRequestModel GetAmendmentRequest(int id) { AmendmentRequestModel model = AmendmentRequestData.GetById(id); LoadAmendment(model); return model; } public RepudiateRequestModel GetRepudiationRequest(int id) { RepudiateRequestModel model = RepudiationData.GetById(id); LoadRepudiation(model); return model; } public List GetPendingAmendmentRequests() { List requests = AmendmentRequestData.GetPendingRequests(); //TODO: Might want to refactor this. Depends on how slow or quickly this loads. foreach (AmendmentRequestModel i in requests) { LoadAmendment(i); } return requests; } public List GetPendingRepudiations() { List requests = RepudiationData.GetPendingRepudiations(); //TODO: Might want to refactor this. Depends on how slow or quickly this loads. foreach (RepudiateRequestModel i in requests) { LoadRepudiation(i); } return requests; } public bool CloseRepudiation(RepudiateRequestModel repudiation, bool approved, string comment) { SubmissionDocumentModel submission = RepudiationData.GetById(repudiation.SubmissionId); var cor = RepudiationData.GetSingle(x => x.Submission.Id == repudiation.SubmissionId); cor.CreatedBy = UserData.GetById(cor.CreatedBy.Id); //update necessary fields. submission.Status = approved ? SubmissionDocumentStatus.Repudiated : SubmissionDocumentStatus.Submitted; repudiation.ClosedByUserId = SessionUtility.CurrentUser.Id; repudiation.ClosedDate = DateTime.Now; repudiation.Comment = comment; RepudiationData.Update(repudiation); RepudiationData.Update(submission); //Send email updat to user Dictionary emailArgs = new Dictionary(); emailArgs.Add("RequesterName", repudiation.RequestedByUser.FullName); emailArgs.Add("Approved", approved); emailArgs.Add("Comment", comment); emailArgs.Add("ReportYear", repudiation.Report.Number); emailArgs.Add("SubmissionConfirmationNumber", submission.Number); EmailUtility.SendArgs(repudiation.RequestedByUser.Email +"," + cor.CreatedBy.Email, AgencyResponseToRepudiationEmailTemplate, emailArgs); Audit(new AppEventModel(EventType.Audit, SessionUtility.CurrentUser.Email, "Report repudiation approved: " + approved.ToString() + "Submission Number: " + submission.Number, HttpContext.Current.Request.UserHostAddress)); return true; } public bool CloseAmendment(AmendmentRequestModel amendment, bool approved, string comment) { amendment.ClosedByUserId = SessionUtility.CurrentUser.Id; amendment.ClosedDate = DateTime.Now; amendment.Comment = comment; amendment.RequestApprovedIndicator = approved ? 1 : 0; if (approved) { /* Set M_AGN_RPT.RPT_LOAD_DATE = NULL, RPT_EIS_SUBM_DATE = NULL, RPT_COMPLETE_DATE = NULL for the AGN_RPT_ID from the M_AMEND_RQST Set P_FAC_EMIS_RPT.RPT_SUBM_DATE = NULL, RPT_SUBM_IND = 0 for the AGN_RPT_ID from the M_AMEND_RQST */ AgencyReport agencyReport = RepudiationData.GetById(amendment.ReportId); agencyReport.LoadDate = null; agencyReport.EisSubmissionDate = null; agencyReport.CompleteDate = null; RepudiationData.SaveOrUpdate(agencyReport); PublicReportModel publicReport = RepudiationData.GetSingle(r => r.ReportId == agencyReport.Id); publicReport.ReportSubmissionDate = null; publicReport.SubmittedIndicator = 0; RepudiationData.SaveOrUpdate(publicReport); } AmendmentRequestData.SaveOrUpdate(amendment); //Send email update to user. Dictionary emailArgs = new Dictionary(); emailArgs.Add("RequesterName", amendment.RequestedByUser.FullName); emailArgs.Add("Approved", approved); emailArgs.Add("Comment", comment); emailArgs.Add("ReportYear", amendment.Report.Number); EmailUtility.SendArgs(amendment.RequestedByUser.Email, AgencyResponseToAmendmentEmailTemplate, emailArgs); Audit(new AppEventModel(EventType.Audit, SessionUtility.CurrentUser.Email, "Report amendment approved: " + approved.ToString(), HttpContext.Current.Request.UserHostAddress)); return true; } private void LoadAmendment(AmendmentRequestModel amendment) { amendment.Report = AmendmentRequestData.GetSingle(r => r.Id == amendment.ReportId); amendment.RequestedByUser = AmendmentRequestData.GetSingle(u => u.Id == amendment.RequestByUserId); amendment.Facility = AmendmentRequestData.GetSingle(f => f.Id == amendment.Report.FacilityId); using (ISession session = FacilityData.GetSession()) { AgencyReport.LoadReportStatus(session, amendment.Report); } } private void LoadRepudiation(RepudiateRequestModel repudiation) { SubmissionDocumentModel submission = RepudiationData.GetSingle(s => s.Id == repudiation.SubmissionId); repudiation.Report = RepudiationData.GetSingle(r => r.Id == submission.ReportId); repudiation.RequestedByUser = RepudiationData.GetSingle(u => u.Id == repudiation.RequestByUserId); repudiation.Facility = RepudiationData.GetSingle(f => f.Id == repudiation.Report.FacilityId); using (ISession session = FacilityData.GetSession()) { AgencyReport.LoadReportStatus(session, repudiation.Report); } } public int GetPendingRequestsCount() { return AmendmentRequestData.GetPendingRequestsCount(); } public int GetPendingRepudiationsCount() { return RepudiationData.GetPendingRepudiationsCount(); } public List GetCustomFields(int id, int reportYear, CustomFieldEntityType entityType) where T : CustomFieldEntityValue { List customFields = new List(); //Get all custom fields for this type of identity foreach (CustomFieldModel field in CustomFieldData.Get(entityType)) { //Create an instance of the custom field view CustomFieldView fieldView = new CustomFieldView(field); //Set field vuew value in case this is an edit fieldView.Value = CustomFieldValueData.Get(id, fieldView.Field.Id); if ( (field.LastReportingYear == 0) || //End year has not been set (field.LastReportingYear >= reportYear) || //End year >= reporting year (!fieldView.ValueIsNullOrEmpty) //Regardless of the reporting year, if the value is there ) { //if the value has not been set if (fieldView.Value == null) { fieldView.Value = new CustomFieldEntityValue(); if (field.Type == CustomFieldDataType.Boolean) { fieldView.Value.FieldValue.Value = "N"; } } customFields.Add(fieldView); } } return customFields; } public void GenerateZip(FileStream[] fileStreams, Stream outputStream) { using (ZipFile zip = new ZipFile()) { foreach (FileStream f in fileStreams) { zip.AddFileStream(f.Name, "directoryPath", f); } zip.Save(outputStream); } } public List GetSimpleLookupItemByCustomQuery(string queryName, string searchTerm, int facilityId=0, int reportId=0) { return SimpleLookupItemData.GetByCustomQuery(queryName, searchTerm, facilityId, reportId); } public List GetSimpleLookupItemForScc(string queryName, string levelOne, string levelTwo, string levelThree, int year) { return SimpleLookupItemData.GetByCustomQueryForScc(queryName, levelOne, levelTwo, levelThree, year); } /* public bool IsDuplicateIdentifier(int entityId, string entityIdentifier, ISession session) where Obj : IIdentifiable { return BaseData.Exists(x => x.Id != entityId && x.Identifier == entityIdentifier, session); } */ protected void SaveCustomFields(List customFields, int entityId, ISession session) where TValue : CustomFieldEntityValue, new() { if (customFields != null) { foreach (CustomFieldView customFeild in customFields) { //TODO: There has to be a better way, right? // Otherwise we have to create a new DAO for each one of the 12 custo field tables TValue val = customFeild.Value.Convert(); val.EntityId = entityId; val.FieldValue.CustomFieldId = customFeild.Field.Id; session.SaveOrUpdate(val); } } } protected void DeleteCustomFieldsForEntity(int parentEntityId, int reportId, CustomFieldEntityType type, ISession session) where T : CustomFieldEntityValue { List customFields = GetCustomFields(parentEntityId, reportId, type); foreach (CustomFieldView customFeild in customFields) { EmissionUnitCustomFieldValue val = customFeild.Value.Convert(); val.EntityId = parentEntityId; val.FieldValue.CustomFieldId = customFeild.Field.Id; CustomFieldValueData.Delete(session, val); } } } }