static string ProcessIncidents() { PSsqmEntities entities = new PSsqmEntities(); SETTINGS setting = null; int workdays = 7; int rollupMonthsAhead = 0; string nextStep = ""; DateTime fromDate = DateTime.UtcNow.AddMonths(-11); // set the incident 'select from' date. TODO: get this from SETTINGS table // set end date to end of current month to clear spurrious entries ? DateTime rollupToDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.DaysInMonth(DateTime.UtcNow.Year, DateTime.UtcNow.Month)); WriteLine("INCIDENT Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy")); List <SETTINGS> sets = SQMSettings.SelectSettingsGroup("AUTOMATE", ""); // ABW 20140805 try { setting = sets.Where(x => x.SETTING_CD == "ROLLUP_WORKDAYS").FirstOrDefault(); if (setting != null && !string.IsNullOrEmpty(setting.VALUE)) { if (!int.TryParse(setting.VALUE, out workdays)) { workdays = 7; } } setting = sets.Where(x => x.SETTING_CD == "ROLLUP_NEXTPAGE").FirstOrDefault(); if (setting != null && !string.IsNullOrEmpty(setting.VALUE) && setting.VALUE.Length > 1) { nextStep = setting.VALUE; } // fetch all incidents occurring after the minimum reporting date List <INCIDENT> incidentList = (from i in entities.INCIDENT.Include("INCFORM_INJURYILLNESS") where i.ISSUE_TYPE_ID != (decimal)EHSIncidentTypeId.PreventativeAction && i.INCIDENT_DT >= fromDate && i.DETECT_PLANT_ID > 0 select i).OrderBy(l => l.DETECT_PLANT_ID).ThenBy(l => l.INCIDENT_DT).ToList(); List <PLANT> plantList = SQMModelMgr.SelectPlantList(entities, 1, 0); PLANT plant = null; // fetch all the plant accounting records for the target timespan DateTime minDate = incidentList.Select(l => l.INCIDENT_DT).Min(); minDate = minDate.AddMonths(-1); PLANT_ACCOUNTING pa = null; List <PLANT_ACCOUNTING> paList = (from a in entities.PLANT_ACCOUNTING where EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) >= minDate && EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) <= rollupToDate select a).OrderBy(l => l.PLANT_ID).ThenBy(l => l.PERIOD_YEAR).ThenBy(l => l.PERIOD_MONTH).ToList(); List <EHSIncidentTimeAccounting> summaryList = new List <EHSIncidentTimeAccounting>(); foreach (INCIDENT incident in incidentList) { WriteLine("Incident ID: " + incident.INCIDENT_ID.ToString() + " Occur Date: " + Convert.ToDateTime(incident.INCIDENT_DT).ToShortDateString()); incident.INCFORM_CAUSATION.Load(); if (incident.ISSUE_TYPE_ID == (decimal)EHSIncidentTypeId.InjuryIllness) { incident.INCFORM_LOSTTIME_HIST.Load(); } plant = plantList.Where(l => l.PLANT_ID == (decimal)incident.DETECT_PLANT_ID).FirstOrDefault(); summaryList = EHSIncidentMgr.SummarizeIncidentAccounting(summaryList, EHSIncidentMgr.CalculateIncidentAccounting(incident, plant.LOCAL_TIMEZONE, workdays)); } plant = null; PLANT_ACTIVE pact = null; DateTime periodDate; foreach (PLANT_ACCOUNTING pah in paList.OrderBy(l => l.PLANT_ID).ToList()) { if (pact == null || pact.PLANT_ID != pah.PLANT_ID) { pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == pah.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault(); } //if (pact != null && pact.EFF_END_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date) if (pact != null && pact.EFF_START_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date) { pah.TIME_LOST = pah.TOTAL_DAYS_RESTRICTED = 0; pah.TIME_LOST_CASES = pah.RECORDED_CASES = pah.FIRST_AID_CASES = 0; } } plant = null; pact = null; foreach (EHSIncidentTimeAccounting period in summaryList.OrderBy(l => l.PlantID).ThenBy(l => l.PeriodYear).ThenBy(l => l.PeriodMonth).ToList()) { if (plant == null || plant.PLANT_ID != period.PlantID) { plant = plantList.Where(l => l.PLANT_ID == period.PlantID).FirstOrDefault(); pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault(); } periodDate = new DateTime(period.PeriodYear, period.PeriodMonth, 1); if (pact != null && pact.EFF_START_DATE.HasValue && periodDate >= pact.EFF_START_DATE) { // write PLANT_ACCOUNTING metrics if ((pa = paList.Where(l => l.PLANT_ID == period.PlantID && l.PERIOD_YEAR == period.PeriodYear && l.PERIOD_MONTH == period.PeriodMonth).FirstOrDefault()) == null) { paList.Add((pa = new PLANT_ACCOUNTING())); pa.PLANT_ID = period.PlantID; pa.PERIOD_YEAR = period.PeriodYear; pa.PERIOD_MONTH = period.PeriodMonth; } pa.TIME_LOST = period.LostTime; pa.TOTAL_DAYS_RESTRICTED = period.RestrictedTime; pa.TIME_LOST_CASES = period.LostTimeCase; pa.RECORDED_CASES = period.RecordableCase; pa.FIRST_AID_CASES = period.FirstAidCase; pa.LAST_UPD_DT = DateTime.UtcNow; pa.LAST_UPD_BY = "automated"; EHSModel.UpdatePlantAccounting(entities, pa); } } WriteLine("INCIDENT Rollup Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy")); } catch (Exception ex) { WriteLine("INCIDENT RollUp Error: " + ex.ToString()); } return(nextStep); }
public static void SaveMonthlyData(decimal plantID, DateTime day, Dictionary <string, string> allData) { using (var entities = new PSsqmEntities()) { var measures = from m in entities.EHS_MEASURE where m.MEASURE_CATEGORY == "SAFE" && m.MEASURE_SUBCATEGORY == "SAFE1" && m.STATUS == "A" && m.FREQUENCY == "M" select new { m.MEASURE_ID, m.DATA_TYPE }; var startOfMonth = new DateTime(day.Year, day.Month, 1); foreach (var measure in measures) { string text = allData[measure.MEASURE_ID.ToString()]; bool hasText = !string.IsNullOrWhiteSpace(text); // We determine if we need to add a new entry into the database by looking for if there is any data. bool addNew = true; var data = entities.EHS_DATA.FirstOrDefault(d => EntityFunctions.TruncateTime(d.DATE) == startOfMonth.Date && d.PLANT_ID == plantID && d.MEASURE_ID == measure.MEASURE_ID); if (data != null) { addNew = false; // Check if this was inserted by an automated process, and ignore any changes if so. if (!data.UPDATE_IND.HasValue || data.UPDATE_IND.Value == 0) { // If we had some text in the RadTextBox, then we'll update the entry, otherwise we'll delete it. if (hasText) { if (measure.DATA_TYPE == "V" || measure.DATA_TYPE == "F") { string newValue = Regex.Replace(text, "[^0-9]", ""); data.VALUE = decimal.Parse(newValue); } else if (measure.DATA_TYPE == "A" || measure.DATA_TYPE == "Y") { data.ATTRIBUTE = text; } } else { entities.DeleteObject(data); } } } // This will only add a new entry if there was no entry found already and we had some text in the RadTextBox. if (addNew && hasText) { var newData = new EHS_DATA() { MEASURE_ID = measure.MEASURE_ID, PLANT_ID = plantID, DATE = startOfMonth }; if (measure.DATA_TYPE == "V") { string newValue = Regex.Replace(text, "[^0-9]", ""); newData.VALUE = decimal.Parse(newValue); } else if (measure.DATA_TYPE == "A" || measure.DATA_TYPE == "Y") { newData.ATTRIBUTE = text; } entities.EHS_DATA.AddObject(newData); } } // Save the changes we made to the database. This has to be done before the Plant Accounting stuff so there is data to find. entities.SaveChanges(); // Add the time worked and time lost items to the Plant Accounting table. var dataTimeWorked = entities.EHS_DATA.FirstOrDefault(d => EntityFunctions.TruncateTime(d.DATE) == startOfMonth.Date && d.PLANT_ID == plantID && d.EHS_MEASURE.MEASURE_CD == "S60002"); var dataTimeLost = entities.EHS_DATA.FirstOrDefault(d => EntityFunctions.TruncateTime(d.DATE) == startOfMonth.Date && d.PLANT_ID == plantID && d.EHS_MEASURE.MEASURE_CD == "S60001"); var pa = EHSModel.LookupPlantAccounting(entities, plantID, day.Year, day.Month, true); pa.TIME_WORKED = dataTimeWorked == null ? null : dataTimeWorked.VALUE; pa.TIME_LOST = dataTimeLost == null ? null : dataTimeLost.VALUE; EHSModel.UpdatePlantAccounting(entities, pa); } }
public static void SaveDailyData(decimal plantID, DateTime day, Dictionary <string, Dictionary <string, dynamic> > allData) { using (var entities = new PSsqmEntities()) { var measures = from m in entities.EHS_MEASURE where m.MEASURE_CATEGORY == "SAFE" && m.MEASURE_SUBCATEGORY == "SAFE1" && m.STATUS == "A" && m.FREQUENCY == "D" select new { m.MEASURE_ID, m.DATA_TYPE }; var startOfWeek = FirstDayOfWeek(day, calendar, calendarWeekRule, firstDayOfWeek); var currentDay = startOfWeek; for (int i = 0; i < 7; ++i, currentDay = currentDay.AddDays(1)) { string dayName = currentDay.ToString("ddd"); var dayData = entities.EHS_DATA.Where(d => EntityFunctions.TruncateTime(d.DATE) == currentDay.Date && d.PLANT_ID == plantID); foreach (var measure in measures) { bool measureIsValue = measure.DATA_TYPE == "V" || measure.DATA_TYPE == "F" || measure.DATA_TYPE == "O"; var measure_data = allData[dayName + "|" + measure.MEASURE_ID]; string text = measure_data["value"]; bool hasText = !string.IsNullOrWhiteSpace(text); // We determine if we need to add a new entry into the database by looking for if there is any data. bool addNew = true; if (dayData.Any()) { var data = dayData.FirstOrDefault(d => d.MEASURE_ID == measure.MEASURE_ID); if (data != null) { addNew = false; // Check if this was inserted by an automated process, and ignore any changes if so. if (!data.UPDATE_IND.HasValue || data.UPDATE_IND.Value == 0) { // If we had some text in the RadTextBox, then we'll update the entry, otherwise we'll delete it. if (hasText) { if (measureIsValue) { data.VALUE = decimal.Parse(text); } else if (measure.DATA_TYPE == "A" || measure.DATA_TYPE == "Y") { data.ATTRIBUTE = text; } if (measure_data.ContainsKey("ordinal")) { UpdateOrdinalData(entities, data.DATA_ID, measure_data["ordinal"]); } } else { entities.DeleteObject(data); } } } } // This will only add a new entry if there was no entry found already and we had some text in the RadTextBox. if (addNew && hasText) { var newData = new EHS_DATA() { MEASURE_ID = measure.MEASURE_ID, PLANT_ID = plantID, DATE = currentDay }; if (measureIsValue) { newData.VALUE = decimal.Parse(text); } else if (measure.DATA_TYPE == "A" || measure.DATA_TYPE == "Y") { newData.ATTRIBUTE = text; } entities.EHS_DATA.AddObject(newData); if (measure_data.ContainsKey("ordinal")) { AddOrdinalData(entities, newData, measure_data["ordinal"]); } } } } // Save the changes we made to the database. This has to be done before the Plant Accounting stuff so there is data to find. entities.SaveChanges(); // Add the recorded cases and time lost cases to the Plant Accounting table. var endOfWeek = startOfWeek.AddDays(6); DateTime startOfMonth, startOfNextMonth; PLANT_ACCOUNTING pa; // This checks for a week that crosses over a month. if (startOfWeek.Month != endOfWeek.Month) { startOfMonth = new DateTime(startOfWeek.Year, startOfWeek.Month, 1); startOfNextMonth = startOfMonth.AddMonths(1); pa = EHSModel.LookupPlantAccounting(entities, plantID, startOfMonth.Year, startOfMonth.Month, true); pa.RECORDED_CASES = entities.EHS_DATA.Where(d => EntityFunctions.TruncateTime(d.DATE) >= startOfMonth.Date && EntityFunctions.TruncateTime(d.DATE) < startOfNextMonth && d.PLANT_ID == plantID && d.EHS_MEASURE.MEASURE_CD == "S20004").Sum(o => o.VALUE) ?? null; pa.TIME_LOST_CASES = entities.EHS_DATA.Where(d => EntityFunctions.TruncateTime(d.DATE) >= startOfMonth.Date && EntityFunctions.TruncateTime(d.DATE) < startOfNextMonth && d.PLANT_ID == plantID && d.EHS_MEASURE.MEASURE_CD == "S20005").Sum(o => o.VALUE) ?? null; EHSModel.UpdatePlantAccounting(entities, pa, false); } startOfMonth = new DateTime(endOfWeek.Year, endOfWeek.Month, 1); startOfNextMonth = startOfMonth.AddMonths(1); pa = EHSModel.LookupPlantAccounting(entities, plantID, startOfMonth.Year, startOfMonth.Month, true); pa.RECORDED_CASES = entities.EHS_DATA.Where(d => EntityFunctions.TruncateTime(d.DATE) >= startOfMonth.Date && EntityFunctions.TruncateTime(d.DATE) < startOfNextMonth && d.PLANT_ID == plantID && d.EHS_MEASURE.MEASURE_CD == "S20004").Sum(o => o.VALUE) ?? null; pa.TIME_LOST_CASES = entities.EHS_DATA.Where(d => EntityFunctions.TruncateTime(d.DATE) >= startOfMonth.Date && EntityFunctions.TruncateTime(d.DATE) < startOfNextMonth && d.PLANT_ID == plantID && d.EHS_MEASURE.MEASURE_CD == "S20005").Sum(o => o.VALUE) ?? null; EHSModel.UpdatePlantAccounting(entities, pa); } }
private static void UpdateIncidentLostTimeDays(INCIDENT incident, string someReturnDate) { var entities = new PSsqmEntities(); DateTime startDate = incident.INCIDENT_DT.AddDays(1); // Default to current date if no actual return date set DateTime endDate; try { // Try to parse return date (expected or actual) endDate = DateTime.Parse(someReturnDate, CultureInfo.GetCultureInfo("en-US")); } catch { return; } if (startDate >= endDate) { return; } DateTime incDate = startDate; decimal plantId = (decimal)incident.DETECT_PLANT_ID; while (incDate < endDate || (incDate.Month == endDate.Month && incDate.Year == endDate.Year)) { int lostTimeThisMonth = 0; int daysInThisMonth = DateTime.DaysInMonth(incDate.Year, incDate.Month); DateTime monthStart = new DateTime(incDate.Year, incDate.Month, 1, 0, 0, 0); // first second of the month DateTime monthEnd = monthStart.AddDays(daysInThisMonth).Subtract(new TimeSpan(0, 0, 1)); // last second of the month if (startDate < monthStart && endDate > monthEnd) { // Incident starts before and ends after this month lostTimeThisMonth = daysInThisMonth; } else if (startDate >= monthStart && endDate > monthEnd) { // Incident starts but doesn't end this month lostTimeThisMonth = (int)Math.Ceiling((monthEnd - startDate).TotalDays); } else if (startDate < monthStart && endDate <= monthEnd) { // Incident ends but didn't start this month lostTimeThisMonth = (int)Math.Ceiling((endDate - monthStart).TotalDays); } else if (endDate > startDate) { // Incident both starts and ends this month lostTimeThisMonth = (int)Math.Ceiling((endDate - startDate).TotalDays); } var pa = EHSModel.LookupPlantAccounting(entities, plantId, incDate.Year, incDate.Month, true); pa.TIME_LOST += lostTimeThisMonth; EHSModel.UpdatePlantAccounting(entities, pa); incDate = incDate.AddMonths(1); } }
public static void RollupPlantAccounting(decimal initialPlantId, decimal finalPlantId) { var entities = new PSsqmEntities(); var plantIds = new HashSet <decimal> { initialPlantId, finalPlantId }; plantIds.Remove(0); // Default to January 1 of current year if web.config value not found DateTime startDate = new DateTime(DateTime.Now.Year, 1, 1); string plantAccountingCalcStartDate = System.Configuration.ConfigurationManager.AppSettings["PlantAccountingCalcStartDate"]; if (!string.IsNullOrEmpty(plantAccountingCalcStartDate)) { DateTime result; if (DateTime.TryParse(plantAccountingCalcStartDate, out result)) { startDate = result; } } // Step 1 - zero out incident plant accounting values or create new records foreach (decimal pid in plantIds) { DateTime incDate = startDate; while (incDate < DateTime.Now || (incDate.Month == DateTime.Now.Month && incDate.Year == DateTime.Now.Year)) { var pa = EHSModel.LookupPlantAccounting(entities, pid, incDate.Year, incDate.Month, true); pa.RECORDED_CASES = 0; pa.TIME_LOST_CASES = 0; pa.TIME_LOST = 0; EHSModel.UpdatePlantAccounting(entities, pa); incDate = incDate.AddMonths(1); } } // Step 2 - update records incident by incident foreach (decimal pid in plantIds) { DateTime incDate = startDate; while (incDate < DateTime.Now || (incDate.Month == DateTime.Now.Month && incDate.Year == DateTime.Now.Year)) { var pa = EHSModel.LookupPlantAccounting(entities, pid, incDate.Year, incDate.Month, true); var incidentList = EHSIncidentMgr.SelectInjuryIllnessIncidents(pid, incDate); // this might be wrong ?? foreach (INCIDENT incident in incidentList) { string recordableAnswerValue = EHSIncidentMgr.SelectIncidentAnswer(incident, (decimal)EHSQuestionId.Recordable); if (!string.IsNullOrEmpty(recordableAnswerValue) && recordableAnswerValue == "Yes") { pa.RECORDED_CASES++; } string ltcAnswerValue = EHSIncidentMgr.SelectIncidentAnswer(incident, (decimal)EHSQuestionId.LostTimeCase); if (!string.IsNullOrEmpty(ltcAnswerValue) && ltcAnswerValue == "Yes") { pa.TIME_LOST_CASES++; } string someReturnDate = ""; // expected or actual return date string erdAnswerValue = EHSIncidentMgr.SelectIncidentAnswer(incident, (decimal)EHSQuestionId.ExpectedReturnDate); if (!string.IsNullOrEmpty(erdAnswerValue)) { someReturnDate = erdAnswerValue; } string ardAnswerValue = EHSIncidentMgr.SelectIncidentAnswer(incident, (decimal)EHSQuestionId.ActualReturnDate); if (!string.IsNullOrEmpty(ardAnswerValue)) { someReturnDate = ardAnswerValue; } if (!string.IsNullOrEmpty(someReturnDate)) { UpdateIncidentLostTimeDays(incident, someReturnDate); } } EHSModel.UpdatePlantAccounting(entities, pa); incDate = incDate.AddMonths(1); } } }
protected void Page_Load(object sender, EventArgs e) { string pageMode = ""; if (!string.IsNullOrEmpty(Request.QueryString["m"])) // .../...aspx?p=xxxxx { pageMode = Request.QueryString["m"].ToLower(); // page mode (web == running manually from the menu) } if (IsPostBack) { if (pageMode != "web") { System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true); } return; } output = new StringBuilder(); SETTINGS setting = null; bool validIP = true; int workdays = 7; string pageURI = HttpContext.Current.Request.Url.AbsoluteUri; string nextPage = ""; PLANT_ACCOUNTING pa = null; fromDate = DateTime.UtcNow.AddMonths(-11); // set the incident 'select from' date. TODO: get this from SETTINGS table // set end date to end of current month to clear spurrious entries ? DateTime rollupToDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.DaysInMonth(DateTime.UtcNow.Year, DateTime.UtcNow.Month)); WriteLine("Incident Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy")); WriteLine(pageURI); try { string currentIP = GetIPAddress(); List <SETTINGS> sets = SQMSettings.SelectSettingsGroup("AUTOMATE", ""); // ABW 20140805 string strValidIP = sets.Find(x => x.SETTING_CD == "ValidIP").VALUE.ToString(); setting = sets.Where(x => x.SETTING_CD == "ROLLUP_WORKDAYS").FirstOrDefault(); if (setting != null && !string.IsNullOrEmpty(setting.VALUE)) { if (!int.TryParse(setting.VALUE, out workdays)) { workdays = 7; } } setting = sets.Where(x => x.SETTING_CD == "ROLLUP_NEXTPAGE").FirstOrDefault(); if (setting != null && !string.IsNullOrEmpty(setting.VALUE) && setting.VALUE.Length > 1) { nextPage = setting.VALUE; } /* * int rollupMonthsAhead = 0; * setting = sets.Where(x => x.SETTING_CD == "ROLLUP_MONTHS_AHEAD").FirstOrDefault(); * if (setting != null && !string.IsNullOrEmpty(setting.VALUE)) * { * int.TryParse(setting.VALUE, out rollupMonthsAhead); * rollupToDate = rollupToDate.AddMonths(rollupMonthsAhead); * } */ /* * if (strValidIP.Equals(currentIP)) * { * WriteLine("Main Incident RollUp being accessed from a valid IP address " + currentIP); * validIP = true; * * if (Request.QueryString["validation"] != null) * { * if (Request.QueryString["validation"].ToString().Equals("Vb12M11a4")) * validIP = true; * } * else * { * WriteLine("Main Incident RollUp requested from incorrect source."); * validIP = false; * } * } * else * { * WriteLine("Main Incident RollUp being accessed from invalid IP address " + currentIP); * validIP = false; * } */ } catch (Exception ex) { validIP = false; WriteLine("Main Incident RollUp Error validating IP Address: " + ex.ToString()); } // make sure this code is NOT moved to production //validIP = true; if (!validIP) { WriteLine("Main Incident RollUp Invalid IP Address"); ltrStatus.Text = output.ToString().Replace("\n", "<br/>"); WriteLogFile(); if (pageMode != "web") { System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true); } return; } try { PSsqmEntities entities = new PSsqmEntities(); // fetch all incidents occurring after the minimum reporting date List <INCIDENT> incidentList = (from i in entities.INCIDENT.Include("INCFORM_INJURYILLNESS") where i.ISSUE_TYPE_ID != (decimal)EHSIncidentTypeId.PreventativeAction && i.INCIDENT_DT >= fromDate && i.DETECT_PLANT_ID > 0 select i).OrderBy(l => l.DETECT_PLANT_ID).ThenBy(l => l.INCIDENT_DT).ToList(); List <PLANT> plantList = SQMModelMgr.SelectPlantList(entities, 1, 0); PLANT plant = null; // fetch all the plant accounting records for the target timespan DateTime minDate = incidentList.Select(l => l.INCIDENT_DT).Min(); minDate = minDate.AddMonths(-1); List <PLANT_ACCOUNTING> paList = (from a in entities.PLANT_ACCOUNTING where EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) >= minDate && EntityFunctions.CreateDateTime(a.PERIOD_YEAR, a.PERIOD_MONTH, 1, 0, 0, 0) <= rollupToDate select a).OrderBy(l => l.PLANT_ID).ThenBy(l => l.PERIOD_YEAR).ThenBy(l => l.PERIOD_MONTH).ToList(); List <EHSIncidentTimeAccounting> summaryList = new List <EHSIncidentTimeAccounting>(); foreach (INCIDENT incident in incidentList) { WriteLine("Incident ID: " + incident.INCIDENT_ID.ToString() + " Occur Date: " + Convert.ToDateTime(incident.INCIDENT_DT).ToShortDateString()); incident.INCFORM_CAUSATION.Load(); if (incident.ISSUE_TYPE_ID == (decimal)EHSIncidentTypeId.InjuryIllness) { incident.INCFORM_LOSTTIME_HIST.Load(); } plant = plantList.Where(l => l.PLANT_ID == (decimal)incident.DETECT_PLANT_ID).FirstOrDefault(); summaryList = EHSIncidentMgr.SummarizeIncidentAccounting(summaryList, EHSIncidentMgr.CalculateIncidentAccounting(incident, plant.LOCAL_TIMEZONE, workdays)); } plant = null; PLANT_ACTIVE pact = null; DateTime periodDate; foreach (PLANT_ACCOUNTING pah in paList.OrderBy(l => l.PLANT_ID).ToList()) { if (pact == null || pact.PLANT_ID != pah.PLANT_ID) { pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == pah.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault(); } //if (pact != null && pact.EFF_END_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date) if (pact != null && pact.EFF_START_DATE.HasValue && new DateTime(pah.PERIOD_YEAR, pah.PERIOD_MONTH, 1).Date >= ((DateTime)pact.EFF_START_DATE).Date) { pah.TIME_LOST = pah.TOTAL_DAYS_RESTRICTED = 0; pah.TIME_LOST_CASES = pah.RECORDED_CASES = pah.FIRST_AID_CASES = 0; } } plant = null; pact = null; foreach (EHSIncidentTimeAccounting period in summaryList.OrderBy(l => l.PlantID).ThenBy(l => l.PeriodYear).ThenBy(l => l.PeriodMonth).ToList()) { if (plant == null || plant.PLANT_ID != period.PlantID) { plant = plantList.Where(l => l.PLANT_ID == period.PlantID).FirstOrDefault(); pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault(); } periodDate = new DateTime(period.PeriodYear, period.PeriodMonth, 1); if (pact != null && pact.EFF_START_DATE.HasValue && periodDate >= pact.EFF_START_DATE) { // write PLANT_ACCOUNTING metrics if ((pa = paList.Where(l => l.PLANT_ID == period.PlantID && l.PERIOD_YEAR == period.PeriodYear && l.PERIOD_MONTH == period.PeriodMonth).FirstOrDefault()) == null) { paList.Add((pa = new PLANT_ACCOUNTING())); pa.PLANT_ID = period.PlantID; pa.PERIOD_YEAR = period.PeriodYear; pa.PERIOD_MONTH = period.PeriodMonth; } pa.TIME_LOST = period.LostTime; pa.TOTAL_DAYS_RESTRICTED = period.RestrictedTime; pa.TIME_LOST_CASES = period.LostTimeCase; pa.RECORDED_CASES = period.RecordableCase; pa.FIRST_AID_CASES = period.FirstAidCase; pa.LAST_UPD_DT = DateTime.UtcNow; pa.LAST_UPD_BY = "automated"; EHSModel.UpdatePlantAccounting(entities, pa); } } } catch (Exception ex) { WriteLine("Main Incident RollUp Error - " + ex.ToString()); } WriteLine(""); WriteLine("Completed: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy")); ltrStatus.Text = output.ToString().Replace("\n", "<br/>"); WriteLogFile(); try { if (!string.IsNullOrEmpty(nextPage)) { int s1 = pageURI.LastIndexOf('/'); int s2 = pageURI.LastIndexOf('.') > -1 ? pageURI.LastIndexOf('.') : pageURI.Length; string nextPageURI = pageURI.Substring(0, s1 + 1) + nextPage + pageURI.Substring(s2, pageURI.Length - s2); Response.Redirect(nextPageURI); } } catch (Exception ex) { output = new StringBuilder(); WriteLine("RollUp Redirect Error - " + ex.ToString()); WriteLogFile(); } if (pageMode != "web") { System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "closePage", "window.onunload = CloseWindow();", true); } }