Example #1
0
        protected void rgPlantActive_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                try
                {
                    GridDataItem item        = (GridDataItem)e.Item;
                    PLANT_ACTIVE plantActive = (PLANT_ACTIVE)e.Item.DataItem;

                    HiddenField hf = (HiddenField)item.FindControl("hPlantID");

                    Label lbl = (Label)item.FindControl("lblModule");
                    lbl.Text = ((TaskRecordType)plantActive.RECORD_TYPE).ToString();

                    RadMonthYearPicker rdp = (RadMonthYearPicker)item.FindControl("rdpStartDate");
                    rdp.SelectedDate = plantActive.EFF_START_DATE.HasValue ? plantActive.EFF_START_DATE : null;

                    rdp = (RadMonthYearPicker)item.FindControl("rdpStopDate");
                    rdp.SelectedDate = plantActive.EFF_END_DATE.HasValue ? plantActive.EFF_END_DATE : null;

                    CheckBox cb = (CheckBox)item.FindControl("cbEnableEmail");
                    cb.Checked = (bool)plantActive.ENABLE_EMAIL;

                    cb         = (CheckBox)item.FindControl("cbViewInactiveHist");
                    cb.Checked = (bool)plantActive.ENABLE_INACTIVE_HIST;
                }
                catch
                {
                }
            }
        }
Example #2
0
        protected void lnkPlantView_Click(object sender, EventArgs e)
        {
            PLANT plant = (PLANT)SessionManager.EffLocation.Plant;

            TextBox tbPlantName    = (TextBox)hfBase.FindControl("tbPlantName"); tbPlantName.Text = plant.PLANT_NAME;
            TextBox tbPlantDesc    = (TextBox)hfBase.FindControl("tbPlantDesc"); tbPlantDesc.Text = plant.DISP_PLANT_NAME;
            TextBox tbPlantLocCode = (TextBox)hfBase.FindControl("tbPlantLocCode"); tbPlantLocCode.Text = plant.DUNS_CODE;
            TextBox tbAltPlantCode = (TextBox)hfBase.FindControl("tbAltPlantCode"); tbAltPlantCode.Text = plant.ALT_DUNS_CODE;

            cbTrackFinData.Checked = (bool)plant.TRACK_FIN_DATA;
            cbTrackEWData.Checked  = (bool)plant.TRACK_EW_DATA;
            Label lblLastUpdate = (Label)hfBase.FindControl("lblPlantLastUpdate"); lblLastUpdate.Text = plant.LAST_UPD_BY;

            lblPlantLastUpdateDate.Text = SQMBasePage.FormatDate(WebSiteCommon.LocalTime((DateTime)plant.LAST_UPD_DT, SessionManager.UserContext.TimeZoneID), "d", false);
            // Label lblLastUpdateDate = (Label)hfBase.FindControl("lblPlantLastUpdateDate"); lblLastUpdateDate.Text = WebSiteCommon.LocalTime((DateTime)plant.LAST_UPD_DT, SessionManager.UserContext.TimeZoneID).ToString();

            LoadPlantSelects(plant);

            if (plant.ADDRESS != null)
            {
                ADDRESS address = plant.ADDRESS.FirstOrDefault();
                if (address != null)
                {
                    tbAddress1.Text = address.STREET1;
                    tbAddress2.Text = address.STREET2;
                    tbCity.Text     = address.CITY;
                    tbState.Text    = address.STATE_PROV;
                    tbPostal.Text   = address.POSTAL_CODE;
                }
            }

            int[] recList = new int[5] {
                30, 40, 45, 50, 90
            };
            PLANT_ACTIVE        pa = null;
            List <PLANT_ACTIVE> plantActiveList = new List <PLANT_ACTIVE>();

            foreach (int recType in recList)
            {
                PLANT_ACTIVE plantActive = new PLANT_ACTIVE();
                plantActive.PLANT_ID     = plant.PLANT_ID;
                plantActive.RECORD_TYPE  = recType;
                plantActive.ENABLE_EMAIL = true;
                if ((pa = plant.PLANT_ACTIVE.Where(p => p.RECORD_TYPE == recType).FirstOrDefault()) != null)
                {
                    plantActive.EFF_START_DATE       = pa.EFF_START_DATE;
                    plantActive.EFF_END_DATE         = pa.EFF_END_DATE;
                    plantActive.ENABLE_EMAIL         = pa.ENABLE_EMAIL;
                    plantActive.ENABLE_INACTIVE_HIST = pa.ENABLE_INACTIVE_HIST;
                }
                plantActiveList.Add(plantActive);
            }
            BindPlantActive(plantActiveList);

            LocalOrg().EditObject = plant;
        }
