public IActionResult OnGet()
        {
            PageInit();
            if (ErpPage == null)
            {
                return(NotFound());
            }


            var componentLibrary = new PageComponentLibraryService().GetPageComponentsList();

            foreach (var component in componentLibrary)
            {
                if (component.Description.Length >= 120)
                {
                    component.Description = component.Description.Substring(0, 120) + "...";
                }
                //Apply component Usage
                var userUsage = CurrentUser.Preferences.ComponentUsage.FirstOrDefault(x => x.Name == component.Name);
                if (userUsage != null)
                {
                    component.LastUsedOn   = userUsage.SdkUsedOn;
                    component.UsageCounter = userUsage.SdkUsed;
                }
            }

            LibraryJson = JsonConvert.SerializeObject(componentLibrary);
            var pageNodes = new PageService().GetPageNodes(ErpPage.Id);

            PageNodeListJson = JsonConvert.SerializeObject(pageNodes);

            ErpRequestContext.PageContext = PageContext;
            return(Page());
        }
Beispiel #2
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query parameter 'pid', when requesting this component")));
                }

                var options = new PcSectionOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcSectionOptions>(context.Options.ToString());
                }

                //Check if it is defined in form group
                if (options.LabelMode == WvLabelRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(WvLabelRenderMode)))
                    {
                        options.LabelMode = (WvLabelRenderMode)context.Items[typeof(WvLabelRenderMode)];
                    }
                    else
                    {
                        options.LabelMode = WvLabelRenderMode.Stacked;
                    }
                }

                //Check if it is defined in form group
                if (options.FieldMode == WvFieldRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(WvFieldRenderMode)))
                    {
                        options.FieldMode = (WvFieldRenderMode)context.Items[typeof(WvFieldRenderMode)];
                    }
                    else
                    {
                        options.FieldMode = WvFieldRenderMode.Form;
                    }
                }
                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                //Init IsCollapsed from userPreferences
                if (HttpContext.User != null)
                {
                    var currentUser = AuthService.GetUser(HttpContext.User);
                    if (currentUser != null)
                    {
                        var componentData = new UserPreferencies().GetComponentData(currentUser.Id, "WebVella.Erp.Web.Components.PcSection");
                        if (componentData != null)
                        {
                            var collapsedNodeIds   = new List <Guid>();
                            var uncollapsedNodeIds = new List <Guid>();
                            if (componentData.Properties.ContainsKey("collapsed_node_ids") && componentData["collapsed_node_ids"] != null)
                            {
                                if (componentData["collapsed_node_ids"] is string)
                                {
                                    try
                                    {
                                        collapsedNodeIds = JsonConvert.DeserializeObject <List <Guid> >((string)componentData["collapsed_node_ids"]);
                                    }
                                    catch
                                    {
                                        throw new Exception("WebVella.Erp.Web.Components.PcSection component data object in user preferences not in the correct format. collapsed_node_ids should be List<Guid>");
                                    }
                                }
                                else if (componentData["collapsed_node_ids"] is List <Guid> )
                                {
                                    collapsedNodeIds = (List <Guid>)componentData["collapsed_node_ids"];
                                }
                                else if (componentData["collapsed_node_ids"] is JArray)
                                {
                                    collapsedNodeIds = ((JArray)componentData["collapsed_node_ids"]).ToObject <List <Guid> >();
                                }
                                else
                                {
                                    throw new Exception("Unknown format of collapsed_node_ids");
                                }
                            }
                            if (componentData.Properties.ContainsKey("uncollapsed_node_ids") && componentData["uncollapsed_node_ids"] != null)
                            {
                                if (componentData["uncollapsed_node_ids"] is string)
                                {
                                    try
                                    {
                                        uncollapsedNodeIds = JsonConvert.DeserializeObject <List <Guid> >((string)componentData["uncollapsed_node_ids"]);
                                    }
                                    catch
                                    {
                                        throw new Exception("WebVella.Erp.Web.Components.PcSection component data object in user preferences not in the correct format. uncollapsed_node_ids should be List<Guid>");
                                    }
                                }
                                else if (componentData["uncollapsed_node_ids"] is List <Guid> )
                                {
                                    uncollapsedNodeIds = (List <Guid>)componentData["uncollapsed_node_ids"];
                                }
                                else if (componentData["uncollapsed_node_ids"] is JArray)
                                {
                                    uncollapsedNodeIds = ((JArray)componentData["uncollapsed_node_ids"]).ToObject <List <Guid> >();
                                }
                                else
                                {
                                    throw new Exception("Unknown format of uncollapsed_node_ids");
                                }
                            }
                            if (collapsedNodeIds.Contains(context.Node.Id))
                            {
                                options.IsCollapsed = true;
                            }
                            else if (uncollapsedNodeIds.Contains(context.Node.Id))
                            {
                                options.IsCollapsed = false;
                            }
                        }
                    }
                }


                #endregion


                ViewBag.Options            = options;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                if (context.Mode == ComponentMode.Display || context.Mode == ComponentMode.Design)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    ViewBag.ProcessedTitle = context.DataModel.GetPropertyValueByDataSource(options.Title);

                    var isCollapsed = context.DataModel.GetPropertyValueByDataSource(options.IsCollapsedDs) as bool?;
                    if (isCollapsed != null)
                    {
                        options.IsCollapsed = isCollapsed.Value;
                        ViewBag.Options     = options;
                    }
                    else if (options.IsCollapsedDs.ToLowerInvariant() == "true")
                    {
                        options.IsCollapsed = true;
                        ViewBag.Options     = options;
                    }
                }

                context.Items[typeof(WvLabelRenderMode)] = options.LabelMode;
                context.Items[typeof(WvFieldRenderMode)] = options.FieldMode;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    ViewBag.LabelRenderModeOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvLabelRenderMode>();
                    ViewBag.FieldRenderModeOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvFieldRenderMode>();
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #3
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcChartOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcChartOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                var theme            = new Theme();
                var colorOptionsList = new List <string>()
                {
                    theme.TealColor, theme.PinkColor, theme.GreenColor, theme.OrangeColor, theme.RedColor, theme.PurpleColor, theme.DeepPurpleColor,
                    theme.BlueColor, theme.LightBlueColor, theme.CyanColor, theme.GreenColor, theme.IndigoColor, theme.LightGreenColor, theme.LimeColor, theme.YellowColor,
                    theme.AmberColor, theme.DeepOrangeColor
                };

                var bkgColorOptionsList = new List <string>()
                {
                    theme.TealLightColor, theme.PinkLightColor, theme.GreenLightColor, theme.OrangeLightColor, theme.RedLightColor, theme.PurpleLightColor, theme.DeepPurpleLightColor,
                    theme.BlueLightColor, theme.LightBlueLightColor, theme.CyanLightColor, theme.GreenLightColor, theme.IndigoLightColor, theme.LightGreenLightColor, theme.LimeLightColor, theme.YellowLightColor,
                    theme.AmberLightColor, theme.DeepOrangeLightColor
                };

                List <ErpChartDataset> dataSets = context.DataModel.GetPropertyValueByDataSource(options.Datasets) as List <ErpChartDataset> ?? new List <ErpChartDataset>();

                if (dataSets == null || dataSets.Count == 0)
                {
                    var decimalList = new List <decimal>();
                    decimalList = context.DataModel.GetPropertyValueByDataSource(options.Datasets) as List <decimal> ?? new List <decimal>();
                    if ((dataSets == null || dataSets.Count == 0) && !String.IsNullOrWhiteSpace(options.Datasets) && options.Datasets.Contains(","))
                    {
                        var optionValueCsv   = options.Datasets.Split(",");
                        var csvDecimalList   = new List <decimal>();
                        var csvParseHasError = false;
                        foreach (var valueString in optionValueCsv)
                        {
                            if (Decimal.TryParse(valueString.Trim(), out decimal outDecimal))
                            {
                                csvDecimalList.Add(outDecimal);
                            }
                            else
                            {
                                csvParseHasError = true;
                                break;
                            }
                        }
                        if (!csvParseHasError)
                        {
                            decimalList = csvDecimalList;
                        }
                    }

                    if (decimalList != null && decimalList.Count > 0)
                    {
                        var dataSet = new ErpChartDataset();
                        dataSet.Data = decimalList;
                        if (options.Type == ErpChartType.Area || options.Type == ErpChartType.Line)
                        {
                            dataSet.BorderColor     = colorOptionsList[0];
                            dataSet.BackgroundColor = bkgColorOptionsList[0];
                        }
                        else
                        {
                            dataSet.BorderColor     = new List <string>();
                            dataSet.BackgroundColor = new List <string>();
                            var index = 0;
                            foreach (var value in decimalList)
                            {
                                ((List <string>)dataSet.BorderColor).Add(colorOptionsList[index]);
                                if (options.Type == ErpChartType.Bar || options.Type == ErpChartType.HorizontalBar)
                                {
                                    ((List <string>)dataSet.BackgroundColor).Add(bkgColorOptionsList[index]);
                                }
                                else
                                {
                                    ((List <string>)dataSet.BackgroundColor).Add(colorOptionsList[index]);
                                }
                                index++;
                            }
                        }
                        dataSets.Add(dataSet);
                    }
                }

                List <string> labels = context.DataModel.GetPropertyValueByDataSource(options.Labels) as List <string> ?? new List <string>();
                if ((labels == null || labels.Count == 0) && !String.IsNullOrWhiteSpace(options.Labels) && options.Labels.Contains(","))
                {
                    labels = options.Labels.Split(",").ToList();
                }

                ViewBag.DataSets = dataSets;
                ViewBag.Labels   = labels;
                var chartTypeOptions = ModelExtensions.GetEnumAsSelectOptions <ErpChartType>();
                chartTypeOptions.First(x => x.Value == "4").Label = "area";
                ViewBag.ChartTypeOptions = chartTypeOptions;
                ViewBag.ShowLegend       = options.ShowLegend;
                ViewBag.Height           = options.Height;
                ViewBag.Width            = options.Width;
                ViewBag.Type             = (ErpChartType)options.Type;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #4
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query param 'pid', when requesting this component")));
                }

                var instanceOptions = new PcSectionOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcSectionOptions>(context.Options.ToString());
                }

                //Check if it is defined in form group
                if (instanceOptions.LabelMode == LabelRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(LabelRenderMode)))
                    {
                        instanceOptions.LabelMode = (LabelRenderMode)context.Items[typeof(LabelRenderMode)];
                    }
                    else
                    {
                        instanceOptions.LabelMode = LabelRenderMode.Stacked;
                    }
                }

                //Check if it is defined in form group
                if (instanceOptions.FieldMode == FieldRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(FieldRenderMode)))
                    {
                        instanceOptions.FieldMode = (FieldRenderMode)context.Items[typeof(FieldRenderMode)];
                    }
                    else
                    {
                        instanceOptions.FieldMode = FieldRenderMode.Form;
                    }
                }
                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options            = instanceOptions;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                if (context.Mode == ComponentMode.Display || context.Mode == ComponentMode.Design)
                {
                    ViewBag.ProcessedTitle = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Title);
                }

                context.Items[typeof(LabelRenderMode)] = instanceOptions.LabelMode;
                context.Items[typeof(FieldRenderMode)] = instanceOptions.FieldMode;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    ViewBag.LabelRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <LabelRenderMode>();
                    ViewBag.FieldRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldRenderMode>();
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcApplicationsOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcApplicationsOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = instanceOptions;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var currentUser = AuthService.GetUser(HttpContext.User);

                    var currentUserRoles = currentUser.Roles.Select(x => x.Id);
                    var apps             = new AppService().GetAllApplications().OrderBy(x => x.Weight).ToList();
                    var allowedApps      = new List <App>();
                    if (apps != null)
                    {
                        foreach (var app in apps)
                        {
                            if (app.Access == null || app.Access.Count == 0)
                            {
                                continue;
                            }

                            IEnumerable <Guid> accessRoles = app.Access.Intersect(currentUserRoles);
                            if (accessRoles.Any())
                            {
                                allowedApps.Add(app);
                            }
                        }
                    }
                    //Generate Url
                    foreach (var app in allowedApps)
                    {
                        app.HomePages = app.HomePages.FindAll(x => x.Weight < 1000).OrderBy(x => x.Weight).ToList();
                        foreach (var area in app.Sitemap.Areas)
                        {
                            foreach (var node in area.Nodes)
                            {
                                node.Url = PageUtils.GenerateSitemapNodeUrl(node, area, app);
                            }
                        }
                        app.Sitemap = new AppService().OrderSitemap(app.Sitemap);
                    }
                    ViewBag.Apps = allowedApps;
                }


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #6
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcHtmlBlockOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcHtmlBlockOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = instanceOptions;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                ViewBag.ProccessedHtml = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Html);

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #7
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTasksPriorityChartOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksPriorityChartOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid?projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid?;
                    Guid?userId    = context.DataModel.GetPropertyValueByDataSource(options.UserId) as Guid?;


                    var projectTasks   = new TaskService().GetTaskQueue(projectId, userId, TasksDueType.StartTimeDue);
                    int lowPriority    = 0;
                    int normalPriority = 0;
                    int highPriority   = 0;

                    foreach (var task in projectTasks)
                    {
                        var taskPriority = (string)task["priority"];
                        switch (taskPriority)
                        {
                        case "1":
                            lowPriority++;
                            break;

                        case "2":
                            normalPriority++;
                            break;

                        case "3":
                            highPriority++;
                            break;

                        default:
                            throw new Exception("Unknown task priority: " + taskPriority);
                        }
                    }


                    var theme         = new Theme();
                    var chartDatasets = new List <ErpChartDataset>()
                    {
                        new ErpChartDataset()
                        {
                            Data = new List <decimal>()
                            {
                                highPriority, normalPriority, lowPriority
                            },
                            BackgroundColor = new List <string> {
                                theme.RedColor, theme.LightBlueColor, theme.GreenColor
                            },
                            BorderColor = new List <string> {
                                theme.RedColor, theme.LightBlueColor, theme.GreenColor
                            }
                        }
                    };

                    ViewBag.LowPriority     = lowPriority;
                    ViewBag.NormalPriority  = normalPriority;
                    ViewBag.HighPriority    = highPriority;
                    ViewBag.PriorityOptions = ((SelectField) new EntityManager().ReadEntity("task").Object.Fields.First(x => x.Name == "priority")).Options;
                    ViewBag.Datasets        = chartDatasets;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldCheckboxOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldCheckboxOptions>(context.Options.ToString());
                    ////Check for connection to entity field
                    //if (instanceOptions.TryConnectToEntity)
                    //{
                    //	var entity = context.DataModel.GetProperty("Entity");
                    //	if (entity != null && entity is Entity)
                    //	{
                    //		var fieldName = instanceOptions.Name;
                    //		var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    //		if (entityField != null && entityField is CheckboxField)
                    //		{
                    //			var castedEntityField = ((CheckboxField)entityField);
                    //			//No options connected
                    //		}
                    //	}
                    //}
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as FieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                #endregion



                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    #region << Init DataSources >>
                    dynamic valueResult = context.DataModel.GetPropertyValueByDataSource(options.Value);
                    if (valueResult == null)
                    {
                        model.Value = false;
                    }
                    else if (valueResult is bool)
                    {
                        model.Value = (bool)valueResult;
                    }
                    else if (valueResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(valueResult))
                        {
                            model.Value     = false;
                            stringProcessed = true;
                        }
                        if (!stringProcessed && ((string)valueResult) == "true")
                        {
                            model.Value = true;
                        }
                        else
                        {
                            model.Value = false;
                        }
                    }
                    #endregion
                }


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #9
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcFeedListOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFeedListOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.CurrentUser      = SecurityContext.CurrentUser;
                ViewBag.CurrentUserJson  = JsonConvert.SerializeObject(SecurityContext.CurrentUser);

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var inputRecords    = context.DataModel.GetPropertyValueByDataSource(options.Records) as List <EntityRecord> ?? new List <EntityRecord>();
                    var groupedRecords  = inputRecords.GroupBy(x => ((DateTime)x["created_on"]).ToString("dd MMMM")).ToList();
                    var groupedFeedList = new EntityRecord();
                    foreach (var feedDate in groupedRecords)
                    {
                        groupedFeedList[feedDate.Key] = feedDate;
                    }
                    ViewBag.RecordsJson = JsonConvert.SerializeObject(groupedFeedList);
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #10
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcTimelogListOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcTimelogListOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.CurrentUser      = SecurityContext.CurrentUser;
                ViewBag.CurrentUserJson  = JsonConvert.SerializeObject(SecurityContext.CurrentUser);

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var relatedRecordId = (Guid?)context.DataModel.GetProperty("Record.id");
                    if (relatedRecordId == null)
                    {
                        throw new Exception("Record.id detasource returns null");
                    }

                    var entityName     = (string)context.DataModel.GetProperty("Entity.Name");
                    var relatedRecords = new List <Guid>();
                    relatedRecords.Add(relatedRecordId.Value);
                    switch (entityName)
                    {
                    case "task":
                    {
                        var eqlCommand = "SELECT $project_nn_task.id FROM task WHERE id = @recordId";
                        var eqlParams  = new List <EqlParameter>()
                        {
                            new EqlParameter("recordId", relatedRecordId)
                        };
                        var eqlResult = new EqlCommand(eqlCommand, eqlParams).Execute();
                        if (eqlResult.Any())
                        {
                            var taskRecord = eqlResult[0];
                            if (taskRecord.Properties.ContainsKey("$project_nn_task") && taskRecord["$project_nn_task"] != null)
                            {
                                if (((List <EntityRecord>)taskRecord["$project_nn_task"]).Any())
                                {
                                    var projectRecord = ((List <EntityRecord>)taskRecord["$project_nn_task"])[0];
                                    if (projectRecord.Properties.ContainsKey("id") && projectRecord["id"] != null)
                                    {
                                        relatedRecords.Add((Guid)projectRecord["id"]);
                                    }
                                }
                            }
                        }
                    }
                    break;

                    default:
                        break;
                    }

                    ViewBag.RelatedRecordId    = relatedRecordId;
                    ViewBag.RelatedRecordsJson = JsonConvert.SerializeObject(relatedRecords);

                    var inputRecords = context.DataModel.GetPropertyValueByDataSource(options.Records) as List <EntityRecord> ?? new List <EntityRecord>();
                    ViewBag.RecordsJson = JsonConvert.SerializeObject(inputRecords);
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #11
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcFormOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcFormOptions>(context.Options.ToString());
                    if (instanceOptions.LabelMode == LabelRenderMode.Undefined)
                    {
                        instanceOptions.LabelMode = LabelRenderMode.Stacked;
                    }
                    if (instanceOptions.Mode == FieldRenderMode.Undefined)
                    {
                        instanceOptions.Mode = FieldRenderMode.Form;
                    }
                }

                if (String.IsNullOrWhiteSpace(instanceOptions.Id))
                {
                    instanceOptions.Id = "wv-" + context.Node.Id.ToString();
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                var isVisible   = true;
                var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IsVisible);
                if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                {
                    if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                    {
                        isVisible = outBool;
                    }
                }
                else if (isVisibleDS is Boolean)
                {
                    isVisible = (bool)isVisibleDS;
                }
                ViewBag.IsVisible = isVisible;

                ViewBag.Options            = instanceOptions;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                ViewBag.LabelRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <LabelRenderMode>();

                ViewBag.FieldRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldRenderMode>();


                context.Items[typeof(LabelRenderMode)] = instanceOptions.LabelMode;
                context.Items[typeof(FieldRenderMode)] = instanceOptions.Mode;

                var validation = context.DataModel.GetProperty("Validation") as ValidationException ?? new ValidationException();

                context.Items[typeof(ValidationException)] = validation;
                ViewBag.Validation = validation;

                ViewBag.Action = "";
                if (!String.IsNullOrWhiteSpace(instanceOptions.HookKey))
                {
                    var queryList = new List <SelectOption>();
                    foreach (var key in HttpContext.Request.Query.Keys)
                    {
                        if (key != "hookKey")
                        {
                            queryList.Add(new SelectOption(key, HttpContext.Request.Query[key].ToString()));
                        }
                    }
                    queryList.Add(new SelectOption("hookKey", instanceOptions.HookKey));                    //override even if already present

                    ViewBag.Action = string.Format(HttpContext.Request.Path + "?{0}", string.Join("&", queryList.Select(kvp => string.Format("{0}={1}", kvp.Value, kvp.Label))));
                }

                ViewBag.MethodOptions = new List <SelectOption>()
                {
                    new SelectOption("get", "get"),
                    new SelectOption("post", "post")
                };


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTimesheetOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTimesheetOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid?projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid?;
                    Guid?userId    = context.DataModel.GetPropertyValueByDataSource(options.UserId) as Guid?;

                    var             nowDate   = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, DateTimeKind.Local);
                    List <DateTime> last7Days = Enumerable.Range(0, 7).Select(i => nowDate.AddDays(-6).Date.AddDays(i)).ToList();
                    var             startDate = new DateTime(last7Days[0].Year, last7Days[0].Month, last7Days[0].Day, 0, 0, 0, DateTimeKind.Local);
                    var             endDate   = nowDate.AddDays(1);       //Get End of current date

                    var projectTimelogs = new TimeLogService().GetTimelogsForPeriod(projectId, userId, startDate, endDate);

                    var users = new UserService().GetAll();

                    #region << Generate Grid Columns >>
                    var gridColumns = new List <GridColumn>()
                    {
                        new GridColumn()
                    };
                    foreach (var date in last7Days)
                    {
                        gridColumns.Add(new GridColumn()
                        {
                            Label = date.ToString("dd MMM"),
                            Width = "10%",
                            Class = "text-right"
                        });
                    }
                    gridColumns.Add(new GridColumn()
                    {
                        Label = "Total",
                        Width = "10%",
                        Class = "font-weight-bold text-right"
                    });
                    ViewBag.GridColumns = gridColumns;
                    #endregion

                    var records = new List <EntityRecord>();                    //id and other fields
                    #region << Init Rows >>
                    {
                        var billableRow = new EntityRecord();
                        billableRow["id"]    = "billable";
                        billableRow["label"] = "Billable";
                        billableRow["total"] = (decimal)0;
                        records.Add(billableRow);
                        var nonbillableRow = new EntityRecord();
                        nonbillableRow["id"]    = "nonbillable";
                        nonbillableRow["label"] = "Non-Billable";
                        nonbillableRow["total"] = (decimal)0;
                        records.Add(nonbillableRow);
                        var totalRow = new EntityRecord();
                        totalRow["id"]    = "total";
                        totalRow["label"] = "Total";
                        totalRow["total"] = (decimal)0;
                        records.Add(totalRow);
                    }
                    #endregion

                    var timelogsGroupByDate = projectTimelogs.GroupBy(x => (((DateTime?)x["logged_on"]).ConvertToAppDate() ?? DateTime.Now).ToString("dd-MM")).ToList();

                    for (int i = 0; i < 7; i++)
                    {
                        var billableRow    = records.First(x => (string)x["id"] == "billable");
                        var nonbillableRow = records.First(x => (string)x["id"] == "nonbillable");
                        var totalRow       = records.First(x => (string)x["id"] == "total");

                        billableRow.Properties.Add("day" + (i + 1), (decimal)0);
                        nonbillableRow.Properties.Add("day" + (i + 1), (decimal)0);
                        totalRow.Properties.Add("day" + (i + 1), (decimal)0);

                        var dateString   = last7Days[i].ToString("dd-MM");
                        var dateLogGroup = timelogsGroupByDate.FirstOrDefault(x => x.Key == dateString);
                        if (dateLogGroup != null)
                        {
                            var dateLogs = dateLogGroup.ToList();
                            foreach (var timelog in dateLogs)
                            {
                                totalRow["day" + (i + 1)] = (decimal)totalRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                if ((bool)timelog["is_billable"])
                                {
                                    billableRow["day" + (i + 1)] = (decimal)billableRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                    billableRow["total"]         = (decimal)billableRow["total"] + (decimal)timelog["minutes"];
                                }
                                else
                                {
                                    nonbillableRow["day" + (i + 1)] = (decimal)nonbillableRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                    nonbillableRow["total"]         = (decimal)nonbillableRow["total"] + (decimal)timelog["minutes"];
                                }
                                totalRow["total"] = (decimal)totalRow["total"] + (decimal)timelog["minutes"];
                            }
                        }
                    }

                    if (userId == null)
                    {
                        var timelogsGroupByCreator = projectTimelogs.GroupBy(x => (Guid)x["created_by"]).ToList();
                        foreach (var userGroup in timelogsGroupByCreator)
                        {
                            var user      = users.First(x => (Guid)x["id"] == userGroup.Key);
                            var imagePath = "/assets/avatar.png";
                            if (user["image"] != null && (string)user["image"] != "")
                            {
                                imagePath = "/fs" + (string)user["image"];
                            }

                            var userTimelogs            = userGroup.ToList();
                            var userTimelogsGroupByDate = userTimelogs.GroupBy(x => (((DateTime?)x["logged_on"]).ConvertToAppDate() ?? DateTime.Now).ToString("dd-MM")).ToList();
                            var userRow = new EntityRecord();
                            userRow["id"]    = (string)user["username"];
                            userRow["label"] = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                            userRow["total"] = (decimal)0;

                            for (int i = 0; i < 7; i++)
                            {
                                userRow.Properties.Add("day" + (i + 1), (decimal)0);
                                var dateString   = last7Days[i].ToString("dd-MM");
                                var dateLogGroup = userTimelogsGroupByDate.FirstOrDefault(x => x.Key == dateString);
                                if (dateLogGroup != null)
                                {
                                    var dateLogs = dateLogGroup.ToList();
                                    foreach (var timelog in dateLogs)
                                    {
                                        userRow["day" + (i + 1)] = (decimal)userRow["day" + (i + 1)] + (decimal)timelog["minutes"];
                                        userRow["total"]         = (decimal)userRow["total"] + (decimal)timelog["minutes"];
                                    }
                                }
                            }
                            records.Add(userRow);
                        }
                    }
                    ViewBag.Records = records;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #13
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTasksDueTodayOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksDueTodayOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid? ?? Guid.Empty;

                    if (projectId == Guid.Empty)
                    {
                        return(await Task.FromResult <IViewComponentResult>(Content("Error: ProjectId is required")));
                    }

                    var projectRecord = new ProjectService().Get(projectId);
                    var projectTasks  = new TaskService().GetTasks(projectId, null);

                    var overdueTasks = new List <EntityRecord>();
                    var users        = new UserService().GetAll();

                    foreach (var task in projectTasks)
                    {
                        var targetDate = (DateTime?)task["target_date"];

                        if (targetDate != null)
                        {
                            var erpTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ErpSettings.TimeZoneName);
                            targetDate = TimeZoneInfo.ConvertTimeFromUtc(targetDate.Value, erpTimeZone);
                            if (targetDate.Value.Date == DateTime.Now.Date)
                            {
                                var user      = users.First(x => (Guid)x["id"] == (Guid)task["owner_id"]);
                                var imagePath = "/assets/avatar.png";
                                if (user["image"] != null && (string)user["image"] != "")
                                {
                                    imagePath = "/fs" + (string)user["image"];
                                }

                                string iconClass = "";
                                string color     = "";
                                new TaskService().GetTaskIconAndColor((string)task["priority"], out iconClass, out color);

                                var row = new EntityRecord();
                                row["task"] = $"<i class='{iconClass}' style='color:{color}'></i> <a target=\"_blank\" href=\"/projects/tasks/tasks/r/{(Guid)task["id"]}/details\">[{task["key"]}] {task["subject"]}</a>";
                                row["user"] = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                                row["date"] = targetDate;
                                overdueTasks.Add(row);
                            }
                        }
                    }
                    ViewBag.Records = overdueTasks;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcGridFilterFieldOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcGridFilterFieldOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                var selectedQueryOptionsConverted = new List <string>();
                foreach (var option in options.QueryOptions)
                {
                    selectedQueryOptionsConverted.Add(((int)option).ToString());
                }
                ViewBag.ConvertedSelectedQueryOptions = selectedQueryOptionsConverted;

                if (context.Mode == ComponentMode.Options)
                {
                    ViewBag.FieldTypeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldType>();
                    var filterOptions = ModelExtensions.GetEnumAsSelectOptions <FilterType>();
                    var idField       = filterOptions.Single(x => x.Value == ((int)FilterType.Undefined).ToString());
                    filterOptions.Remove(idField);
                    ViewBag.FilterTypeOptions = filterOptions;
                }

                ViewBag.ValueOptions = new List <SelectOption>();
                var entity = context.DataModel.GetProperty("Entity");
                if (options.TryConnectToEntity)
                {
                    var fieldName   = options.Name;
                    var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    if (entityField != null)
                    {
                        //Connection success override the local options
                        //Init model
                        if (String.IsNullOrWhiteSpace(options.Label))
                        {
                            options.Label = entityField.Label;
                        }

                        //Specific model properties
                        var fieldOptions = new List <SelectOption>();
                        switch (entityField.GetFieldType())
                        {
                        case FieldType.AutoNumberField:
                            options.FieldType = FieldType.AutoNumberField;
                            break;

                        case FieldType.CheckboxField:
                            options.FieldType = FieldType.CheckboxField;
                            break;

                        case FieldType.CurrencyField:
                            options.FieldType = FieldType.CurrencyField;
                            break;

                        case FieldType.DateField:
                            options.FieldType = FieldType.DateField;
                            break;

                        case FieldType.DateTimeField:
                            options.FieldType = FieldType.DateTimeField;
                            break;

                        case FieldType.EmailField:
                            options.FieldType = FieldType.EmailField;
                            break;

                        case FieldType.FileField:
                            options.FieldType = FieldType.FileField;
                            break;

                        case FieldType.GuidField:
                            options.FieldType = FieldType.GuidField;
                            break;

                        case FieldType.HtmlField:
                            options.FieldType = FieldType.HtmlField;
                            break;

                        case FieldType.ImageField:
                            options.FieldType = FieldType.ImageField;
                            break;

                        case FieldType.MultiLineTextField:
                            options.FieldType = FieldType.MultiLineTextField;
                            break;

                        case FieldType.NumberField:
                            options.FieldType = FieldType.NumberField;
                            break;

                        case FieldType.PercentField:
                            options.FieldType = FieldType.PercentField;
                            break;

                        case FieldType.PhoneField:
                            options.FieldType = FieldType.PhoneField;
                            break;

                        case FieldType.SelectField:
                            options.FieldType = FieldType.SelectField;
                            var selectField = ((SelectField)entityField);
                            ViewBag.ValueOptions = selectField.Options;
                            break;

                        case FieldType.MultiSelectField:
                            options.FieldType = FieldType.MultiSelectField;
                            break;

                        case FieldType.TextField:
                            options.FieldType = FieldType.TextField;
                            break;

                        case FieldType.UrlField:
                            options.FieldType = FieldType.UrlField;
                            break;

                        default:
                            throw new Exception("No such field Type");
                        }
                    }
                }

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #15
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }


                var optionsObject = InitOptions(context.Options);

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                #endregion

                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.Options          = optionsObject;
                ViewBag.ComponentContext = context;

                ViewBag.WvFlexSelfAlignTypeOptions   = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvFlexSelfAlignType>();
                ViewBag.FlexVerticalAlignmentOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvFlexVerticalAlignmentType>();

                ViewBag.FlexHorizontalAlignmentOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvFlexHorizontalAlignmentType>();

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #16
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcRepeaterOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcRepeaterOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    if (!isVisible && context.Mode == ComponentMode.Display)
                    {
                        return(await Task.FromResult <IViewComponentResult>(Content("")));
                    }

                    ViewBag.Records = context.DataModel.GetPropertyValueByDataSource(options.Records) as List <EntityRecord> ?? new List <EntityRecord>();
                }

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldMultiSelectOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldMultiSelectOptions>(context.Options.ToString());
                }
                var modelFieldLabel = "";
                var model           = (PcFieldMultiSelectModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel, targetModel: "PcFieldMultiSelectModel");
                if (String.IsNullOrWhiteSpace(options.LabelText) && context.Mode != ComponentMode.Options)
                {
                    options.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == WvLabelRenderMode.Undefined && baseOptions.LabelMode != WvLabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == WvFieldRenderMode.Undefined && baseOptions.Mode != WvFieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as WvFieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?;
                if (requiredOverride != null)
                {
                    model.Required = requiredOverride.Value;
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(options.RequiredOverrideDs))
                    {
                        if (options.RequiredOverrideDs.ToLowerInvariant() == "true")
                        {
                            model.Required = true;
                        }
                        else if (options.RequiredOverrideDs.ToLowerInvariant() == "false")
                        {
                            model.Required = false;
                        }
                    }
                }
                #endregion


                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    #region << Init DataSources >>

                    dynamic valueResult = context.DataModel.GetPropertyValueByDataSource(options.Value);
                    if (valueResult == null)
                    {
                        model.Value = new List <string>();
                    }
                    else if (valueResult is List <string> )
                    {
                        model.Value = (List <string>)valueResult;
                    }
                    else if (valueResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(valueResult))
                        {
                            model.Value     = new List <string>();
                            stringProcessed = true;
                        }
                        if (!stringProcessed && (((string)valueResult).StartsWith("{") || ((string)valueResult).StartsWith("[")))
                        {
                            try
                            {
                                model.Value     = JsonConvert.DeserializeObject <List <string> >(valueResult.ToString());
                                stringProcessed = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Value Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && !((string)valueResult).Contains("{") && !((string)valueResult).Contains("["))
                        {
                            var valueArray = ((string)valueResult).Split(',', StringSplitOptions.RemoveEmptyEntries);
                            model.Value     = new List <string>(valueArray);
                            stringProcessed = true;
                        }
                        if (!stringProcessed && ((string)valueResult).StartsWith("[") && ((string)valueResult).EndsWith("]"))
                        {
                            model.Value = JsonConvert.DeserializeObject <List <string> >((string)valueResult);
                        }
                    }
                    else if (valueResult is List <Guid> )
                    {
                        model.Value = ((List <Guid>)valueResult).Select(x => x.ToString()).ToList();
                    }
                    else if (valueResult is Guid)
                    {
                        model.Value = new List <string>(valueResult.ToString());
                    }
                    else if (valueResult is List <EntityRecord> )
                    {
                        if (((List <EntityRecord>)valueResult).Count > 0)
                        {
                            if (!((List <EntityRecord>)valueResult)[0].Properties.ContainsKey("id"))
                            {
                                throw new Exception("The provided list of entity records does not contain an 'id' property");
                            }
                        }
                        model.Value = ((List <EntityRecord>)valueResult).Select(x => ((Guid)x["id"]).ToString()).ToList();
                    }

                    var     dataSourceOptions = new List <SelectOption>();
                    dynamic optionsResult     = context.DataModel.GetPropertyValueByDataSource(options.Options);
                    if (optionsResult == null)
                    {
                    }
                    if (optionsResult is List <SelectOption> )
                    {
                        dataSourceOptions = (List <SelectOption>)optionsResult;
                    }
                    else if (optionsResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(optionsResult))
                        {
                            dataSourceOptions = new List <SelectOption>();
                            stringProcessed   = true;
                        }
                        //AJAX Options
                        if (!stringProcessed && ((string)optionsResult).StartsWith("{"))
                        {
                            try
                            {
                                options.AjaxDatasource = JsonConvert.DeserializeObject <SelectOptionsAjaxDatasource>(optionsResult, new JsonSerializerSettings()
                                {
                                    MissingMemberHandling = MissingMemberHandling.Error
                                });
                                stringProcessed = true;
                                ViewBag.Options = options;
                            }
                            catch
                            {
                            }
                        }
                        if (!stringProcessed && (((string)optionsResult).StartsWith("{") || ((string)optionsResult).StartsWith("[")))
                        {
                            try
                            {
                                dataSourceOptions = JsonConvert.DeserializeObject <List <SelectOption> >(optionsResult);
                                stringProcessed   = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Options Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && ((string)optionsResult).Contains(",") && !((string)optionsResult).Contains("{") && !((string)optionsResult).Contains("["))
                        {
                            var optionsArray = ((string)optionsResult).Split(',');
                            var optionsList  = new List <SelectOption>();
                            foreach (var optionString in optionsArray)
                            {
                                optionsList.Add(new SelectOption(optionString, optionString));
                            }
                            dataSourceOptions = optionsList;
                        }
                    }
                    if (dataSourceOptions.Count > 0)
                    {
                        model.Options = dataSourceOptions;
                    }
                    #endregion
                }

                ViewBag.SelectMatchOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <WvSelectMatchType>();

                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #18
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldSelectOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldSelectOptions>(context.Options.ToString());
                    ////Check for connection to entity field
                    //if (instanceOptions.TryConnectToEntity)
                    //{
                    //	var entity = context.DataModel.GetProperty("Entity");
                    //	if (entity != null && entity is Entity)
                    //	{
                    //		var fieldName = instanceOptions.Name;
                    //		var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    //		if (entityField != null && entityField is PhoneField)
                    //		{
                    //			var castedEntityField = ((PhoneField)entityField);
                    //			//No options connected
                    //		}
                    //	}
                    //}
                }
                var modelFieldLabel = "";
                var model           = (PcFieldSelectModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel, targetModel: "PcFieldSelectModel");
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }
                //PcFieldSelectModel model = PcFieldSelectModel.CopyFromBaseModel(baseModel);

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as FieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                #endregion


                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    #region << Init DataSources >>
                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);

                    dynamic optionsResult = context.DataModel.GetPropertyValueByDataSource(options.Options);

                    var dataSourceOptions = new List <SelectOption>();
                    if (optionsResult == null)
                    {
                    }
                    if (optionsResult is List <SelectOption> )
                    {
                        dataSourceOptions = (List <SelectOption>)optionsResult;
                    }
                    else if (optionsResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(optionsResult))
                        {
                            dataSourceOptions = new List <SelectOption>();
                            stringProcessed   = true;
                        }
                        //AJAX Options
                        if (!stringProcessed && ((string)optionsResult).StartsWith("{"))
                        {
                            try
                            {
                                options.AjaxDatasource = JsonConvert.DeserializeObject <SelectOptionsAjaxDatasource>(optionsResult, new JsonSerializerSettings()
                                {
                                    MissingMemberHandling = MissingMemberHandling.Error
                                });
                                stringProcessed = true;
                                ViewBag.Options = options;
                            }
                            catch {
                            }
                        }
                        if (!stringProcessed && (((string)optionsResult).StartsWith("{") || ((string)optionsResult).StartsWith("[")))
                        {
                            try
                            {
                                dataSourceOptions = JsonConvert.DeserializeObject <List <SelectOption> >(optionsResult);
                                stringProcessed   = true;
                            }
                            catch
                            {
                                stringProcessed = false;
                                return(await Task.FromResult <IViewComponentResult>(Content("Error: Options Json De-serialization failed!")));
                            }
                        }
                        if (!stringProcessed && ((string)optionsResult).Contains(",") && !((string)optionsResult).Contains("{") && !((string)optionsResult).Contains("["))
                        {
                            var optionsArray = ((string)optionsResult).Split(',');
                            var optionsList  = new List <SelectOption>();
                            foreach (var optionString in optionsArray)
                            {
                                optionsList.Add(new SelectOption(optionString, optionString));
                            }
                            dataSourceOptions = optionsList;
                        }
                    }

                    if (dataSourceOptions.Count > 0)
                    {
                        model.Options = dataSourceOptions;
                    }

                    #endregion
                }

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query parameter 'pid', when requesting this component")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldDataCsvOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldDataCsvOptions>(context.Options.ToString());
                }

                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }

                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == WvLabelRenderMode.Undefined && baseOptions.LabelMode != WvLabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == WvFieldRenderMode.Undefined && baseOptions.Mode != WvFieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as WvFieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?;
                if (requiredOverride != null)
                {
                    model.Required = requiredOverride.Value;
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(options.RequiredOverrideDs))
                    {
                        if (options.RequiredOverrideDs.ToLowerInvariant() == "true")
                        {
                            model.Required = true;
                        }
                        else if (options.RequiredOverrideDs.ToLowerInvariant() == "false")
                        {
                            model.Required = false;
                        }
                    }
                }
                #endregion

                ViewBag.Options            = options;
                ViewBag.Model              = model;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);

                    var delimiter = context.DataModel.GetPropertyValueByDataSource(options.DelimiterValueDs) as string;
                    var lang      = context.DataModel.GetPropertyValueByDataSource(options.LangDs) as string;
                    var hasHeader = context.DataModel.GetPropertyValueByDataSource(options.HasHeaderValueDs) as bool?;

                    ViewBag.Delimiter = ErpDataCsvDelimiterType.COMMA;
                    if (!String.IsNullOrWhiteSpace(delimiter) && delimiter == "tab")
                    {
                        ViewBag.Delimiter = ErpDataCsvDelimiterType.TAB;
                    }
                    ViewBag.Lang = "en";
                    if (!String.IsNullOrWhiteSpace(lang))
                    {
                        ViewBag.Lang = lang;
                    }
                    ViewBag.HasHeader = true;
                    if (hasHeader != null)
                    {
                        ViewBag.HasHeader = hasHeader;
                    }
                }



                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcTaskRepeatRecurrenceSetOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcTaskRepeatRecurrenceSetOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.CurrentUser      = SecurityContext.CurrentUser;
                ViewBag.CurrentUserJson  = JsonConvert.SerializeObject(SecurityContext.CurrentUser);

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var record = (EntityRecord)context.DataModel.GetProperty("Record");
                    if (record == null)
                    {
                        throw new ValidationException()
                              {
                                  Message = "Record not found"
                              }
                    }
                    ;

                    ViewBag.RecurrenceTemplateString = "";
                    if (record.Properties.ContainsKey("recurrence_template") && record["recurrence_template"] is string)
                    {
                        ViewBag.RecurrenceTemplateString = (string)record["recurrence_template"];
                    }
                    ViewBag.TemplateDefault = JsonConvert.SerializeObject(new RecurrenceTemplate());

                    ViewBag.RecurrenceTypeOptions    = JsonConvert.SerializeObject(ModelExtensions.GetEnumAsSelectOptions <RecurrenceType>());
                    ViewBag.RecurrenceEndTypeOptions = JsonConvert.SerializeObject(ModelExtensions.GetEnumAsSelectOptions <RecurrenceEndType>());
                    var periodTypes = ModelExtensions.GetEnumAsSelectOptions <RecurrencePeriodType>();
                    periodTypes = periodTypes.FindAll(x => x.Value != "0" && x.Value != "1" && x.Value != "2").ToList();                     // remove seconds minutes and hour
                    ViewBag.PeriodTypeOptions           = JsonConvert.SerializeObject(periodTypes);
                    ViewBag.RecurrenceChangeTypeOptions = JsonConvert.SerializeObject(ModelExtensions.GetEnumAsSelectOptions <RecurrenceChangeType>());
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #21
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var instanceOptions = new PcPageHeaderOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcPageHeaderOptions>(context.Options.ToString());
                }
                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = instanceOptions;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.InstanceOptions  = instanceOptions;
                ViewBag.ComponentContext = context;



                ViewBag.ProccessedTitle        = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Title);
                ViewBag.ProccessedSubTitle     = context.DataModel.GetPropertyValueByDataSource(instanceOptions.SubTitle);
                ViewBag.ProccessedAreaLabel    = context.DataModel.GetPropertyValueByDataSource(instanceOptions.AreaLabel);
                ViewBag.ProccessedAreaSubLabel = context.DataModel.GetPropertyValueByDataSource(instanceOptions.AreaSubLabel);
                ViewBag.ProccessedDescription  = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Description);
                ViewBag.ProccessedColor        = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Color);
                ViewBag.ProccessedIconColor    = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IconColor);
                ViewBag.ProccessedIconClass    = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IconClass);

                if (!String.IsNullOrWhiteSpace(instanceOptions.ReturnUrl))
                {
                    ViewBag.ProccessedReturnUrl = context.DataModel.GetPropertyValueByDataSource(instanceOptions.ReturnUrl);
                }

                else if (ErpRequestContext != null && ErpRequestContext.PageContext != null && ErpRequestContext.PageContext.HttpContext.Request.Query.ContainsKey("returnUrl") &&
                         !String.IsNullOrWhiteSpace(ErpRequestContext.PageContext.HttpContext.Request.Query["returnUrl"]))
                {
                    ViewBag.ProccessedReturnUrl = ErpRequestContext.PageContext.HttpContext.Request.Query["returnUrl"].ToString();
                }

                var switchItemPages    = new List <ErpPage>();
                var currentSitemapArea = ErpRequestContext.SitemapArea;
                var currentSitemapNode = ErpRequestContext.SitemapNode;
                var currentApp         = ErpRequestContext.App;
                if (instanceOptions.ShowPageSwitch && currentPage != null && currentPage.Type == PageType.Site)
                {
                    var allPages = new PageService().GetAll();
                    switchItemPages = allPages.FindAll(x => x.Type == currentPage.Type).ToList();
                }
                else if (instanceOptions.ShowPageSwitch && currentPage != null && currentPage.AppId != null && currentPage.Type == PageType.Application)
                {
                    var allPages = new PageService().GetAll();
                    switchItemPages = allPages.FindAll(x => x.Type == currentPage.Type && x.AppId == currentApp.Id && x.NodeId == currentPage.NodeId).ToList();
                }
                if (instanceOptions.ShowPageSwitch && currentPage != null && currentSitemapNode != null)
                {
                    var allPages      = new PageService().GetAll();
                    var sameTypePages = allPages.FindAll(x => x.Type == currentPage.Type).ToList();
                    foreach (var page in sameTypePages)
                    {
                        if (page.NodeId == context.Node.Id)
                        {
                            switchItemPages.Add(page);
                        }
                        else if (currentSitemapNode.Type == SitemapNodeType.EntityList && page.EntityId == currentSitemapNode.EntityId)
                        {
                            switchItemPages.Add(page);
                        }
                    }
                }

                switchItemPages = switchItemPages.OrderBy(x => x.Weight).ToList();

                var switchItems        = new List <PageSwitchItem>();
                var currentEntity      = ErpRequestContext.Entity;
                var parentEntity       = ErpRequestContext.ParentEntity;
                var currentUrlTemplate = "/";
                //Site pages
                if (currentPage.Type == PageType.Site)
                {
                    currentUrlTemplate = $"/s/[[pageName]]";
                }
                //App pages without nodes
                else if (currentApp != null && currentSitemapNode == null)
                {
                    currentUrlTemplate = $"/{currentApp.Name}/a/[[pageName]]";
                }
                //App pages with sitemap node
                else if (currentApp != null && currentSitemapArea != null && currentSitemapNode != null)
                {
                    //App pages
                    if (currentPage.Type == PageType.Application)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/a/[[pageName]]";
                    }
                    //Record create page, No relation
                    else if (currentPage.Type == PageType.RecordCreate && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/c/[[pageName]]";
                    }
                    //Record create page, With relation
                    else if (currentPage.Type == PageType.RecordCreate && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/c/[[pageName]]";
                    }
                    //Record manage page, No relation
                    else if (currentPage.Type == PageType.RecordManage && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/m/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record manage page, With relation
                    else if (currentPage.Type == PageType.RecordManage && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/m/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record details page, No relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record details page, With relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/r/{ErpRequestContext.RecordId}/[[pageName]]";
                    }
                    //Record list page, No relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/l/[[pageName]]";
                    }
                    //Record list page, With relation
                    else if (currentPage.Type == PageType.RecordDetails && parentEntity != null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/r/{ErpRequestContext.ParentRecordId}/rl/{ErpRequestContext.RelationId}/l/[[pageName]]";
                    }
                }

                foreach (var switchPage in switchItemPages)
                {
                    var isSelected = false;
                    if (currentPage != null && switchPage.Id == currentPage.Id)
                    {
                        isSelected = true;
                    }
                    switchItems.Add(new PageSwitchItem()
                    {
                        IsSelected = isSelected,
                        Label      = switchPage.Label,
                        Url        = currentUrlTemplate.Replace("[[pageName]]", switchPage.Name)
                    });
                }

                ViewBag.PageSwitchItems = switchItems;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #22
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query param 'pid', when requesting this component")));
                }

                var instanceOptions = new PcBtnToolbarOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcBtnToolbarOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options            = instanceOptions;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                ViewBag.CssSize = ModelExtensions.GetEnumAsSelectOptions <CssSize>();

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #23
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query param 'pid', when requesting this component")));
                }

                var instanceOptions = new PcButtonOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcButtonOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                ViewBag.Options        = instanceOptions;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    instanceOptions.Text      = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Text) as string;
                    instanceOptions.Class     = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Class) as string;
                    instanceOptions.IconClass = context.DataModel.GetPropertyValueByDataSource(instanceOptions.IconClass) as string;

                    ViewBag.ProcessedHref = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Href);
                }
                #region << Select options >>
                ViewBag.CssSize = ModelExtensions.GetEnumAsSelectOptions <CssSize>();

                ViewBag.ColorOptions = ModelExtensions.GetEnumAsSelectOptions <ErpColor>().OrderBy(x => x.Label).ToList();

                ViewBag.TypeOptions = ModelExtensions.GetEnumAsSelectOptions <ButtonType>();

                #endregion
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #24
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldHtmlOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldHtmlOptions>(context.Options.ToString());
                    if (context.Mode != ComponentMode.Options)
                    {
                        if (String.IsNullOrWhiteSpace(options.LabelHelpText))
                        {
                            options.LabelHelpText = baseOptions.LabelHelpText;
                        }

                        if (String.IsNullOrWhiteSpace(options.Description))
                        {
                            options.Description = baseOptions.Description;
                        }
                    }
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText) && context.Mode != ComponentMode.Options)
                {
                    options.LabelText = modelFieldLabel;
                }

                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == WvLabelRenderMode.Undefined && baseOptions.LabelMode != WvLabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == WvFieldRenderMode.Undefined && baseOptions.Mode != WvFieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                var accessOverride = context.DataModel.GetPropertyValueByDataSource(options.AccessOverrideDs) as WvFieldAccess?;
                if (accessOverride != null)
                {
                    model.Access = accessOverride.Value;
                }
                var requiredOverride = context.DataModel.GetPropertyValueByDataSource(options.RequiredOverrideDs) as bool?;
                if (requiredOverride != null)
                {
                    model.Required = requiredOverride.Value;
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(options.RequiredOverrideDs))
                    {
                        if (options.RequiredOverrideDs.ToLowerInvariant() == "true")
                        {
                            model.Required = true;
                        }
                        else if (options.RequiredOverrideDs.ToLowerInvariant() == "false")
                        {
                            model.Required = false;
                        }
                    }
                }
                #endregion


                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);

                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;
                }

                ViewBag.UploadModeOptions  = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <HtmlUploadMode>();
                ViewBag.ToolbarModeOptions = WebVella.TagHelpers.Utilities.ModelExtensions.GetEnumAsSelectOptions <HtmlToolbarMode>();

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions     = InitPcFieldBaseOptions(context);
                var instanceOptions = PcFieldDateTimeOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcFieldDateTimeOptions>(context.Options.ToString());
                    ////Check for connection to entity field
                    //if (instanceOptions.TryConnectToEntity)
                    //{
                    //	var entity = context.DataModel.GetProperty("Entity");
                    //	if (entity != null && entity is Entity)
                    //	{
                    //		var fieldName = instanceOptions.Name;
                    //		var entityField = ((Entity)entity).Fields.FirstOrDefault(x => x.Name == fieldName);
                    //		if (entityField != null && entityField is DateTimeField)
                    //		{
                    //			var castedEntityField = ((DateTimeField)entityField);
                    //			//No options mapped
                    //		}
                    //	}
                    //}
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, instanceOptions, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(instanceOptions.LabelText))
                {
                    instanceOptions.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = instanceOptions.LabelMode;
                ViewBag.Mode      = instanceOptions.Mode;

                if (instanceOptions.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (instanceOptions.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    model.Value = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Value);
                }

                ViewBag.Options        = instanceOptions;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.ExceptionMessage = "Unknown component mode";
                    ViewBag.Errors           = new List <ValidationError>();
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.ExceptionMessage = ex.Message;
                ViewBag.Errors           = new List <ValidationError>();
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #26
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetTasksQueueOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksQueueOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;
                ViewBag.TypeOptions      = ModelExtensions.GetEnumAsSelectOptions <TasksDueType>();

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid?projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid?;

                    Guid?userId    = context.DataModel.GetPropertyValueByDataSource(options.UserId) as Guid?;
                    var  limit     = options.Type == TasksDueType.EndTimeNotDue ? 10 : 50;
                    var  taskQueue = new TaskService().GetTaskQueue(projectId, userId, options.Type, limit);

                    var users = new UserService().GetAll();

                    var resultRecords = new List <EntityRecord>();

                    foreach (var task in taskQueue)
                    {
                        var imagePath = "/webvella-erp-web/assets/avatar.png";
                        var user      = new EntityRecord();
                        user["username"] = "******";
                        if (task["owner_id"] != null)
                        {
                            user = users.First(x => (Guid)x["id"] == (Guid)task["owner_id"]);
                            if (user["image"] != null && (string)user["image"] != "")
                            {
                                imagePath = "/fs" + (string)user["image"];
                            }
                        }
                        string iconClass = "";
                        string color     = "";
                        new TaskService().GetTaskIconAndColor((string)task["priority"], out iconClass, out color);

                        var row = new EntityRecord();
                        row["task"] = $"<i class='{iconClass}' style='color:{color}'></i> <a href=\"/projects/tasks/tasks/r/{(Guid)task["id"]}/details\">[{task["key"]}] {task["subject"]}</a>";
                        row["user"] = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                        row["date"] = ((DateTime?)task["end_time"]).ConvertToAppDate();
                        resultRecords.Add(row);
                    }
                    ViewBag.Records = resultRecords;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);
                var options     = PcFieldAutonumberOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldAutonumberOptions>(context.Options.ToString());

                    if (context.Mode != ComponentMode.Options)
                    {
                        if (String.IsNullOrWhiteSpace(options.Template))
                        {
                            options.Template = baseOptions.Template;
                        }
                    }
                }
                var modelFieldLabel = "";
                var model           = (PcFieldBaseModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel);
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    model.Value = context.DataModel.GetPropertyValueByDataSource(options.Value);
                }

                var isVisible   = true;
                var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                {
                    if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                    {
                        isVisible = outBool;
                    }
                }
                else if (isVisibleDS is Boolean)
                {
                    isVisible = (bool)isVisibleDS;
                }
                ViewBag.IsVisible = isVisible;

                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Beispiel #28
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcGridOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcGridOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;


                ViewBag.CssBreakpointOptions = ModelExtensions.GetEnumAsSelectOptions <CssBreakpoint>();
                ViewBag.Page       = 1;
                ViewBag.TotalCount = 0;

                if (options.PageSize != null)
                {
                    ViewBag.PageSize = options.PageSize;
                }
                else
                {
                    ViewBag.PageSize = 0;
                }


                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    ViewBag.Records = context.DataModel.GetPropertyValueByDataSource(options.Records) as EntityRecordList ?? new EntityRecordList();

                    if (ViewBag.Records is EntityRecordList)
                    {
                        ViewBag.TotalCount = ((EntityRecordList)ViewBag.Records).TotalCount;
                    }
                    string pageKey = options.Prefix + options.QueryStringPage;
                    if (HttpContext.Request.Query.ContainsKey(pageKey))
                    {
                        var queryValue = HttpContext.Request.Query[pageKey].ToString();
                        if (Int16.TryParse(queryValue, out Int16 outInt))
                        {
                            ViewBag.Page = outInt;
                        }
                    }

                    string pagesizeKey = options.Prefix + options.QueryStringPageSize;
                    if (HttpContext.Request.Query.ContainsKey(pagesizeKey))
                    {
                        var queryValue = HttpContext.Request.Query[pagesizeKey].ToString();
                        if (Int16.TryParse(queryValue, out Int16 outInt))
                        {
                            ViewBag.PageSize = outInt;
                        }
                    }
                }
                else
                {
                    ViewBag.VerticalAlignmentOptions   = ModelExtensions.GetEnumAsSelectOptions <VerticalAlignmentType>();
                    ViewBag.HorizontalAlignmentOptions = ModelExtensions.GetEnumAsSelectOptions <HorizontalAlignmentType>();
                }
                var columns = new List <GridColumn>();

                #region << Init Columns >>
                if (options.VisibleColumns > 0)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container1Id,
                        Name        = options.Container1Name,
                        Label       = options.Container1Label,
                        Searchable  = options.Container1Searchable,
                        Sortable    = options.Container1Sortable,
                        Width       = options.Container1Width
                    });
                }
                if (options.VisibleColumns > 1)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container2Id,
                        Name        = options.Container2Name,
                        Label       = options.Container2Label,
                        Searchable  = options.Container2Searchable,
                        Sortable    = options.Container2Sortable,
                        Width       = options.Container2Width
                    });
                }
                if (options.VisibleColumns > 2)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container3Id,
                        Name        = options.Container3Name,
                        Label       = options.Container3Label,
                        Searchable  = options.Container3Searchable,
                        Sortable    = options.Container3Sortable,
                        Width       = options.Container3Width
                    });
                }
                if (options.VisibleColumns > 3)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container4Id,
                        Name        = options.Container4Name,
                        Label       = options.Container4Label,
                        Searchable  = options.Container4Searchable,
                        Sortable    = options.Container4Sortable,
                        Width       = options.Container4Width
                    });
                }
                if (options.VisibleColumns > 4)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container5Id,
                        Name        = options.Container5Name,
                        Label       = options.Container5Label,
                        Searchable  = options.Container5Searchable,
                        Sortable    = options.Container5Sortable,
                        Width       = options.Container5Width
                    });
                }
                if (options.VisibleColumns > 5)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container6Id,
                        Name        = options.Container6Name,
                        Label       = options.Container6Label,
                        Searchable  = options.Container6Searchable,
                        Sortable    = options.Container6Sortable,
                        Width       = options.Container6Width
                    });
                }
                if (options.VisibleColumns > 6)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container7Id,
                        Name        = options.Container7Name,
                        Label       = options.Container7Label,
                        Searchable  = options.Container7Searchable,
                        Sortable    = options.Container7Sortable,
                        Width       = options.Container7Width
                    });
                }
                if (options.VisibleColumns > 7)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container8Id,
                        Name        = options.Container8Name,
                        Label       = options.Container8Label,
                        Searchable  = options.Container8Searchable,
                        Sortable    = options.Container8Sortable,
                        Width       = options.Container8Width
                    });
                }
                if (options.VisibleColumns > 8)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container9Id,
                        Name        = options.Container9Name,
                        Label       = options.Container9Label,
                        Searchable  = options.Container9Searchable,
                        Sortable    = options.Container9Sortable,
                        Width       = options.Container9Width
                    });
                }
                if (options.VisibleColumns > 9)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container10Id,
                        Name        = options.Container10Name,
                        Label       = options.Container10Label,
                        Searchable  = options.Container10Searchable,
                        Sortable    = options.Container10Sortable,
                        Width       = options.Container10Width
                    });
                }
                if (options.VisibleColumns > 10)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container11Id,
                        Name        = options.Container11Name,
                        Label       = options.Container11Label,
                        Searchable  = options.Container11Searchable,
                        Sortable    = options.Container11Sortable,
                        Width       = options.Container11Width
                    });
                }
                if (options.VisibleColumns > 11)
                {
                    columns.Add(new GridColumn()
                    {
                        ContainerId = options.Container12Id,
                        Name        = options.Container12Name,
                        Label       = options.Container12Label,
                        Searchable  = options.Container12Searchable,
                        Sortable    = options.Container12Sortable,
                        Width       = options.Container12Width
                    });
                }
                #endregion

                ViewBag.Columns = columns;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (EqlException ex)
            {
                var errors = new List <ValidationError>();
                foreach (var error in ex.Errors)
                {
                    errors.Add(new ValidationError("eql", $"Line {error.Line}, Column {error.Column}: {error.Message}"));
                }
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message,
                    Errors  = errors
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var baseOptions = InitPcFieldBaseOptions(context);

                var options = PcFieldCheckboxListOptions.CopyFromBaseOptions(baseOptions);

                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldCheckboxListOptions>(context.Options.ToString());
                }
                var modelFieldLabel = "";
                var model           = (PcFieldCheckboxListModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel, targetModel: "PcFieldCheckboxListModel");
                if (String.IsNullOrWhiteSpace(options.LabelText))
                {
                    options.LabelText = modelFieldLabel;
                }
                //PcFieldCheckboxListModel model = PcFieldCheckboxListModel.CopyFromBaseModel(baseModel);

                //Implementing Inherit label mode
                ViewBag.LabelMode = options.LabelMode;
                ViewBag.Mode      = options.Mode;

                if (options.LabelMode == LabelRenderMode.Undefined && baseOptions.LabelMode != LabelRenderMode.Undefined)
                {
                    ViewBag.LabelMode = baseOptions.LabelMode;
                }

                if (options.Mode == FieldRenderMode.Undefined && baseOptions.Mode != FieldRenderMode.Undefined)
                {
                    ViewBag.Mode = baseOptions.Mode;
                }


                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options        = options;
                ViewBag.Model          = model;
                ViewBag.Node           = context.Node;
                ViewBag.ComponentMeta  = componentMeta;
                ViewBag.RequestContext = ErpRequestContext;
                ViewBag.AppContext     = ErpAppContext.Current;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;


                    #region << Init DataSources >>
                    dynamic valueResult = context.DataModel.GetPropertyValueByDataSource(options.Value);
                    if (valueResult == null)
                    {
                        model.Value = new List <string>();
                    }
                    else if (valueResult is List <string> )
                    {
                        model.Value = (List <string>)valueResult;
                    }
                    else if (valueResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(valueResult))
                        {
                            model.Value     = new List <string>();
                            stringProcessed = true;
                        }
                        if (!stringProcessed && (((string)valueResult).StartsWith("{") || ((string)valueResult).StartsWith("[")))
                        {
                            try
                            {
                                model.Value     = JsonConvert.DeserializeObject <List <string> >(valueResult.ToString());
                                stringProcessed = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Value Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && ((string)valueResult).Contains(",") && !((string)valueResult).Contains("{") && !((string)valueResult).Contains("["))
                        {
                            var valueArray = ((string)valueResult).Split(',');
                            model.Value = new List <string>(valueArray);
                        }
                    }

                    var     dataSourceOptions = new List <SelectOption>();
                    dynamic optionsResult     = context.DataModel.GetPropertyValueByDataSource(options.Options);
                    if (optionsResult == null)
                    {
                    }
                    if (optionsResult is List <SelectOption> )
                    {
                        dataSourceOptions = (List <SelectOption>)optionsResult;
                    }
                    else if (optionsResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(optionsResult))
                        {
                            dataSourceOptions = new List <SelectOption>();
                            stringProcessed   = true;
                        }
                        if (!stringProcessed && (((string)optionsResult).StartsWith("{") || ((string)optionsResult).StartsWith("[")))
                        {
                            try
                            {
                                dataSourceOptions = JsonConvert.DeserializeObject <List <SelectOption> >(optionsResult);
                                stringProcessed   = true;
                            }
                            catch
                            {
                                stringProcessed          = false;
                                ViewBag.ExceptionMessage = "Options Json Deserialization failed!";
                                ViewBag.Errors           = new List <ValidationError>();
                                return(await Task.FromResult <IViewComponentResult>(View("Error")));
                            }
                        }
                        if (!stringProcessed && ((string)optionsResult).Contains(",") && !((string)optionsResult).Contains("{") && !((string)optionsResult).Contains("["))
                        {
                            var optionsArray = ((string)optionsResult).Split(',');
                            var optionsList  = new List <SelectOption>();
                            foreach (var optionString in optionsArray)
                            {
                                optionsList.Add(new SelectOption(optionString, optionString));
                            }
                            dataSourceOptions = optionsList;
                        }
                    }
                    if (dataSourceOptions.Count > 0)
                    {
                        model.Options = dataSourceOptions;
                    }
                    #endregion
                }


                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query parameter 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel cannot be null")));
                }
                else if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                var options = new PcProjectWidgetBudgetChartOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetBudgetChartOptions>(context.Options.ToString());
                }

                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);
                #endregion


                ViewBag.Options          = options;
                ViewBag.Node             = context.Node;
                ViewBag.ComponentMeta    = componentMeta;
                ViewBag.RequestContext   = ErpRequestContext;
                ViewBag.AppContext       = ErpAppContext.Current;
                ViewBag.ComponentContext = context;

                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    Guid projectId = context.DataModel.GetPropertyValueByDataSource(options.ProjectId) as Guid? ?? Guid.Empty;

                    if (projectId == Guid.Empty)
                    {
                        return(await Task.FromResult <IViewComponentResult>(Content("Error: ProjectId is required")));
                    }

                    var projectSrv      = new ProjectService();
                    var projectRecord   = projectSrv.Get(projectId);
                    var projectTasks    = new TaskService().GetTaskQueue(projectId, null, TasksDueType.All);
                    var projectTimelogs = projectSrv.GetProjectTimelogs(projectId);

                    decimal loggedBillableMinutes    = 0;
                    decimal loggedNonBillableMinutes = 0;
                    decimal projectEstimatedMinutes  = 0;

                    foreach (var timelog in projectTimelogs)
                    {
                        if ((bool)timelog["is_billable"])
                        {
                            loggedBillableMinutes += (decimal)timelog["minutes"];
                        }
                        else
                        {
                            loggedNonBillableMinutes += (decimal)timelog["minutes"];
                        }
                    }

                    foreach (var task in projectTasks)
                    {
                        projectEstimatedMinutes += (decimal)task["estimated_minutes"];
                    }

                    var billedHours    = Math.Round(loggedBillableMinutes / 60, 2);
                    var nonBilledhours = Math.Round(loggedNonBillableMinutes / 60, 2);
                    var estimatedHours = Math.Round(projectEstimatedMinutes / 60, 2);

                    var     budgetLeft   = (decimal)0;
                    decimal budgetAmount = projectRecord["budget_amount"] != null ? (decimal)projectRecord["budget_amount"] : 0;
                    decimal hourRate     = projectRecord["hour_rate"] != null ? (decimal)projectRecord["hour_rate"] : 0;

                    if ((string)projectRecord["budget_type"] == "on duration")
                    {
                        budgetLeft = budgetAmount - billedHours;
                    }
                    else
                    {
                        if (hourRate > 0 && budgetAmount > 0)
                        {
                            budgetLeft = (budgetAmount / hourRate) - billedHours;
                        }
                        else
                        {
                            budgetLeft = 0;
                        }
                    }

                    var budgetResult = new EntityRecord();
                    budgetResult["billed_hours"]    = billedHours;
                    budgetResult["nonbilled_hours"] = nonBilledhours;
                    budgetResult["estimated_hours"] = estimatedHours;
                    budgetResult["budget_type"]     = (string)projectRecord["budget_type"];
                    budgetResult["budget_left"]     = budgetLeft;
                    ViewBag.BudgetResult            = budgetResult;

                    var totalLogged         = billedHours + nonBilledhours;
                    var billedPercentage    = 0;
                    var nonBilledPercantage = 0;
                    if (totalLogged > 0)
                    {
                        billedPercentage    = (int)Math.Round(billedHours * 100 / totalLogged, 0);
                        nonBilledPercantage = 100 - billedPercentage;
                    }
                    var theme         = new Theme();
                    var chartDatasets = new List <WvChartDataset>()
                    {
                        new WvChartDataset()
                        {
                            Data = new List <decimal>()
                            {
                                billedPercentage, nonBilledPercantage
                            },
                            BackgroundColor = new List <string> {
                                theme.GreenColor, theme.LightBlueColor
                            },
                            BorderColor = new List <string> {
                                theme.GreenColor, theme.LightBlueColor
                            }
                        }
                    };

                    ViewBag.Datasets = chartDatasets;
                }
                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }