Ejemplo n.º 1
0
        private void BindSubcategoryList(string category)
        {
            if (!string.IsNullOrEmpty(category))
            {
                subList = EHSModel.SelectEHSMeasureSubCategoryList(category);
            }
            else
            {
                subList = EHSModel.SelectEHSMeasureSubCategoryList(ddlMeasureCategory.SelectedValue);
            }

            if (subList != null && subList.Count > 0)
            {
                ddlMeasureSubcategory.DataSource     = subList;
                ddlMeasureSubcategory.DataValueField = "MEASURE_CD";
                ddlMeasureSubcategory.DataTextField  = "MEASURE_NAME";
                ddlMeasureSubcategory.DataBind();

                if (ddlMeasureCategory.SelectedIndex > 0)
                {
                    lnkMeasureNew.Visible = true;
                }
                else
                {
                    lnkMeasureNew.Visible = false;
                }

                if (ddlMeasureCategory.SelectedValue != "PROD" && ddlMeasureCategory.SelectedValue != "SAFE" && ddlMeasureCategory.SelectedValue != "FACT")
                {
                    ddlMeasureSubcategory.Items.Insert(0, new ListItem(""));
                }
                ddlMeasureSubcategory.Enabled = true;
            }
        }
Ejemplo n.º 2
0
        public void BindMeasureList(List <EHS_MEASURE> theList)
        {
            pnlMeasureList.Visible = true;
            pnlMeasureEdit.Visible = false;
            btnMeasureSave.Enabled = btnMeasureCancel.Enabled = false;

            BindSubcategoryList(ddlMeasureCategory.SelectedValue);
            gvMeasureSubcatList.DataSource = EHSModel.SelectEHSMeasureSubCategoryList(ddlMeasureCategory.SelectedValue);
            gvMeasureSubcatList.DataBind();
        }
        private int DisplayResults(string cmdID)
        {
            int          status    = 0;
            SQMMetricMgr metricMgr = null;

            try
            {
                if (!string.IsNullOrEmpty(cmdID))
                {
                    EHS_PROFILE_MEASURE metric      = EHSModel.LookupEHSProfileMeasure(new PSsqmEntities(), Convert.ToDecimal(cmdID));
                    decimal             calcScopeID = EHSModel.ConvertPRODMeasure(metric.EHS_MEASURE, metric.PRMR_ID);
                    decimal             plantID     = Convert.ToDecimal(hfInputsListPlantID.Value);
                    DateTime            periodDate  = Convert.ToDateTime(hfInputsListPeriodDate.Value);

                    divInputsListReviewArea.Visible       = true;
                    divInputsListReviewArea.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
                    if (metricMgr == null)
                    {
                        metricMgr = new SQMMetricMgr().CreateNew(SessionManager.PrimaryCompany(), "I", periodDate.AddMonths(-12), periodDate, new decimal[1] {
                            plantID
                        });
                        metricMgr.Load(DateIntervalType.month, DateSpanOption.SelectRange);
                    }

                    GaugeDefinition ggCfg = new GaugeDefinition().Initialize();
                    ggCfg.Title         = metric.EHS_MEASURE.MEASURE_NAME.Trim() + " - Input History";
                    ggCfg.Height        = 250; ggCfg.Width = 650;
                    ggCfg.NewRow        = true;
                    ggCfg.DisplayLabel  = true;
                    ggCfg.DisplayLegend = false;

                    ggCfg.LabelV = "Quantity";
                    status       = uclGauge.CreateControl(SQMChartType.MultiLine, ggCfg, metricMgr.CalcsMethods(new decimal[1] {
                        plantID
                    }, "I", calcScopeID.ToString(), "sum", 32, (int)EHSCalcsCtl.SeriesOrder.PeriodMeasure), divInputsListReviewArea);

                    if (string.IsNullOrEmpty(metric.EHS_MEASURE.PLANT_ACCT_FIELD) && metric.EHS_MEASURE.MEASURE_CATEGORY != "FACT")
                    {
                        ggCfg.Height       = 165; ggCfg.Width = 650;
                        ggCfg.Title        = "";
                        ggCfg.DisplayLabel = false;
                        ggCfg.LabelV       = "Cost";
                        status             = uclGauge.CreateControl(SQMChartType.MultiLine, ggCfg, metricMgr.CalcsMethods(new decimal[1] {
                            plantID
                        }, "I", calcScopeID.ToString(), "cost", 32, (int)EHSCalcsCtl.SeriesOrder.PeriodMeasure), divInputsListReviewArea);
                    }
                }
            }
            catch
            {
                ;
            }

            return(status);
        }
Ejemplo n.º 4
0
        private void SetupPage()
        {
            if (langList == null || langList.Count == 0)
            {
                langList = SQMModelMgr.SelectLanguageList(new PSsqmEntities(), true);
                uclPrefsEdit.SetLanguageList(langList);
            }

            BusinessLocation businessLocation = new BusinessLocation(); businessLocation = SessionManager.UserContext.HRLocation;

            uclPrefsEdit.BindUser(null, SessionManager.UserContext.HRLocation, SessionManager.UserContext.WorkingLocation);

            if (UserContext.CheckAccess("CQM", "home", "92") == AccessMode.None)
            {
                uclPrefsEdit.DelegateList.Attributes.Add("disabled", "true");
            }

            // quality tasks
            if (uclTaskList.TaskListRepeater.Items.Count < 1)
            {
                bool            hasDelegates;
                List <TaskItem> taskList = new List <TaskItem>();
                // taskList = QualityIssue.IncidentTaskList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID, SessionManager.UserContext.Person.PERSON_ID, false, out hasDelegates);

                // EHS inputs
                if (UserContext.CheckAccess("EHS", "input", "301") > AccessMode.View)
                {
                    if (respForList == null || respForList.Count == 0)
                    {
                        respForList = SQMModelMgr.SelectDelegateList(SessionManager.UserContext.Person.PERSON_ID);
                        respForList.Insert(0, SessionManager.UserContext.Person);
                    }
                    decimal[] pids = respForList.Select(l => l.PERSON_ID).ToArray();
                    taskList.AddRange(EHSModel.ProfileTaskList(EHSModel.GetIncompleteInputs(pids, DateTime.Now.AddMonths(-12))));
                }
                // Problem cases
                if (UserContext.CheckAccess("CQM", "prob", "151") > AccessMode.View)
                {
                    taskList.AddRange(ProblemCase.CaseTaskList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID, SessionManager.UserContext.Person.PERSON_ID, false, out hasDelegates));
                }

                // taskList = taskList.OrderBy(l => l.RecordType).ThenBy(l => l.RecordID).ToList();
                uclTaskList.BindTaskList(taskList);
            }
        }
Ejemplo n.º 5
0
        private void OnLocationSelect(decimal plantID)
        {
            PLANT plant = SQMModelMgr.LookupPlant(plantID);

            if (plant == null)
            {
                DisplayProfileMessage(lblProfileNotExist);
            }
            else
            {
                List <BusinessLocation> locationList = new List <BusinessLocation>();
                locationList.Add(new BusinessLocation().Initialize(plantID));
                List <PERSON> responsibleList = SQMModelMgr.SelectPlantPersonList(locationList, "311", AccessMode.Update);

                SQMBasePage.SetPersonList(ddlMetricResponsible, responsibleList, "");
                SQMBasePage.SetPersonList(ddlFinalApprover, responsibleList.Where(l => l.ROLE < SessionManager.AccessModeRoleXREF(AccessMode.Update)).ToList(), "");

                LoadPlantProfile(plant);

                if (LocalProfile() != null && (LocalProfile().Profile.EHS_PROFILE_MEASURE == null || LocalProfile().Profile.EHS_PROFILE_MEASURE.Count == 0))
                {
                    if (UserContext.RoleAccess() > AccessMode.Plant)
                    {
                        List <EHS_PROFILE> profileList = EHSModel.SelectPlantProfileList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID);
                        SQMBasePage.SetLocationList(ddlCopyProfile, SQMModelMgr.SelectBusinessLocationList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID, 0, true).Where(l => profileList.Select(p => p.PLANT_ID).ToArray().Contains(l.Plant.PLANT_ID)).ToList(), 0);
                        ddlCopyProfile.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("", ""));
                        responsibleList = SQMModelMgr.SelectPersonList((decimal)plant.COMPANY_ID, (decimal)plant.BUS_ORG_ID, true, false).Where(p => p.ROLE >= SessionManager.AccessModeRoleXREF(AccessMode.Admin) && p.ROLE < SessionManager.AccessModeRoleXREF(AccessMode.View)).OrderBy(l => l.LAST_NAME).ToList();
                        ddlDefaultResponsible.Items.Clear();
                        foreach (PERSON person in responsibleList)
                        {
                            if (SQMModelMgr.PersonPlantAccess(person, plant.PLANT_ID))
                            {
                                ddlDefaultResponsible.Items.Add(new Telerik.Web.UI.RadComboBoxItem(SQMModelMgr.FormatPersonListItem(person), person.PERSON_ID.ToString()));
                            }
                        }
                        ddlDefaultResponsible.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("", ""));
                        pnlCopyProfile.Visible = true;
                    }
                }

                pnlProfileEdit.Style.Add("display", "none");
            }
        }
Ejemplo n.º 6
0
        private void SetupPage()
        {
            // this is really the Measures tab

            ToggleVisible(pnlMeasureList);
            if (ddlMeasureStatus.Items.Count == 0)
            {
                ddlMeasureStatus.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("statusCodeDelete", "short"));
            }

            if (ddlMeasureCategory.Items.Count < 2)
            {
                ddlMeasureCategory.Items.Clear();
                ddlMeasureCategory.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("measureCategoryEHS"));
                ddlMeasureCategory.Items.Insert(0, new ListItem("-all categories-", ""));
                ddlMeasureCategory.SelectedValue = "";
                lnkMeasureNew.Visible            = false;
            }

            if (ddlMeasureEFMType.Items.Count == 0)
            {
                ddlMeasureEFMType.DataSource     = EHSModel.SelectEFMTypeList("");
                ddlMeasureEFMType.DataValueField = "EFM_TYPE";
                ddlMeasureEFMType.DataTextField  = "DESCRIPTION";
                ddlMeasureEFMType.DataBind();
                ddlMeasureEFMType.Items.Insert(0, new ListItem(""));
            }

            if (ddlOutputUOM.Items.Count == 0)
            {
                string[] uomcats = { "FACT" };
                foreach (UOM uom in SessionManager.UOMList.Where(l => uomcats.Contains(l.UOM_CATEGORY)).ToList())
                {
                    ddlOutputUOM.Items.Add(new ListItem(uom.UOM_DESC, uom.UOM_ID.ToString()));
                }
                ddlOutputUOM.Items.Insert(0, new ListItem("", ""));
            }

            measureList = EHSModel.SelectEHSMeasureList(ddlMeasureCategory.SelectedValue, false);
            BindMeasureList(measureList);
        }
Ejemplo n.º 7
0
        private void OnLocationSelect(decimal plantID)
        {
            PLANT plant = SQMModelMgr.LookupPlant(plantID);

            if (plant == null)
            {
                DisplayProfileMessage(lblProfileNotExist);
            }
            else
            {
                List <BusinessLocation> locationList = new List <BusinessLocation>();
                locationList.Add(new BusinessLocation().Initialize(plantID));

                List <PERSON> responsibleList = SQMModelMgr.SelectPrivGroupPersonList(SysPriv.approve, SysScope.envdata, plant.PLANT_ID);
                responsibleList.AddRange(SQMModelMgr.SelectPrivGroupPersonList(SysPriv.admin, SysScope.system, 0));                  // append any system administrators to the approval list
                SQMBasePage.SetPersonList(ddlFinalApprover, responsibleList, "", true);
                SQMBasePage.SetPersonList(ddlMetricResponsible, SQMModelMgr.SelectPrivGroupPersonList(SysPriv.originate, SysScope.envdata, plant.PLANT_ID), "", true);

                LoadPlantProfile(plant);

                if (LocalProfile() != null && (LocalProfile().Profile.EHS_PROFILE_MEASURE == null || LocalProfile().Profile.EHS_PROFILE_MEASURE.Count == 0))
                {
                    if (UserContext.GetMaxScopePrivilege(SysScope.envdata) <= SysPriv.config)
                    {
                        List <EHS_PROFILE> profileList = EHSModel.SelectPlantProfileList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID);
                        SQMBasePage.SetLocationList(ddlCopyProfile, SQMModelMgr.SelectBusinessLocationList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID, 0, true).Where(l => profileList.Select(p => p.PLANT_ID).ToArray().Contains(l.Plant.PLANT_ID)).ToList(), 0);
                        ddlCopyProfile.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("", ""));

                        responsibleList = SQMModelMgr.SelectPrivGroupPersonList(SysPriv.originate, SysScope.envdata, plant.PLANT_ID);
                        SQMBasePage.SetPersonList(ddlDefaultResponsible, responsibleList, "");
                        ddlDefaultResponsible.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("", ""));
                        pnlCopyProfile.Visible = true;
                    }
                }

                pnlProfileEdit.Style.Add("display", "none");
            }
        }
Ejemplo n.º 8
0
        protected void btnMetricSave_Click(object sender, EventArgs e)
        {
            bool success;
            bool measureChanged    = false;
            bool reqdError         = false;
            EHS_PROFILE_MEASURE pm = null;

            if (hfOper.Value == "add")
            {
                pm = new EHS_PROFILE_MEASURE();
                pm.EHS_PROFILE_MEASURE_EXT = new EHS_PROFILE_MEASURE_EXT();
            }
            else
            {
                pm = LocalProfile().Profile.EHS_PROFILE_MEASURE.FirstOrDefault(l => l.PRMR_ID == LocalProfile().CurrentProfileMeasure.PRMR_ID);
                if (pm.EHS_PROFILE_MEASURE_EXT == null)
                {
                    pm.EHS_PROFILE_MEASURE_EXT         = new EHS_PROFILE_MEASURE_EXT();
                    pm.EHS_PROFILE_MEASURE_EXT.PRMR_ID = pm.PRMR_ID;
                }
            }

            pm.PLANT_ID = LocalProfile().Profile.PLANT_ID;

            decimal measureID = 0;

            if (!string.IsNullOrEmpty(ddlMetricID.SelectedValue))
            {
                measureID = Convert.ToDecimal(WebSiteCommon.ParseItemValue(ddlMetricID.SelectedValue));
                if (pm.MEASURE_ID != measureID)
                {
                    measureChanged = true;
                }
            }

            pm.MEASURE_ID     = measureID;
            pm.MEASURE_PROMPT = tbMetricPrompt.Text;
            pm.REG_STATUS     = ddlMetricRegStatus.SelectedValue;
            pm.UN_CODE        = ddlMetricDisposalCode.SelectedValue;
            pm.WASTE_CODE     = tbWasteCode.Text;

            pm.DEFAULT_CURRENCY_CODE = ddlMetricCurrency.SelectedValue;
            if (ddlMetricResponsible.SelectedIndex > 0)
            {
                decimal personID = Convert.ToDecimal(ddlMetricResponsible.SelectedValue);
                if (personID != pm.RESPONSIBLE_ID)
                {
                    pm = LocalProfile().UpdateMeasureResponsible(pm, personID);
                }
                pm.RESPONSIBLE_ID = personID;
            }
            else
            {
                pm.RESPONSIBLE_ID = Convert.ToDecimal(null);
            }

            if (ddlMetricCost.SelectedValue == "CREDIT")
            {
                pm.NEG_VALUE_ALLOWED = true;
            }
            else
            {
                pm.NEG_VALUE_ALLOWED = false;
            }

            pm.STATUS = ddlMetricStatus.SelectedValue;

            pm.IS_REQUIRED = cbMetricRequired.Checked;

            decimal uomID = 0;

            if (ddlMetricCategory.SelectedValue == "FACT")
            {
                pm.DEFAULT_UOM = EHSModel.LookupEHSMeasure(new PSsqmEntities(), pm.MEASURE_ID, "").STD_UOM;
            }
            else
            {
                if (SQMBasePage.ParseToDecimal(WebSiteCommon.ParseItemValue(ddlMetricUOM.SelectedValue), out uomID))
                {
                    pm.DEFAULT_UOM = uomID;
                }

                decimal UOMFactor = 0;
                if (decimal.TryParse(tbUOMFactor.Text, out UOMFactor))
                {
                    pm.UOM_FACTOR = UOMFactor;
                }
                else
                {
                    pm.UOM_FACTOR = null;
                }
            }

            if (phMetricExt.Visible)
            {
                decimal decimalValue;
                if (SQMBasePage.ParseToDecimal(tbValueDflt.Text, out decimalValue))
                {
                    pm.EHS_PROFILE_MEASURE_EXT.VALUE_DEFAULT = decimalValue;
                }
                else
                {
                    pm.EHS_PROFILE_MEASURE_EXT.VALUE_DEFAULT = null;
                }

                if (SQMBasePage.ParseToDecimal(tbCostDflt.Text, out decimalValue))
                {
                    pm.EHS_PROFILE_MEASURE_EXT.COST_DEFAULT = decimalValue;
                }
                else
                {
                    pm.EHS_PROFILE_MEASURE_EXT.COST_DEFAULT = null;
                }

                if ((pm.EHS_PROFILE_MEASURE_EXT.VALUE_DEFAULT.HasValue || pm.EHS_PROFILE_MEASURE_EXT.COST_DEFAULT.HasValue))
                {
                    pm.EHS_PROFILE_MEASURE_EXT.OVERRIDE_ALLOWED = cbEnableOverride.Checked;
                }
                else
                {
                    pm.EHS_PROFILE_MEASURE_EXT.OVERRIDE_ALLOWED = false;
                }

                /*
                 * if ((pm.EHS_PROFILE_MEASURE_EXT.VALUE_DEFAULT.HasValue || pm.EHS_PROFILE_MEASURE_EXT.COST_DEFAULT.HasValue) && radEffEndDate.SelectedDate != null)
                 *  pm.EHS_PROFILE_MEASURE_EXT.EFF_END_DT = (DateTime)radEffEndDate.SelectedDate;
                 * else
                 *  pm.EHS_PROFILE_MEASURE_EXT.EFF_END_DT = null;
                 */
            }

            // validate

            switch (ddlMetricCategory.SelectedValue)
            {
            case "ENGY":
            case "EUTL":
                if (string.IsNullOrEmpty(ddlMetricCategory.SelectedValue) || string.IsNullOrEmpty(ddlMetricID.SelectedValue) || string.IsNullOrEmpty(ddlMetricUOM.SelectedValue) || string.IsNullOrEmpty(ddlMetricResponsible.SelectedValue))
                {
                    reqdError = true;
                }
                break;

            case "PROD":
            case "FACT":
                if (string.IsNullOrEmpty(ddlMetricCategory.SelectedValue) || string.IsNullOrEmpty(ddlMetricID.SelectedValue) || string.IsNullOrEmpty(ddlMetricResponsible.SelectedValue))
                {
                    reqdError = true;
                }
                break;

            case "SAFE":
                if (string.IsNullOrEmpty(ddlMetricCategory.SelectedValue) || string.IsNullOrEmpty(ddlMetricID.SelectedValue) || string.IsNullOrEmpty(ddlMetricResponsible.SelectedValue))
                {
                    reqdError = true;
                }
                break;

            default:
                if (string.IsNullOrEmpty(ddlMetricCategory.SelectedValue) || string.IsNullOrEmpty(ddlMetricID.SelectedValue) || string.IsNullOrEmpty(ddlMetricUOM.SelectedValue) || string.IsNullOrEmpty(ddlMetricResponsible.SelectedValue) ||
                    string.IsNullOrEmpty(ddlMetricDisposalCode.SelectedValue) || string.IsNullOrEmpty(ddlMetricRegStatus.SelectedValue))
                {
                    reqdError = true;
                }
                if (tbUOMFactor.Visible && string.IsNullOrEmpty(tbUOMFactor.Text))
                {
                    reqdError = true;
                }
                break;
            }
            if (reqdError)
            {
                BindProfileMeasure(pm);
                DisplayErrorMessage(hfErrRequiredInputs);
                return;
            }

            if (hfOper.Value == "add")  // add measure to list
            {
                pm = LocalProfile().AddMeasure(pm, Convert.ToDecimal(WebSiteCommon.ParseItemValue(ddlMetricID.SelectedValue)));
            }

            EHSProfile.UpdateProfile(LocalProfile());

            if (pm.STATUS == "D")
            {
                EHSProfile.DeleteProfileMeasure(LocalProfile(), pm.MEASURE_ID, true, true);
                measureChanged = true;
            }

            if (measureChanged)
            {
                SetLocalProfile(new EHSProfile().Load(LocalProfile().Plant.PLANT_ID, true, false));
            }

            btnMetricClear_Click(null, null);
            BindProfile(LocalProfile());
        }
        private int DisplayResults(string cmdID)
        {
            int          status    = 0;
            SQMMetricMgr metricMgr = null;

            foreach (RepeaterItem item in rptProfilePeriod.Items)
            {
                try
                {
                    LinkButton lnk = (LinkButton)item.FindControl("lnkMetricCD");
                    CheckBox   cb  = (CheckBox)item.FindControl("cbMetricSelect");
                    if (cb.Checked) //  ||  cmdID == "0")
                    {
                        EHS_PROFILE_MEASURE metric      = LocalProfile().GetMeasure(Convert.ToDecimal(lnk.CommandArgument));
                        decimal             calcScopeID = EHSModel.ConvertPRODMeasure(metric.EHS_MEASURE, metric.PRMR_ID);
                        System.Web.UI.HtmlControls.HtmlGenericControl reviewArea = (System.Web.UI.HtmlControls.HtmlGenericControl)item.FindControl("divReviewArea");
                        LinkButton lnkClose = (LinkButton)item.FindControl("lnkReviewAreaClose");
                        lnkClose.Visible         = reviewArea.Visible = true;
                        lnk.Visible              = false;
                        reviewArea.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
                        if (metricMgr == null)
                        {
                            metricMgr = new SQMMetricMgr().CreateNew(SessionManager.PrimaryCompany(), "I", LocalProfile().InputPeriod.PeriodDate.AddMonths(-12), LocalProfile().InputPeriod.PeriodDate, new decimal[1] {
                                LocalProfile().Profile.PLANT_ID
                            });
                            metricMgr.Load(DateIntervalType.month, DateSpanOption.SelectRange);
                        }

                        GaugeDefinition ggCfg = new GaugeDefinition().Initialize();
                        ggCfg.Title         = metric.EHS_MEASURE.MEASURE_NAME.Trim() + " - Input History";
                        ggCfg.Height        = 250; ggCfg.Width = 700;
                        ggCfg.NewRow        = true;
                        ggCfg.DisplayLabel  = true;
                        ggCfg.DisplayLegend = false;

                        ggCfg.LabelV = "Quantity";
                        status       = uclGauge.CreateControl(SQMChartType.MultiLine, ggCfg, metricMgr.CalcsMethods(new decimal[1] {
                            LocalProfile().Profile.PLANT_ID
                        }, "I", calcScopeID.ToString(), "sum", 32, (int)EHSCalcsCtl.SeriesOrder.PeriodMeasure), reviewArea);

                        if (string.IsNullOrEmpty(metric.EHS_MEASURE.PLANT_ACCT_FIELD) && metric.EHS_MEASURE.MEASURE_CATEGORY != "FACT")
                        {
                            ggCfg.Height       = 180; ggCfg.Width = 700;
                            ggCfg.Title        = "";
                            ggCfg.DisplayLabel = false;
                            ggCfg.LabelV       = "Cost";
                            status             = uclGauge.CreateControl(SQMChartType.MultiLine, ggCfg, metricMgr.CalcsMethods(new decimal[1] {
                                LocalProfile().Profile.PLANT_ID
                            }, "I", calcScopeID.ToString(), "cost", 32, (int)EHSCalcsCtl.SeriesOrder.PeriodMeasure), reviewArea);
                        }
                    }
                }
                catch
                {
                    ;
                }
            }

            BindSharedCalendars();

            return(status);
        }