Example #3
0
        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);
        }
Example #4
0
        static string ProcessEHSData()
        {
            string nextStep = "";

            WriteLine("EHSDATA Rollup Started: " + DateTime.UtcNow.ToString("hh:mm MM/dd/yyyy"));

            List <SETTINGS> sets = SQMSettings.SelectSettingsGroup("AUTOMATE", "TASK");            // ABW 20140805

            try
            {
                using (var entities = new PSsqmEntities())
                {
                    long     updateIndicator = DateTime.UtcNow.Ticks;
                    SETTINGS setting         = null;

                    // get any AUTOMATE settings
                    sets = SQMSettings.SelectSettingsGroup("AUTOMATE", "TASK");

                    DateTime rollupFromDate = DateTime.UtcNow.AddMonths(-11);                           // this should be a setting
                    // 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));

                    /*
                     * 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);
                     * }
                     */

                    List <EHS_MEASURE> measureList = (from m in entities.EHS_MEASURE select m).ToList();

                    decimal plantManagerAuditsMeasureID        = measureList.First(m => m.MEASURE_CD == "S30003").MEASURE_ID;
                    decimal ehsAuditsMeasureID                 = measureList.First(m => m.MEASURE_CD == "S30001").MEASURE_ID;
                    decimal supervisorAuditsMeasureID          = measureList.First(m => m.MEASURE_CD == "S30002").MEASURE_ID;
                    decimal plantManagerAuditsCreatedMeasureID = measureList.First(m => m.MEASURE_CD == "S3C003").MEASURE_ID;
                    decimal ehsAuditsCreatedMeasureID          = measureList.First(m => m.MEASURE_CD == "S3C001").MEASURE_ID;
                    decimal supervisorAuditsCreatedMeasureID   = measureList.First(m => m.MEASURE_CD == "S3C002").MEASURE_ID;
                    decimal allAuditsCreatedMeasureID          = measureList.FirstOrDefault(m => m.MEASURE_CD == "S3C000").MEASURE_ID;
                    var     auditDailyMeasureIDs               = new List <decimal>()
                    {
                        plantManagerAuditsMeasureID,
                        ehsAuditsMeasureID,
                        supervisorAuditsMeasureID,
                    };
                    var auditMonthlyMeasureIDs = new List <decimal>()
                    {
                        plantManagerAuditsCreatedMeasureID,
                        ehsAuditsCreatedMeasureID,
                        supervisorAuditsCreatedMeasureID,
                        allAuditsCreatedMeasureID
                    };


                    decimal nearMissMeasureID            = measureList.First(m => m.MEASURE_CD == "S20002").MEASURE_ID;
                    decimal firstAidMeasureID            = measureList.First(m => m.MEASURE_CD == "S20003").MEASURE_ID;
                    decimal recordableMeasureID          = measureList.First(m => m.MEASURE_CD == "S20004").MEASURE_ID;
                    decimal lostTimeCaseMeasureID        = measureList.First(m => m.MEASURE_CD == "S20005").MEASURE_ID;
                    decimal fatalityMeasureID            = measureList.First(m => m.MEASURE_CD == "S20006").MEASURE_ID;
                    decimal otherIncidentsID             = measureList.First(m => m.MEASURE_CD == "S20001").MEASURE_ID;
                    decimal closedInvestigationMeasureID = measureList.First(m => m.MEASURE_CD == "S20007").MEASURE_ID;
                    var     incidentMeasureIDs           = new List <decimal>()
                    {
                        nearMissMeasureID,
                        firstAidMeasureID,
                        recordableMeasureID,
                        lostTimeCaseMeasureID,
                        fatalityMeasureID,
                        otherIncidentsID,
                        closedInvestigationMeasureID
                    };

                    decimal timeLostMeasureID         = entities.EHS_MEASURE.First(m => m.MEASURE_CD == "S60001").MEASURE_ID;
                    decimal timeRestrictedMeasureID   = entities.EHS_MEASURE.First(m => m.MEASURE_CD == "S60003").MEASURE_ID;
                    var     incidentMonthlyMeasureIDs = new List <decimal>()
                    {
                        timeLostMeasureID,
                        timeRestrictedMeasureID
                    };

                    decimal injuryIllnessIssueTypeID = entities.INCIDENT_TYPE.First(i => i.TITLE == "Injury/Illness").INCIDENT_TYPE_ID;
                    decimal nearMissIssueTypeID      = entities.INCIDENT_TYPE.First(i => i.TITLE == "Near Miss").INCIDENT_TYPE_ID;


                    List <PLANT> plantList = SQMModelMgr.SelectPlantList(entities, 1, 0).Where(l => l.STATUS == "A").ToList();
                    PLANT_ACTIVE pact      = null;

                    var createdAudits = (from a in entities.AUDIT where a.AUDIT_DT >= rollupFromDate && new decimal[3] {
                        1, 2, 3
                    }.Contains(a.AUDIT_TYPE_ID) select a).ToList();
                    //var incidents = (from i in entities.INCIDENT where i.INCIDENT_DT >= rollupFromDate && (i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID || i.ISSUE_TYPE_ID == nearMissIssueTypeID) select i).ToList();
                    var incidents = (from i in entities.INCIDENT.Include("INCFORM_INJURYILLNESS") where i.INCIDENT_DT >= rollupFromDate && (i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID || i.ISSUE_TYPE_ID == nearMissIssueTypeID) select i).ToList();

                    // AUDITS
                    foreach (var plant in plantList)
                    {
                        pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.Audit select a).SingleOrDefault();
                        if (pact != null && pact.EFF_START_DATE.HasValue)                               // plant is active
                        {
                            var auditsForPlant = createdAudits.Where(a => a.DETECT_PLANT_ID == plant.PLANT_ID && a.CURRENT_STATUS != "I");

                            // new timespan logic
                            DateTime fromDate = rollupFromDate > (DateTime)pact.EFF_START_DATE ? rollupFromDate : (DateTime)pact.EFF_START_DATE;
                            DateTime toDate   = pact.EFF_END_DATE.HasValue && (DateTime)pact.EFF_END_DATE < rollupToDate ? (DateTime)pact.EFF_END_DATE : rollupToDate;

                            WriteLine("AUDIT Rollup For Plant " + pact.PLANT_ID + "  from date = " + fromDate.ToShortDateString() + "  to date = " + toDate.ToShortDateString());

                            // loop by month to get audits created for month and then by day to calculate completions
                            for (DateTime dt = fromDate; dt <= toDate; dt = dt.AddMonths(1))
                            {
                                int plantManagerAuditsCreatedMonth = 0;
                                int ehsAuditsCreatedMonth          = 0;
                                int supervisorAuditsCreatedMonth   = 0;
                                int auditsCreatedMonth             = 0;

                                for (var currDate = new System.DateTime(dt.Year, dt.Month, 1); currDate <= new System.DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month)); currDate = currDate.AddDays(1))
                                {
                                    int plantManagerAudits = 0;
                                    int ehsAudits          = 0;
                                    int supervisorAudits   = 0;

                                    // fetch audits scheduled for this day
                                    var auditsForDay = auditsForPlant.Where(a => TruncateTime(a.AUDIT_DT) == currDate.Date);
                                    if (auditsForDay.Any())
                                    {
                                        auditsCreatedMonth             += auditsForDay.Count();
                                        plantManagerAuditsCreatedMonth += auditsForDay.Count(a => a.AUDIT_TYPE_ID == 1);
                                        ehsAuditsCreatedMonth          += auditsForDay.Count(a => a.AUDIT_TYPE_ID == 2);
                                        supervisorAuditsCreatedMonth   += auditsForDay.Count(a => a.AUDIT_TYPE_ID == 3);
                                    }
                                    // get audits scheduled for this day that have been completed
                                    var closedAuditsForDay = auditsForDay.Where(a => a.CLOSE_DATE_DATA_COMPLETE != null);
                                    if (closedAuditsForDay.Any())
                                    {
                                        plantManagerAudits = closedAuditsForDay.Count(a => a.AUDIT_TYPE_ID == 1);
                                        ehsAudits          = closedAuditsForDay.Count(a => a.AUDIT_TYPE_ID == 2);
                                        supervisorAudits   = closedAuditsForDay.Count(a => a.AUDIT_TYPE_ID == 3);
                                    }

                                    var dailyData = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, auditDailyMeasureIDs, true, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(dailyData, plantManagerAuditsMeasureID, plantManagerAudits, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(dailyData, ehsAuditsMeasureID, ehsAudits, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(dailyData, supervisorAuditsMeasureID, supervisorAudits, updateIndicator);
                                    foreach (var data in dailyData)
                                    {
                                        if (data.EntityState == EntityState.Detached && data.VALUE != 0)
                                        {
                                            entities.EHS_DATA.AddObject(data);
                                        }
                                        else if (data.EntityState != EntityState.Detached && data.VALUE == 0)
                                        {
                                            entities.DeleteObject(data);
                                        }
                                    }
                                }

                                var monthlyData = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, new DateTime(dt.Year, dt.Month, 1), auditMonthlyMeasureIDs, true, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, plantManagerAuditsCreatedMeasureID, plantManagerAuditsCreatedMonth, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, supervisorAuditsCreatedMeasureID, supervisorAuditsCreatedMonth, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, ehsAuditsCreatedMeasureID, ehsAuditsCreatedMonth, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(monthlyData, allAuditsCreatedMeasureID, auditsCreatedMonth, updateIndicator);
                                foreach (var data in monthlyData)
                                {
                                    if (data.EntityState == EntityState.Detached && data.VALUE != 0)
                                    {
                                        entities.EHS_DATA.AddObject(data);
                                    }
                                    else if (data.EntityState != EntityState.Detached && data.VALUE == 0)
                                    {
                                        entities.DeleteObject(data);
                                    }
                                }

                                entities.SaveChanges();
                            }
                        }
                        entities.SaveChanges();
                    }

                    // INCIDENTS
                    foreach (var plant in plantList)
                    {
                        pact = (from a in entities.PLANT_ACTIVE where a.PLANT_ID == plant.PLANT_ID && a.RECORD_TYPE == (int)TaskRecordType.HealthSafetyIncident select a).SingleOrDefault();
                        if (pact != null && pact.EFF_START_DATE.HasValue)                               // plant is active
                        {
                            var incidentsForPlant = incidents.Where(i => i.DETECT_PLANT_ID == plant.PLANT_ID);
                            //var minDate = new[] { pact.EFF_START_DATE, incidentsForPlant.Min(i => (DateTime?)i.INCIDENT_DT) }.Max();
                            //var maxDate = new[] { pact.EFF_END_DATE, incidentsForPlant.Max(i => (DateTime?)i.INCIDENT_DT) }.Min();
                            // new timespan logic
                            DateTime fromDate = rollupFromDate > (DateTime)pact.EFF_START_DATE ? rollupFromDate : (DateTime)pact.EFF_START_DATE;
                            DateTime toDate   = pact.EFF_END_DATE.HasValue && (DateTime)pact.EFF_END_DATE < rollupToDate ? (DateTime)pact.EFF_END_DATE : rollupToDate;

                            WriteLine("INCIDENT Rollup For Plant " + pact.PLANT_ID + "  from date = " + fromDate.ToShortDateString() + "  to date = " + toDate.ToShortDateString());

                            for (var currDate = fromDate; currDate <= toDate; currDate = currDate.AddDays(1))
                            {
                                int nearMisses           = 0;
                                int firstAidCases        = 0;
                                int recordables          = 0;
                                int lostTimeCases        = 0;
                                int fatalities           = 0;
                                int otherIncidents       = 0;
                                int closedInvestigations = 0;

                                var firstAidOrdinals = new Dictionary <string, Dictionary <string, int> >()
                                {
                                    { "type", null },
                                    { "bodyPart", null },
                                    { "rootCause", null },
                                    { "tenure", null },
                                    { "daysToClose", null }
                                };
                                var recordableOrdinals = new Dictionary <string, Dictionary <string, int> >()
                                {
                                    { "type", null },
                                    { "bodyPart", null },
                                    { "rootCause", null },
                                    { "tenure", null },
                                    { "daysToClose", null }
                                };

                                var incidentsForDay = incidentsForPlant.Where(i => TruncateTime(i.INCIDENT_DT) == currDate.Date);
                                //if (incidentsForDay.Any())
                                if (incidentsForDay.Count() > 0)
                                {
                                    var firstAidIncidents   = incidentsForDay.Where(i => i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.FIRST_AID);
                                    var recordableIncidents = incidentsForDay.Where(i => i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.RECORDABLE);
                                    otherIncidents = incidentsForDay.Where(i => i.ISSUE_TYPE_ID != injuryIllnessIssueTypeID).Count();
                                    // Basic data
                                    nearMisses    = incidentsForDay.Count(i => i.ISSUE_TYPE_ID == nearMissIssueTypeID);
                                    firstAidCases = firstAidIncidents.Count();
                                    recordables   = recordableIncidents.Count();
                                    lostTimeCases = incidentsForDay.Count(i => i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.LOST_TIME);
                                    fatalities    = incidentsForDay.Count(i =>
                                                                          i.ISSUE_TYPE_ID == injuryIllnessIssueTypeID && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.FATALITY.HasValue && i.INCFORM_INJURYILLNESS != null && i.INCFORM_INJURYILLNESS.FATALITY.Value);
                                    closedInvestigations = incidentsForDay.Count(i => i.CLOSE_DATE.HasValue);

                                    // First Aid ordinals
                                    // check which ordinal data we wish to capture
                                    SETTINGS setFirstAid = sets.Where(s => s.SETTING_CD == "FIRSTAID-ORDINALS").FirstOrDefault();
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("type"))
                                    {
                                        firstAidOrdinals["type"] = firstAidIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_TYPE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("bodyPart"))
                                    {
                                        firstAidOrdinals["bodyPart"] = firstAidIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_BODY_PART).ToDictionary(b => b.Key ?? "", b => b.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("rootCause"))
                                    {
                                        firstAidOrdinals["rootCause"] = firstAidIncidents.SelectMany(i => i.INCFORM_CAUSATION).GroupBy(c => c.CAUSEATION_CD).ToDictionary(c =>
                                                                                                                                                                          c.Key ?? "", c => c.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("tenure"))
                                    {
                                        firstAidOrdinals["tenure"] = firstAidIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.JOB_TENURE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setFirstAid != null && setFirstAid.VALUE.Contains("daysToClose"))
                                    {
                                        firstAidOrdinals["daysToClose"] = firstAidIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                                                                                                                     ((TimeSpan)(i.INCIDENT_DT - i.CLOSE_DATE)).Days).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                                                                                                                                                                                                                                   (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                                                                                                                                                                                                                                                                                                                                                                             x.Key ?? "", x => x.Count());

                                        /*
                                         * firstAidOrdinals["daysToClose"] = firstAidIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                         * EntityFunctions.DiffDays(i.INCIDENT_DT, i.CLOSE_DATE)).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                         * (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                         * x.Key ?? "", x => x.Count());
                                         */
                                    }

                                    // Recordable ordinals
                                    // check which ordinal data we wish to capture
                                    SETTINGS setRecordable = sets.Where(s => s.SETTING_CD == "RECORDABLE-ORDINALS").FirstOrDefault();
                                    if (setRecordable != null && setRecordable.VALUE.Contains("type"))
                                    {
                                        recordableOrdinals["type"] = recordableIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_TYPE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("bodyPart"))
                                    {
                                        recordableOrdinals["bodyPart"] = recordableIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.INJURY_BODY_PART).ToDictionary(b => b.Key ?? "", b => b.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("rootCause"))
                                    {
                                        recordableOrdinals["rootCause"] = recordableIncidents.SelectMany(i => i.INCFORM_CAUSATION).GroupBy(c => c.CAUSEATION_CD).ToDictionary(c =>
                                                                                                                                                                              c.Key ?? "", c => c.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("tenure"))
                                    {
                                        recordableOrdinals["tenure"] = recordableIncidents.GroupBy(i => i.INCFORM_INJURYILLNESS.JOB_TENURE).ToDictionary(t => t.Key ?? "", t => t.Count());
                                    }
                                    if (setRecordable != null && setRecordable.VALUE.Contains("daysToClose"))
                                    {
                                        recordableOrdinals["daysToClose"] = recordableIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                                                                                                                         ((TimeSpan)(i.INCIDENT_DT - i.CLOSE_DATE)).Days).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                                                                                                                                                                                                                                       (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                                                                                                                                                                                                                                                                                                                                                                                 x.Key ?? "", x => x.Count());

                                        /*
                                         *                                                                              recordableOrdinals["daysToClose"] = recordableIncidents.Where(i => i.CLOSE_DATE.HasValue).Select(i =>
                                         * EntityFunctions.DiffDays(i.INCIDENT_DT, i.CLOSE_DATE)).Select(d => entities.XLAT_DAYS_TO_CLOSE_TRANS.FirstOrDefault(x =>
                                         * (x.MIN_DAYS.HasValue ? d >= x.MIN_DAYS : true) && (x.MAX_DAYS.HasValue ? d <= x.MAX_DAYS : true)).XLAT_CODE).GroupBy(x => x).ToDictionary(x =>
                                         * x.Key ?? "", x => x.Count());
                                         */
                                    }
                                }

                                var dataList = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, incidentMeasureIDs, true, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, nearMissMeasureID, nearMisses, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, firstAidMeasureID, firstAidCases, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, recordableMeasureID, recordables, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, lostTimeCaseMeasureID, lostTimeCases, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, fatalityMeasureID, fatalities, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, otherIncidentsID, otherIncidents, updateIndicator);
                                EHSDataMapping.SetEHSDataValue(dataList, closedInvestigationMeasureID, closedInvestigations, updateIndicator);
                                foreach (var data in dataList)
                                {
                                    if (data.VALUE != 0)
                                    {
                                        if (data.EntityState == EntityState.Detached)
                                        {
                                            entities.EHS_DATA.AddObject(data);
                                        }
                                        if (incidentsForDay.Any())
                                        {
                                            if (data.MEASURE_ID == firstAidMeasureID)
                                            {
                                                UpdateOrdinalData(entities, data, firstAidOrdinals);
                                            }
                                            else if (data.MEASURE_ID == recordableMeasureID)
                                            {
                                                UpdateOrdinalData(entities, data, recordableOrdinals);
                                            }
                                        }
                                    }
                                    else if (data.EntityState != EntityState.Detached && data.VALUE == 0)
                                    {
                                        if (data.MEASURE_ID == firstAidMeasureID)
                                        {
                                            foreach (var key in firstAidOrdinals.Keys.ToArray())
                                            {
                                                firstAidOrdinals[key] = new Dictionary <string, int>();
                                            }
                                            UpdateOrdinalData(entities, data, firstAidOrdinals);
                                        }
                                        else if (data.MEASURE_ID == recordableMeasureID)
                                        {
                                            foreach (var key in recordableOrdinals.Keys.ToArray())
                                            {
                                                recordableOrdinals[key] = new Dictionary <string, int>();
                                            }
                                            UpdateOrdinalData(entities, data, recordableOrdinals);
                                        }
                                        entities.DeleteObject(data);
                                    }
                                }
                            }

                            // MONTHLY INCIDENTS (from PLANT_ACCOUNTING)
                            var             accountingForPlant = entities.PLANT_ACCOUNTING.Where(a => a.PLANT_ID == plant.PLANT_ID);
                            List <EHS_DATA> ehsdataList;

                            for (var currDate = fromDate; currDate <= toDate; currDate = currDate.AddDays(1))
                            {
                                decimal timeLost       = 0;
                                decimal timeRestricted = 0;

                                if (currDate.Day == 1)
                                {
                                    // get or create data records for the 1st day of the month
                                    ehsdataList = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, incidentMonthlyMeasureIDs, true, updateIndicator);
                                    var accountingForMonth = accountingForPlant.FirstOrDefault(a => a.PERIOD_YEAR == currDate.Year && a.PERIOD_MONTH == currDate.Month);
                                    if (accountingForMonth != null)
                                    {
                                        timeLost       = accountingForMonth.TIME_LOST ?? 0;
                                        timeRestricted = accountingForMonth.TOTAL_DAYS_RESTRICTED ?? 0;
                                    }
                                    EHSDataMapping.SetEHSDataValue(ehsdataList, timeLostMeasureID, timeLost, updateIndicator);
                                    EHSDataMapping.SetEHSDataValue(ehsdataList, timeRestrictedMeasureID, timeRestricted, updateIndicator);
                                    WriteLine("ACCOUNTING Rollup For Plant " + pact.PLANT_ID + " date = " + currDate.ToShortDateString());
                                }
                                else
                                {
                                    // get any spurrious data that might have been entered manually. we will want to delete these
                                    ehsdataList = EHSDataMapping.SelectEHSDataPeriodList(entities, plant.PLANT_ID, currDate, incidentMonthlyMeasureIDs, false, updateIndicator);
                                }

                                foreach (var data in ehsdataList)
                                {
                                    if (data.EntityState == EntityState.Detached && data.VALUE.HasValue && currDate.Day == 1)
                                    {
                                        entities.EHS_DATA.AddObject(data);
                                    }
                                    else if (data.EntityState != EntityState.Detached && currDate.Day != 1)
                                    {
                                        entities.DeleteObject(data);
                                    }
                                }
                            }
                        }

                        entities.SaveChanges();
                    }

                    entities.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                output.AppendFormat("EHS Data RollUp Error - {0}", ex);
            }

            return(nextStep);
        }