Ejemplo n.º 10
0
        private void SetupProfilePanel()
        {
            if (ddlMetricDisposalCode.Items.Count == 0)
            {
                ddlDayDue.Items.AddRange(WebSiteCommon.PopulateDropDownListNums(1, 31));
                ddlWarningDays.Items.AddRange(WebSiteCommon.PopulateDropDownListNums(0, 11));

                ddlMetricDisposalCode.DataSource     = SessionManager.DisposalCodeList;
                ddlMetricDisposalCode.DataValueField = "UN_CODE";
                ddlMetricDisposalCode.DataTextField  = "UN_CODE";
                ddlMetricDisposalCode.DataBind();
                ddlMetricDisposalCode.Items.Insert(0, new ListItem(""));

                ddlMetricRegStatus.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("regulatoryStatus"));
                ddlMetricRegStatus.Items.Insert(0, new ListItem(""));

                SQMBasePage.FillCurrencyDDL(ddlMetricCurrency, "EUR");
                ddlMetricCurrency.Items.Insert(0, "");

                ddlMetricCost.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("costType", "long"));
                ddlMetricCost.Items.Insert(0, "");

                if (UserContext.CheckUserPrivilege(SysPriv.config, SysScope.envdata))
                {
                    ddlMetricStatus.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("statusCodeDelete"));
                }
                else
                {
                    ddlMetricStatus.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("statusCode"));
                }

                ddlMetricCategory.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("measureCategoryEHS", 2, ""));
                ddlMetricCategory.Items.Insert(0, "");

                measureList = EHSModel.SelectEHSMeasureList("", true).OrderBy(l => l.MEASURE_NAME).ToList();
                foreach (EHS_MEASURE measure in measureList)
                {
                    ddlMetricID.Items.Add(new ListItem(measure.MEASURE_NAME.Trim(), WebSiteCommon.PackItemValue(measure.MEASURE_CATEGORY, measure.EFM_TYPE, measure.MEASURE_ID.ToString())));
                    if (measure.MEASURE_CATEGORY == "FACT")
                    {
                        ListItem item = new ListItem(measure.MEASURE_NAME.Trim(), measure.MEASURE_ID.ToString());
                        item.Attributes.Add("title", measure.MEASURE_DESC);
                        ddlNormFact.Items.Add(item);
                    }
                }
                ddlMetricID.Items.Insert(0, "");
                ddlNormFact.Items.Insert(0, "");

                if (ddlNormFact.Items.Count == 1)       // don't display normalize selects if no factors defined
                {
                    phNormFact.Visible = false;
                }

                foreach (UOM uom in SessionManager.UOMList.Where(l => l.OWNER_ID == null).OrderBy(l => l.UOM_NAME).ToList())
                {
                    ddlMetricUOM.Items.Add(new ListItem(uom.UOM_NAME, WebSiteCommon.PackItemValue(uom.UOM_CATEGORY, uom.EFM_TYPE, uom.UOM_ID.ToString())));
                }
                ddlMetricUOM.Items.Insert(0, "");
                ddlMetricUOM.SelectedIndex = 0;
            }
            divEHSProfile.Visible  = true;
            pnlCopyProfile.Visible = false;
            UpdateListTitles();
        }
Ejemplo n.º 11
0
        public void LoadProfileSelectHdr(decimal companyID, decimal busOrgID, bool indicateUndefined, bool showExpanded)
        {
            ToggleVisible(pnlProfileSelectHdr);

            List <BusinessLocation> locationList = SQMModelMgr.SelectBusinessLocationList(companyID, busOrgID, true).Where(l => l.Plant.TRACK_EW_DATA == true).ToList();

            locationList = UserContext.FilterPlantAccessList(locationList);

            int maxdesc = locationList.Select(l => l.Plant.PLANT_NAME.Length).Max();

            if (showExpanded && locationList.Select(l => l.Plant.BUS_ORG_ID).Distinct().Count() > 1 && maxdesc < 41)
            {
                ddlBusLocSelect.Visible = false;
                mnuBusLocSelect.Visible = true;
                SQMBasePage.SetLocationList(mnuBusLocSelect, locationList, 0, "select a location ...", "TOP", false);
                if (indicateUndefined)
                {
                    int           undefinedCount = 0;
                    List <string> profileList    = EHSModel.SelectPlantProfileList(companyID).Select(l => l.PLANT_ID.ToString()).ToList();
                    RadMenuItem   miTop          = mnuBusLocSelect.Items[0];
                    foreach (RadMenuItem miBU in miTop.Items)
                    {
                        foreach (RadMenuItem miLoc in miBU.Items)
                        {
                            if (!profileList.Contains(miLoc.Value))
                            {
                                ++undefinedCount;
                                // miLoc.ImageUrl = "~/images/defaulticon/16x16/grid-dot.png";
                                miLoc.CssClass = "rcbItemEmphasis";
                            }
                            else
                            {
                                miLoc.ImageUrl = "~/images/defaulticon/16x16/document.png";
                            }
                        }
                    }
                }
            }
            else
            {
                ddlBusLocSelect.Visible = true;
                mnuBusLocSelect.Visible = false;
                SQMBasePage.SetLocationList(ddlBusLocSelect, locationList, 0);
                if (indicateUndefined)
                {
                    int           undefinedCount = 0;
                    List <string> profileList    = EHSModel.SelectPlantProfileList(companyID).Select(l => l.PLANT_ID.ToString()).ToList();
                    foreach (RadComboBoxItem item in ddlBusLocSelect.Items)
                    {
                        if (!item.IsSeparator)
                        {
                            if (!profileList.Contains(item.Value))
                            {
                                ++undefinedCount;
                                item.ImageUrl = "~/images/defaulticon/16x16/blank.png";
                                item.CssClass = "rcbItemEmphasis";
                                item.ToolTip  = "Metrics not defined";
                            }
                            else
                            {
                                item.ImageUrl = "~/images/defaulticon/16x16/document.png";
                            }
                        }
                    }
                    if (undefinedCount > 0)
                    {
                        ddlBusLocSelect.ToolTip += hfBusLocProfileUndefined.Value;
                    }
                }
                ddlBusLocSelect.Items.Insert(0, new RadComboBoxItem("", ""));
            }
        }
        private int SaveInputs(decimal targetPrmrID, bool commitChanges)
        {
            int              status = 0;
            LinkButton       lnk;
            HiddenField      hf;
            TextBox          tbValue, tbCost, tbCredit;
            CheckBox         cbDelete;
            decimal          decimalValue;
            DateTime         dateValue;
            decimal          prmrID;
            bool             hasReqdInputs  = true;
            bool             hasSaveWarning = false;
            bool             hasSaveError   = false;
            EHSProfileStatus saveStatus     = EHSProfileStatus.Normal;

            try
            {
                foreach (RepeaterItem item in rptProfilePeriod.Items)
                {
                    lnk    = (LinkButton)item.FindControl("lnkMetricCD");
                    prmrID = Convert.ToDecimal(lnk.CommandArgument);
                    EHS_PROFILE_MEASURE metric = LocalProfile().GetMeasure((decimal)prmrID);

                    if (prmrID == targetPrmrID || commitChanges)
                    {
                        Repeater rpt      = (Repeater)item.FindControl("rptProfileInput");
                        int      numInput = 0;
                        foreach (RepeaterItem inputItem in rpt.Items)
                        {
                            hf = (HiddenField)inputItem.FindControl("hfInputDate");
                            EHS_PROFILE_INPUT input = LocalProfile().InputPeriod.GetPeriodInput(prmrID, Convert.ToDateTime(hf.Value));
                            if (input != null)
                            {
                                RadDatePicker dtpFrom = (RadDatePicker)inputItem.FindControl("radDateFrom");
                                RadDatePicker dtpTo   = (RadDatePicker)inputItem.FindControl("radDateTo");
                                tbValue  = (TextBox)inputItem.FindControl("tbMetricValue");
                                tbCost   = (TextBox)inputItem.FindControl("tbMetricCost");
                                tbCredit = (TextBox)inputItem.FindControl("tbMetricCredit");
                                cbDelete = (CheckBox)inputItem.FindControl("cbDelete");
                                hf       = (HiddenField)inputItem.FindControl("hfStatus");
                                Control tr = new Control();

                                EHSProfileStatus inputStatus = EHSProfileStatus.Normal;
                                switch (metric.EHS_MEASURE.MEASURE_CATEGORY)
                                {
                                case "PROD":
                                case "SAFE":
                                case "FACT":
                                    if (dtpFrom.SelectedDate == null || dtpTo.SelectedDate == null)
                                    {
                                        inputStatus = EHSProfileStatus.Incomplete;
                                    }
                                    else if (string.IsNullOrEmpty(tbValue.Text.Trim()))
                                    {
                                        inputStatus = EHSProfileStatus.NoInputs;
                                    }
                                    break;

                                default:
                                    if (string.IsNullOrEmpty(tbValue.Text.Trim()))
                                    {
                                        if (string.IsNullOrEmpty(tbCost.Text.Trim() + tbCredit.Text.Trim()))
                                        {
                                            inputStatus = EHSProfileStatus.NoInputs;
                                        }
                                        else
                                        {
                                            inputStatus = EHSProfileStatus.Incomplete;
                                        }
                                    }
                                    else if (string.IsNullOrEmpty(tbCost.Text.Trim() + tbCredit.Text.Trim()))
                                    {
                                        inputStatus = EHSProfileStatus.Incomplete;
                                    }
                                    else if (dtpFrom.SelectedDate == null || dtpTo.SelectedDate == null)
                                    {
                                        inputStatus = EHSProfileStatus.Incomplete;
                                    }

                                    if (metric.EHS_PROFILE_MEASURE_EXT != null && (metric.EHS_PROFILE_MEASURE_EXT.VALUE_DEFAULT.HasValue || metric.EHS_PROFILE_MEASURE_EXT.COST_DEFAULT.HasValue))
                                    {
                                        if (inputStatus == EHSProfileStatus.Incomplete && (dtpFrom.SelectedDate == null || dtpTo.SelectedDate == null))
                                        {
                                            inputStatus = EHSProfileStatus.NoInputs;
                                        }
                                    }

                                    break;
                                }

                                if (inputStatus == EHSProfileStatus.NoInputs)
                                {
                                    LocalProfile().InputPeriod.DeletePeriodInput(input);
                                }
                                else if (inputStatus == EHSProfileStatus.Incomplete)
                                {
                                    hasSaveError = true;
                                    saveStatus   = EHSProfileStatus.Incomplete;
                                    dtpFrom.DateInput.Style.Add("BACKGROUND-COLOR", "LIGHTCORAL");
                                    dtpTo.DateInput.Style.Add("BACKGROUND-COLOR", "LIGHTCORAL");
                                    tbValue.Style.Add("BACKGROUND-COLOR", "LIGHTCORAL");
                                    if (tbCost.Enabled)
                                    {
                                        tbCost.Style.Add("BACKGROUND-COLOR", "LIGHTCORAL");
                                    }
                                    if (tbCredit.Enabled)
                                    {
                                        tbCredit.Style.Add("BACKGROUND-COLOR", "LIGHTCORAL");
                                    }
                                }

                                //if ((string.IsNullOrEmpty(tbValue.Text) || dtpFrom.SelectedDate == null || dtpTo.SelectedDate == null) || (string.IsNullOrEmpty(tbCost.Text + tbCredit.Text) && metric.EHS_MEASURE.MEASURE_CATEGORY != "PROD" && metric.EHS_MEASURE.MEASURE_CATEGORY != "SAFE" && metric.EHS_MEASURE.MEASURE_CATEGORY != "FACT"))
                                //{
                                //    LocalProfile().InputPeriod.DeletePeriodInput(input);
                                //}
                                else
                                {
                                    ++numInput;

                                    if (cbDelete.Checked)
                                    {
                                        input.STATUS = "D";
                                    }
                                    else if (input.STATUS == "D")
                                    {
                                        input.STATUS = "A";
                                    }

                                    if (input.EFF_FROM_DT > DateTime.MinValue || input.EFF_FROM_DT != dtpFrom.SelectedDate)
                                    {
                                        input.EFF_FROM_DT = (DateTime)dtpFrom.SelectedDate;
                                    }

                                    if (input.EFF_TO_DT > DateTime.MinValue || input.EFF_TO_DT != dtpTo.SelectedDate)
                                    {
                                        input.EFF_TO_DT = (DateTime)dtpTo.SelectedDate;
                                    }

                                    if (SQMBasePage.ParseToDecimal(tbValue.Text, out decimalValue))
                                    {
                                        if (input.MEASURE_VALUE != decimalValue)
                                        {
                                            input.MEASURE_VALUE = decimalValue;
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(tbCredit.Text))
                                    {
                                        SQMBasePage.ParseToDecimal(tbCredit.Text, out decimalValue);
                                        decimalValue = Math.Abs(decimalValue) * -1;
                                        if (!input.MEASURE_COST.HasValue || input.MEASURE_COST != decimalValue)
                                        {
                                            input.MEASURE_COST = decimalValue;
                                        }
                                    }
                                    else
                                    {
                                        SQMBasePage.ParseToDecimal(tbCost.Text, out decimalValue);
                                        decimalValue = Math.Abs(decimalValue);
                                        if (!input.MEASURE_COST.HasValue || input.MEASURE_COST != decimalValue)
                                        {
                                            input.MEASURE_COST = decimalValue;
                                        }
                                    }

                                    if (commitChanges && metric.EHS_MEASURE.MEASURE_CATEGORY != "PROD" && metric.EHS_MEASURE.MEASURE_CATEGORY != "SAFE" && metric.EHS_MEASURE.MEASURE_CATEGORY != "FACT" && LocalProfile().CurrentStatus != EHSProfileStatus.OutOFRange)
                                    {
                                        if (!EHSModel.IsMeasureValueInRange(metric, (double)input.MEASURE_VALUE, 1.0))
                                        {
                                            hasSaveWarning = true;
                                            saveStatus     = EHSProfileStatus.OutOFRange;
                                            tbValue.Style.Add("BACKGROUND-COLOR", "CORNSILK");
                                        }
                                    }
                                }
                            }
                            if (metric != null && (bool)metric.IS_REQUIRED && numInput == 0)
                            {
                                hasReqdInputs = false;
                            }
                        }
                    }
                }

                if (commitChanges)
                {
                    if (hasSaveError)
                    {
                        MessageDisplay(saveStatus);
                        return(0);
                    }

                    if (hasSaveWarning)
                    {
                        MessageDisplay(saveStatus);
                        return(0);
                    }

                    // deleted inputs after approval
                    if ((!string.IsNullOrEmpty(hfNumDelete.Value) && hfNumDelete.Value != "0") && LocalProfile().InputPeriod.PlantAccounting.APPROVAL_DT.HasValue)
                    {
                        cbFinalApproval.Checked = false;
                    }
                    // changed inputs after approval
                    if ((!string.IsNullOrEmpty(hfNumChanged.Value) && hfNumChanged.Value != "0") && LocalProfile().InputPeriod.PlantAccounting.APPROVAL_DT.HasValue)
                    {
                        cbFinalApproval.Checked = false;
                    }

                    status = LocalProfile().UpdatePeriod(true, "", cbFinalApproval.Checked, SessionManager.UserContext.UserName());

                    if (status >= 0)
                    {
                        // option to finalize metrics
                        SETTINGS sets = SQMSettings.GetSetting("EHS", "INPUTFINALIZE");
                        if (sets != null)
                        {
                            bool     doRollup = false;
                            DateTime lastUpdateDate;
                            LocalProfile().PeriodStatus(new string[0] {
                            }, false, out lastUpdateDate);
                            switch (sets.VALUE.ToUpper())
                            {
                            case "ANY":         // finalize any inputs
                                doRollup = true;
                                break;

                            case "ANY_CURRENCY":           // finalize any inputs and if the exchange rate for the period exists
                                if (LocalProfile().InputPeriod.PeriodExchangeRate(LocalProfile().Plant) != null)
                                {
                                    doRollup = true;
                                }
                                break;

                            case "REQD":        // finalize only when all required inputs have been entered
                                if (LocalProfile().InputPeriod.IsRequiredComplete())
                                {
                                    doRollup = true;
                                }
                                break;

                            case "REQD_CURRENCY":           // finalize only when all required inputs are entered and exchange rate for the period exists
                                if (LocalProfile().InputPeriod.IsRequiredComplete() && LocalProfile().InputPeriod.PeriodExchangeRate(LocalProfile().Plant) != null)
                                {
                                    doRollup = true;
                                }
                                break;

                            default:
                                break;
                            }
                            if (doRollup && LocalProfile().ValidPeriod())
                            {
                                status = LocalProfile().UpdateMetricHistory(LocalProfile().InputPeriod.PeriodDate);  // new roll-up logic
                            }
                        }
                    }

                    if (status >= 0)
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alertResult('hfAlertSaveSuccess');", true);
                        hasSaveWarning = false;  // cancel warning to allow re-save
                        MessageDisplay(0);
                        LoadProfileInput(LocalProfile().InputPeriod.PeriodDate, EHSProfileStatus.Normal);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alertResult('hfAlertSaveError');", true);
                        MessageDisplay(0);
                        ClearInput();
                    }
                }
            }
            catch (Exception ex)
            {
                //   SQMLogger.LogException(ex);
                status = -1;
            }

            BindSharedCalendars();

            return(status);
        }