Example #5
0
        protected void lbPlantSave_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            PLANT   plant   = (PLANT)LocalOrg().EditObject;
            ADDRESS address = null;

            TextBox tbPlantName    = (TextBox)hfBase.FindControl("tbPlantName");
            TextBox tbPlantDesc    = (TextBox)hfBase.FindControl("tbPlantDesc");
            TextBox tbOrgLocCode   = (TextBox)hfBase.FindControl("tbOrgLocCode");
            TextBox tbPlantLocCode = (TextBox)hfBase.FindControl("tbPlantLocCode");

            DropDownList ddlParentBusOrg      = (DropDownList)hfBase.FindControl("ddlParentBusOrg");
            DropDownList ddlPlantCurrecyCodes = (DropDownList)hfBase.FindControl("ddlPlantCurrencyCodes");
            DropDownList ddlPlantTimeZone     = (DropDownList)hfBase.FindControl("ddlPlantTimezone");
            DropDownList ddlStatus            = (DropDownList)hfBase.FindControl("ddlPlantStatus");

            if (btn.CommandArgument == "edit")
            {
                if (plant == null)
                {
                    plant            = new PLANT();
                    plant.COMPANY_ID = SessionManager.EffLocation.Company.COMPANY_ID;
                    entities.AddToPLANT(plant);
                }
                else
                {
                    plant = SQMModelMgr.LookupPlant(entities, (decimal)plant.COMPANY_ID, 0, plant.PLANT_ID, "", false);
                }

                if (string.IsNullOrEmpty(tbPlantName.Text)) // || string.IsNullOrEmpty(tbPlantLocCode.Text))
                {
                    ErrorAlert("RequiredInputs");
                    return;
                }

                plant.PLANT_NAME      = tbPlantName.Text.Trim();
                plant.DISP_PLANT_NAME = tbPlantDesc.Text.Trim();
                plant.DUNS_CODE       = tbPlantLocCode.Text.Trim();
                plant.ALT_DUNS_CODE   = tbAltPlantCode.Text.Trim();
                plant.LOCATION_CODE   = ddlCountryCode.SelectedValue;
                if (plant.LOCATION_CODE == "US")
                {
                    plant.COMP_INT_ID = ddlPowerSourcedRegion.SelectedValue;
                }
                else
                {
                    plant.COMP_INT_ID = "";
                }

                if (!string.IsNullOrEmpty(ddlLocalLanguage.SelectedValue))
                {
                    plant.LOCAL_LANGUAGE = Convert.ToInt32(ddlLocalLanguage.SelectedValue);
                }
                else
                {
                    plant.LOCAL_LANGUAGE = null;
                }

                plant.LOCATION_TYPE  = ddlLocationType.SelectedValue;
                plant.TRACK_FIN_DATA = cbTrackFinData.Checked;
                plant.TRACK_EW_DATA  = cbTrackEWData.Checked;
                plant.BUS_ORG_ID     = Int32.Parse(ddlParentBusOrg.SelectedValue);
                plant.CURRENCY_CODE  = ddlPlantCurrecyCodes.SelectedValue;
                plant.LOCAL_TIMEZONE = ddlPlantTimeZone.SelectedValue;
                // plant.LOCAL_LANGUAGE = Convert.ToInt32(ddlPlantLanguage.SelectedValue);
                plant.STATUS = ddlStatus.SelectedValue;

                if (plant.ADDRESS == null || plant.ADDRESS.Count == 0)
                {
                    address              = new ADDRESS();
                    address.COMPANY_ID   = plant.COMPANY_ID;
                    address.PLANT_ID     = plant.PLANT_ID;
                    address.ADDRESS_TYPE = "S";
                    plant.ADDRESS.Add(address);
                }
                else
                {
                    address = plant.ADDRESS.FirstOrDefault();
                }

                address.STREET1     = tbAddress1.Text;
                address.STREET2     = tbAddress2.Text;
                address.CITY        = tbCity.Text;
                address.STATE_PROV  = tbState.Text;
                address.POSTAL_CODE = tbPostal.Text;
                address.COUNTRY     = ddlCountryCode.SelectedValue;

                foreach (GridItem item in rgPlantActive.Items)
                {
                    PLANT_ACTIVE plantActive = null;
                    PLANT_ACTIVE pa          = null;

                    HiddenField        hfRecType = (HiddenField)item.FindControl("hfRecordType");
                    RadMonthYearPicker rdp1      = (RadMonthYearPicker)item.FindControl("rdpStartDate");
                    RadMonthYearPicker rdp2      = (RadMonthYearPicker)item.FindControl("rdpStopDate");
                    CheckBox           cb1       = (CheckBox)item.FindControl("cbEnableEmail");
                    CheckBox           cb2       = (CheckBox)item.FindControl("cbViewInactiveHist");

                    try
                    {
                        if ((pa = plant.PLANT_ACTIVE.Where(p => p.RECORD_TYPE == Convert.ToInt32(hfRecType.Value)).FirstOrDefault()) != null)
                        {
                            pa.EFF_START_DATE       = rdp1.SelectedDate;
                            pa.EFF_END_DATE         = rdp2.SelectedDate;
                            pa.ENABLE_EMAIL         = cb1.Checked;
                            pa.ENABLE_INACTIVE_HIST = cb2.Checked;
                        }
                        else
                        {
                            plantActive                      = new PLANT_ACTIVE();
                            plantActive.PLANT_ID             = plant.PLANT_ID;
                            plantActive.RECORD_TYPE          = Convert.ToInt32(hfRecType.Value);
                            plantActive.EFF_START_DATE       = rdp1.SelectedDate;
                            plantActive.EFF_END_DATE         = rdp2.SelectedDate;
                            plantActive.ENABLE_EMAIL         = cb1.Checked;
                            plantActive.ENABLE_INACTIVE_HIST = cb2.Checked;
                            plant.PLANT_ACTIVE.Add(plantActive);
                            //entities.AddToPLANT_ACTIVE(plantActive);
                        }
                    }
                    catch { }
                }

                if (SQMModelMgr.UpdatePlant(entities, plant, SessionManager.UserContext.UserName()) != null)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alertResult('hfAlertSaveSuccess');", true);
                    lbPlantSave_Click(lbPlantCancel1, null);
                }
                else
                {
                    ErrorAlert("SaveError");
                    return;
                }
            }
            else
            {
                uclSearchBar_OnReturnClick();
            }

            SessionManager.EffLocation.Plant = plant;
            LocalOrg().EditObject            = null;
            SetupPage();
        }
        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);
            }
        }