Ejemplo n.º 13
0
        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);
            }
        }
Ejemplo n.º 14
0
        public void LoadProfileInputHdr(bool loadPlants, DateTime dateFrom, DateTime dateTo, decimal defaultPlantID, bool hideUndefined, bool showExpanded)
        {
            ToggleVisible(pnlProfileInputHdr);

            if (loadPlants && ddlPlantSelect.Items.Count == 0)
            {
                List <BusinessLocation> locationList = SQMModelMgr.SelectBusinessLocationList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID, 0, true).Where(l => l.Plant.TRACK_EW_DATA == true).ToList();
                locationList = UserContext.FilterPlantAccessList(locationList);

                int maxdesc = locationList.Select(l => l.Plant.PLANT_NAME.Length).Max();

                if (locationList.Count > 1 && showExpanded && locationList.Select(l => l.Plant.BUS_ORG_ID).Distinct().Count() > 1 && maxdesc < 41)
                {
                    ddlPlantSelect.Visible = false;
                    tdLocation.Visible     = false;
                    mnuPlantSelect.Visible = true;
                    SQMBasePage.SetLocationList(mnuPlantSelect, locationList, 0, "select a location...", "TOP", false);

                    int           undefinedCount = 0;
                    List <string> profileList    = EHSModel.SelectPlantProfileList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID).Select(l => l.PLANT_ID.ToString()).ToList();
                    RadMenuItem   miTop          = mnuPlantSelect.Items[0];
                    foreach (RadMenuItem miBU in miTop.Items)
                    {
                        foreach (RadMenuItem miLoc in miBU.Items)
                        {
                            if (!profileList.Contains(miLoc.Value))
                            {
                                ++undefinedCount;
                                miLoc.ImageUrl = "~/images/defaulticon/16x16/grid-dot.png";
                                miLoc.CssClass = "rcbItemEmphasis";
                                if (hideUndefined)
                                {
                                    miLoc.Visible = false;
                                }
                            }
                        }
                    }
                    if (mnuPlantSelect.FindItemByValue(defaultPlantID.ToString()) != null)
                    {
                        mnuPlantSelect.FindItemByValue(defaultPlantID.ToString()).Selected = true;
                        LocationSelect_Click(mnuPlantSelect, null);
                    }
                }
                else
                {
                    ddlPlantSelect.Visible = true;
                    mnuPlantSelect.Visible = false;
                    SQMBasePage.SetLocationList(ddlPlantSelect, locationList, 0);
                    if (ddlPlantSelect.Items.Count == 1)
                    {
                        tdLocationSelect.Visible = false;
                        tdLocation.Visible       = true;
                        lblPlantName_out.Text    = ddlPlantSelect.SelectedItem.Text;
                        LocationSelect_Click(ddlPlantSelect, null);
                    }
                    else
                    {
                        List <string> profileList    = EHSModel.SelectPlantProfileList(SessionManager.UserContext.HRLocation.Company.COMPANY_ID).Select(l => l.PLANT_ID.ToString()).ToList();
                        int           undefinedCount = 0;
                        foreach (RadComboBoxItem item in ddlPlantSelect.Items)
                        {
                            if (!item.IsSeparator && !profileList.Contains(item.Value))
                            {
                                ++undefinedCount;
                                //item.ImageUrl = "~/images/defaulticon/16x16/grid-dot.png";
                                item.CssClass = "rcbItemEmphasis";
                                item.ToolTip  = "Metrics not defined";
                                if (hideUndefined)
                                {
                                    item.Visible = false;
                                }
                                else
                                {
                                    item.Enabled = false;
                                }
                            }
                        }
                        if (undefinedCount > 0 && !hideUndefined)
                        {
                            ddlPlantSelect.ToolTip += hfPlantProfileUndefined.Value;
                        }

                        tdLocationSelect.Visible = true;
                        tdLocation.Visible       = false;
                        if (ddlPlantSelect.FindItemByValue(defaultPlantID.ToString()) != null)
                        {
                            ddlPlantSelect.SelectedValue = defaultPlantID.ToString();
                            LocationSelect_Click(ddlPlantSelect, null);
                        }
                        else
                        {
                            LocationSelect_Click(ddlPlantSelect, null);
                        }
                    }
                }
            }

            if (dateFrom > DateTime.MinValue)
            {
                radPeriodSelect.Visible = true;
                // radPeriodSelect.Culture = System.Threading.Thread.CurrentThread.CurrentUICulture;
                radPeriodSelect.MinDate          = dateFrom;
                radPeriodSelect.MaxDate          = dateTo;
                radPeriodSelect.ShowPopupOnFocus = true;
                if (dateFrom == dateTo)
                {
                    radPeriodSelect.SelectedDate = dateFrom;
                    radPeriodSelect.Enabled      = false;
                }
                else
                {
                    radPeriodSelect.SelectedDate = DateTime.Now;
                }

                radPeriodSelect.Culture = System.Threading.Thread.CurrentThread.CurrentUICulture;
                tdPeriod.Visible        = false;
                tdPeriodSelect.Visible  = true;
            }
        }
Ejemplo n.º 15
0
        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);
            }
        }
Ejemplo n.º 16
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);
        }
Ejemplo n.º 17
0
        protected void btnMeasureSave_Click(object sender, EventArgs e)
        {
            bool        success;
            EHS_MEASURE subCategory = null;

            if (hfOper.Value == "add")
            {
                staticMeasure                  = new EHS_MEASURE();
                staticMeasure.COMPANY_ID       = SessionManager.UserContext.HRLocation.Company.COMPANY_ID;
                staticMeasure.MEASURE_CATEGORY = ddlMeasureCategory.SelectedValue;
            }
            else
            {
                staticMeasure = EHSModel.LookupEHSMeasure(entities, staticMeasure.MEASURE_ID, "");
            }

            staticMeasure.MEASURE_SUBCATEGORY = ddlMeasureSubcategory.SelectedValue;
            staticMeasure.STATUS       = ddlMeasureStatus.SelectedValue;
            staticMeasure.MEASURE_CD   = tbMeasureCode.Text;
            staticMeasure.MEASURE_NAME = tbMeasureName.Text;
            staticMeasure.MEASURE_DESC = tbMeasureDesc.Text;

            // validate
            if (hfOper.Value == "add" && measureList.FirstOrDefault(l => l.MEASURE_CD == tbMeasureCode.Text) != null)
            {
                BindMeasure(staticMeasure);
                DisplayErrorMessage(hfDuplicateMeasure);
                return;
            }
            if (string.IsNullOrEmpty(staticMeasure.MEASURE_CD) || string.IsNullOrEmpty(staticMeasure.MEASURE_NAME))
            {
                BindMeasure(staticMeasure);
                DisplayErrorMessage(hfErrRequiredInputs);
                return;
            }

            btnMeasureSave.Enabled = false;

            staticMeasure.PLANT_ACCT_FIELD = "";
            if (staticMeasure.MEASURE_CATEGORY == "PROD")
            {
                staticMeasure.PLANT_ACCT_FIELD = ddlProdTableField.SelectedValue;
            }
            else if (staticMeasure.MEASURE_CATEGORY == "SAFE")
            {
                staticMeasure.PLANT_ACCT_FIELD = ddlSafeTableField.SelectedValue;
            }
            else if (staticMeasure.MEASURE_CATEGORY == "FACT")
            {
                if (ddlOutputUOM.SelectedIndex > 0)
                {
                    staticMeasure.STD_UOM = Convert.ToDecimal(ddlOutputUOM.SelectedValue);
                }
                else
                {
                    staticMeasure.STD_UOM = null;
                }
            }

            if (ddlMeasureEFMType.SelectedIndex == 0)
            {
                staticMeasure.EFM_TYPE = null;
            }
            else
            {
                staticMeasure.EFM_TYPE = ddlMeasureEFMType.SelectedValue;
            }

            hfOper.Value = "";

            if ((staticMeasure = EHSModel.UpdateEHSMeasure(entities, staticMeasure, SessionManager.UserContext.UserName())) != null)
            {
                EHS_MEASURE measure;
                if ((measure = measureList.FirstOrDefault(l => l.MEASURE_ID == staticMeasure.MEASURE_ID)) == null)
                {
                    measureList.Add(staticMeasure);
                }
                else
                {
                    if (staticMeasure.EntityState == System.Data.EntityState.Detached || staticMeasure.EntityState == System.Data.EntityState.Deleted)
                    {
                        measureList.Remove(measure);
                    }
                    else
                    {
                        measure = (EHS_MEASURE)SQMModelMgr.CopyObjectValues(measure, staticMeasure, false);
                    }
                }

                ClearMeasure(null, null);
                BindMeasureList(measureList);
            }
        }
Ejemplo n.º 18
0
        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);
                }
            }
        }
Ejemplo n.º 19
0
        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);
            }
        }
Ejemplo n.º 20
0
        private void SetupProfilePanel()
        {
            if (ddlMetricDisposalCode.Items.Count == 0)
            {
                ddlDayDue.Items.AddRange(WebSiteCommon.PopulateDropDownListNums(1, 31));
                ddlWarningDays.Items.AddRange(WebSiteCommon.PopulateDropDownListNums(0, 11));

                disposalList = EHSModel.SelectDisposalCodeList(true);
                ddlMetricDisposalCode.DataSource     = disposalList;
                ddlMetricDisposalCode.DataValueField = "UN_CODE";
                ddlMetricDisposalCode.DataTextField  = "UN_CODE";
                ddlMetricDisposalCode.DataBind();
                ddlMetricDisposalCode.Items.Insert(0, new ListItem(""));

                ddlMetricRegStatus.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("regulatoryStatus"));
                ddlMetricRegStatus.Items.Insert(0, new ListItem(""));

                ddlMetricResponsible.DataSource     = SQMModelMgr.SelectPersonList(SessionManager.ActiveCompany().COMPANY_ID, 0, false);
                ddlMetricResponsible.DataValueField = "PERSON_ID";
                ddlMetricResponsible.DataTextField  = "EMAIL";
                ddlMetricResponsible.DataBind();
                ddlMetricResponsible.Items.Insert(0, new ListItem(""));
                ddlMetricResponsible.SelectedIndex = 0;

                ddlMetricCurrency.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("currencyCode", "long"));
                ddlMetricCurrency.SelectedValue = "EUR";

                ddlMetricStatus.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("statusCode"));

                ddlMetricCategory.Items.AddRange(WebSiteCommon.PopulateDropDownListItems("measureCategoryEHS"));
                ddlMetricCategory.Items.Insert(0, "");

                measureList = EHSModel.SelectEHSMeasureList("", true);
                foreach (EHS_MEASURE measure in measureList)
                {
                    ddlMetricID.Items.Add(new ListItem(measure.MEASURE_NAME, WebSiteCommon.PackItemValue(measure.MEASURE_CATEGORY, measure.MEASURE_ID.ToString())));
                }
                ddlMetricID.Items.Insert(0, "");


                foreach (UOM uom in SessionManager.UOMList)
                {
                    if (uom.OWNER_ID.HasValue == false)
                    {
                        ddlMetricUOM.Items.Add(new ListItem(uom.UOM_NAME, WebSiteCommon.PackItemValue(uom.UOM_CATEGORY, uom.UOM_ID.ToString())));
                        ddlUserUOMConvertTo.Items.Add(new ListItem(uom.UOM_NAME, WebSiteCommon.PackItemValue(uom.UOM_CATEGORY, uom.UOM_ID.ToString())));
                    }
                }
                ListItem separator = new ListItem("---------------------", "");
                separator.Attributes.Add("disabled", "true");
                ddlMetricUOM.Items.Add(separator);
                foreach (UOM uom in SessionManager.UOMList)
                {
                    if ((uom.OWNER_ID.HasValue && uom.OWNER_ID == staticProfile.Plant.PLANT_ID))
                    {
                        ddlMetricUOM.Items.Add(new ListItem(uom.UOM_NAME, WebSiteCommon.PackItemValue(uom.UOM_CATEGORY, uom.UOM_ID.ToString())));
                    }
                }
                ddlMetricUOM.Items.Insert(0, "");
                ddlMetricUOM.SelectedIndex = 0;
            }
            UpdateListTitles();
        }
Ejemplo n.º 21
0
        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);
            }
        }