Ejemplo n.º 1
0
        public IActionResult OnPost()
        {
            PageInit();
            if (ErpPage == null)
            {
                return(NotFound());
            }

            if (!PageContext.HttpContext.Request.Query.ContainsKey("op"))
            {
                return(NotFound());
            }

            var operation = PageContext.HttpContext.Request.Query["op"];
            var pageServ  = new PageService();

            try
            {
                ErpPage pageCopy = null;

                if (operation == "delete")
                {
                    pageServ.DeletePage(ErpPage.Id);
                }
                else if (operation == "clone")
                {
                    pageCopy = pageServ.ClonePage(ErpPage.Id);
                }
                else
                {
                    return(NotFound());
                }

                if (!String.IsNullOrWhiteSpace(ReturnUrl))
                {
                    if (operation == "clone")
                    {
                        return(Redirect($"/sdk/objects/page/r/{pageCopy.Id}"));
                    }
                    else
                    {
                        return(Redirect(ReturnUrl));
                    }
                }
                else
                {
                    if (operation == "clone")
                    {
                        return(Redirect($"/sdk/objects/page/r/{pageCopy.Id}"));
                    }
                    else
                    {
                        return(Redirect($"/sdk/objects/page/l/list"));
                    }
                }
            }
            catch (ValidationException ex)
            {
                Validation.Message = ex.Message;
                Validation.Errors  = ex.Errors;
            }

            BeforeRender();
            return(Page());
        }
Ejemplo n.º 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 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 = PcFieldMultiSelectOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcFieldMultiSelectOptions>(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 MultiSelectField)
                    //		{
                    //			var castedEntityField = ((MultiSelectField)entityField);
                    //			//No options connected
                    //		}
                    //	}
                    //}
                }
                var modelFieldLabel = "";
                var model           = (PcFieldMultiSelectModel)InitPcFieldBaseModel(context, instanceOptions, label: out modelFieldLabel, targetModel: "PcFieldMultiSelectModel");
                if (String.IsNullOrWhiteSpace(instanceOptions.LabelText))
                {
                    instanceOptions.LabelText = modelFieldLabel;
                }
                //PcFieldMultiSelectModel model = PcFieldMultiSelectModel.CopyFromBaseModel(baseModel);

                //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


                #region << Init DataSources >>
                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    dynamic valueResult = context.DataModel.GetPropertyValueByDataSource(instanceOptions.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);
                        }
                    }
                    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());
                    }


                    var     dataSourceOptions = new List <SelectOption>();
                    dynamic optionsResult     = context.DataModel.GetPropertyValueByDataSource(instanceOptions.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 (!instanceOptions.TryConnectToEntity || dataSourceOptions.Count > 0)
                    {
                        model.Options = dataSourceOptions;
                    }
                }

                #endregion


                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")));
            }
        }
Ejemplo n.º 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 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")));
            }
        }
Ejemplo n.º 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 == 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     = PcFieldTextareaOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcFieldTextareaOptions>(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 == 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;

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

                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")));
            }
        }
Ejemplo n.º 5
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());
                    if (context.Mode != ComponentMode.Options)
                    {
                        if (String.IsNullOrWhiteSpace(options.LabelHelpText))
                        {
                            options.LabelHelpText = baseOptions.LabelHelpText;
                        }

                        if (String.IsNullOrWhiteSpace(options.Description))
                        {
                            options.Description = baseOptions.Description;
                        }
                    }
                    ////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
                    //		}
                    //	}
                    //}

                    /*
                     * If link is present, evaluate the datasource and find the final link and assign to href
                     * Feature: Linkable Text Field
                     * Author: Amarjeet-L
                     */
                    string link = options.Link;
                    if (link != "")
                    {
                        link         = context.DataModel.GetPropertyValueByDataSource(options.Link).ToString();
                        options.Href = link;
                    }
                }

                var modelFieldLabel = "";
                var model           = (PcFieldSelectModel)InitPcFieldBaseModel(context, options, label: out modelFieldLabel, targetModel: "PcFieldSelectModel");
                if (String.IsNullOrWhiteSpace(options.LabelText) && context.Mode != ComponentMode.Options)
                {
                    options.LabelText = modelFieldLabel;
                }
                //PcFieldSelectModel model = PcFieldSelectModel.CopyFromBaseModel(baseModel);

                //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


                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;
                    }
                    if (optionsResult is List <WvSelectOption> )
                    {
                        foreach (var option in (List <WvSelectOption>)optionsResult)
                        {
                            dataSourceOptions.Add(new SelectOption {
                                Color     = option.Color,
                                IconClass = option.IconClass,
                                Label     = option.Label,
                                Value     = option.Value
                            });
                        }
                    }
                    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
                }

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

                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")));
            }
        }
Ejemplo n.º 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 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 PcModalOptions();
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcModalOptions>(context.Options.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;

                if (context.Mode == ComponentMode.Display)
                {
                }

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    ViewBag.ProcessedTitle = context.DataModel.GetPropertyValueByDataSource(instanceOptions.Title);
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

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

                case ComponentMode.Options:
                    ViewBag.PositionOptions = ModelExtensions.GetEnumAsSelectOptions <ModalPosition>();
                    ViewBag.SizeOptions     = ModelExtensions.GetEnumAsSelectOptions <ModalSize>();
                    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")));
            }
        }
Ejemplo n.º 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 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 PcProjectWidgetTaskDistributionOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTaskDistributionOptions>(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);
                    int openTasks     = 0;
                    int closedTasks   = 0;

                    var taskStatuses        = new TaskService().GetTaskStatuses();
                    var closedStatusHashset = new HashSet <Guid>();
                    foreach (var taskStatus in taskStatuses)
                    {
                        if ((bool)taskStatus["is_closed"])
                        {
                            closedStatusHashset.Add((Guid)taskStatus["id"]);
                        }
                    }

                    var users    = new UserService().GetAll();
                    var userDict = new Dictionary <Guid, EntityRecord>();

                    foreach (var task in projectTasks)
                    {
                        var ownerId    = (Guid)task["owner_id"];
                        var taskStatus = (Guid)task["status_id"];
                        var targetDate = (DateTime?)task["target_date"];

                        if (!userDict.ContainsKey(ownerId))
                        {
                            var userRecord = new EntityRecord();
                            userRecord["overdue"] = (int)0;
                            userRecord["today"]   = (int)0;
                            userRecord["open"]    = (int)0;
                            userRecord["all"]     = (int)0;
                            userDict[ownerId]     = userRecord;
                        }

                        var currentRecord = userDict[ownerId];
                        currentRecord["all"] = ((int)currentRecord["all"]) + 1;
                        if (!closedStatusHashset.Contains(taskStatus))
                        {
                            currentRecord["open"] = ((int)currentRecord["open"]) + 1;
                        }

                        if (targetDate != null)
                        {
                            var erpTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ErpSettings.TimeZoneName);
                            targetDate = TimeZoneInfo.ConvertTimeFromUtc(targetDate.Value, erpTimeZone);
                            if (targetDate.Value.Date < DateTime.Now.Date)
                            {
                                currentRecord["overdue"] = ((int)currentRecord["overdue"]) + 1;
                            }
                            else if (targetDate.Value.Date == DateTime.Now.Date)
                            {
                                currentRecord["today"] = ((int)currentRecord["today"]) + 1;
                            }
                        }
                        userDict[ownerId] = currentRecord;
                    }

                    var records = new List <EntityRecord>();
                    foreach (var key in userDict.Keys)
                    {
                        var user       = users.First(x => (Guid)x["id"] == key);
                        var statRecord = userDict[key];
                        var row        = new EntityRecord();
                        var imagePath  = "/assets/avatar.png";
                        if (user["image"] != null && (string)user["image"] != "")
                        {
                            imagePath = "/fs" + (string)user["image"];
                        }

                        row["user"]    = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                        row["overdue"] = statRecord["overdue"];
                        row["today"]   = statRecord["today"];
                        row["open"]    = statRecord["open"];
                        row["all"]     = statRecord["all"];
                        records.Add(row);
                    }
                    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.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")));
            }
        }
Ejemplo n.º 8
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.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")));
            }
        }
Ejemplo n.º 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 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);
                ViewBag.StartDate        = null;
                ViewBag.EndDate          = null;

                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"
                              }
                    }
                    ;

                    if (record.Properties.ContainsKey("start_time") && record["start_time"] is DateTime?)
                    {
                        ViewBag.StartDate = record["start_time"];
                    }
                    if (record.Properties.ContainsKey("end_time") && record["end_time"] is DateTime?)
                    {
                        ViewBag.EndDate = record["end_time"];
                    }

                    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")));
            }
        }
Ejemplo n.º 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 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 PcProjectWidgetTasksChartOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksChartOptions>(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);

                    var overdueTasks  = (int)0;
                    var dueTodayTasks = (int)0;
                    var notDueTasks   = (int)0;

                    foreach (var task in projectTasks)
                    {
                        var endTime = ((DateTime?)task["end_time"]).ConvertToAppDate();

                        if (endTime != null && endTime.Value.AddDays(1) < DateTime.Now)
                        {
                            overdueTasks++;
                        }
                        else if (endTime != null && endTime.Value >= DateTime.Now.Date && endTime.Value < DateTime.Now.Date.AddDays(1))
                        {
                            dueTodayTasks++;
                        }
                        else
                        {
                            notDueTasks++;
                        }
                    }


                    var theme         = new Theme();
                    var chartDatasets = new List <WvChartDataset>()
                    {
                        new WvChartDataset()
                        {
                            Data = new List <decimal>()
                            {
                                overdueTasks, dueTodayTasks, notDueTasks
                            },
                            BackgroundColor = new List <string> {
                                theme.RedColor, theme.OrangeColor, theme.GreenColor
                            },
                            BorderColor = new List <string> {
                                theme.RedColor, theme.OrangeColor, theme.GreenColor
                            }
                        }
                    };

                    ViewBag.Datasets      = chartDatasets;
                    ViewBag.OverdueTasks  = overdueTasks;
                    ViewBag.DueTodayTasks = dueTodayTasks;
                    ViewBag.NotDueTasks   = notDueTasks;
                }
                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")));
            }
        }
Ejemplo n.º 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 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 options = new PcButtonOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcButtonOptions>(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;

                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;

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

                    ViewBag.ProcessedHref = context.DataModel.GetPropertyValueByDataSource(options.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")));
            }
        }
Ejemplo n.º 12
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 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;

                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("")));
                    }
                }

                if (options.QueryOptions == null)
                {
                    options.QueryOptions = new List <FilterType>();
                }

                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.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")));
            }
        }
Ejemplo n.º 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 PcProjectWidgetTasksOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTasksOptions>(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().GetTasks(projectId, userId);
                    int openTasks    = 0;
                    int closedTasks  = 0;

                    var taskStatuses        = new TaskService().GetTaskStatuses();
                    var closedStatusHashset = new HashSet <Guid>();
                    foreach (var taskStatus in taskStatuses)
                    {
                        if ((bool)taskStatus["is_closed"])
                        {
                            closedStatusHashset.Add((Guid)taskStatus["id"]);
                        }
                    }
                    var overdueTasks  = (int)0;
                    var dueTodayTasks = (int)0;

                    foreach (var task in projectTasks)
                    {
                        var taskStatus = (Guid)task["status_id"];
                        var targetDate = (DateTime?)task["target_date"];
                        if (closedStatusHashset.Contains(taskStatus))
                        {
                            closedTasks++;
                        }
                        else
                        {
                            openTasks++;
                        }

                        if (targetDate != null)
                        {
                            var erpTimeZone = TimeZoneInfo.FindSystemTimeZoneById(ErpSettings.TimeZoneName);
                            targetDate = TimeZoneInfo.ConvertTimeFromUtc(targetDate.Value, erpTimeZone);
                            if (targetDate.Value.Date < DateTime.Now.Date)
                            {
                                overdueTasks++;
                            }
                            else if (targetDate.Value.Date == DateTime.Now.Date)
                            {
                                dueTodayTasks++;
                            }
                        }
                    }


                    var theme         = new Theme();
                    var chartDatasets = new List <ErpChartDataset>()
                    {
                        new ErpChartDataset()
                        {
                            Data = new List <decimal>()
                            {
                                openTasks, closedTasks
                            },
                            BackgroundColor = new List <string> {
                                theme.PurpleColor, theme.TealColor
                            },
                            BorderColor = new List <string> {
                                theme.PurpleColor, theme.TealColor
                            }
                        }
                    };

                    ViewBag.OpenTasks     = openTasks;
                    ViewBag.ClosedTasks   = closedTasks;
                    ViewBag.Datasets      = chartDatasets;
                    ViewBag.OverdueTasks  = overdueTasks;
                    ViewBag.DueTodayTasks = dueTodayTasks;
                }
                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")));
            }
        }
Ejemplo n.º 14
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 PcValidationOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcValidationOptions>(context.Options.ToString());
                }

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

                ViewBag.Validation = context.DataModel.GetPropertyValueByDataSource(options.Validation) as ValidationException;

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

                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")));
            }
        }
Ejemplo n.º 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 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.Weight > 0 && 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.Weight > 0 && 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.Weight > 0 && 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.RecordList && parentEntity == null)
                    {
                        currentUrlTemplate = $"/{currentApp.Name}/{currentSitemapArea.Name}/{currentSitemapNode.Name}/l/[[pageName]]";
                    }
                    //Record list page, With relation
                    else if (currentPage.Type == PageType.RecordList && 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.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")));
            }
        }
Ejemplo n.º 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 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;

                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;

                    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;
                    ViewBag.ShowLegend = options.ShowLegend;
                    ViewBag.Height     = options.Height;
                    ViewBag.Width      = options.Width;
                    ViewBag.Type       = (ErpChartType)options.Type;
                }

                var chartTypeOptions = ModelExtensions.GetEnumAsSelectOptions <ErpChartType>();
                chartTypeOptions.First(x => x.Value == "4").Label = "area";
                ViewBag.ChartTypeOptions = chartTypeOptions;

                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")));
            }
        }
Ejemplo n.º 17
0
        public async Task <IViewComponentResult> InvokeAsync(Guid?pageId         = null, WvFieldRenderMode mode = WvFieldRenderMode.Form,
                                                             PageType?presetType = null, Guid?presetAppId       = null, Guid?presetEntityId = null)
        {
            //var typeOptions = new List<SelectFieldOption>();
            //var entityOptions = new List<SelectFieldOption>();
            //var applicationOptions = new List<SelectFieldOption>();
            //var areaOptions = new List<SelectFieldOption>();
            //var nodeOptions = new List<SelectFieldOption>();
            var pageSelectionTree = new PageSelectionTree();
            var erpPage           = new ErpPage();

            if (pageId == null)
            {
                if (presetType != null)
                {
                    erpPage.Type = presetType ?? PageType.Site;
                }
                if (presetAppId != null)
                {
                    erpPage.AppId = presetAppId.Value;
                }
                if (presetEntityId != null)
                {
                    erpPage.EntityId = presetEntityId.Value;
                    erpPage.Type     = PageType.RecordList;
                }
            }
            var pageSrv              = new PageService();
            var typeOptionsFieldId   = Guid.NewGuid();
            var appOptionsFieldId    = Guid.NewGuid();
            var areaOptionsFieldId   = Guid.NewGuid();
            var nodeOptionsFieldId   = Guid.NewGuid();
            var entityOptionsFieldId = Guid.NewGuid();

            #region << Init >>
            var apps     = new AppService().GetAllApplications();
            var entities = new EntityManager().ReadEntities().Object;

            #region << ErpPage && Init it>>
            if (pageId != null)
            {
                erpPage = pageSrv.GetPage(pageId ?? Guid.Empty);
                if (erpPage == null)
                {
                    ViewBag.ErrorMessage = "Error: the set pageId is not found as ErpPage!";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }

                if (erpPage.Type == PageType.Application && erpPage.AppId == null)
                {
                    ViewBag.ErrorMessage = "Error: Application should have AppId!";
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            #endregion

            #region << Type options >>
            {
                pageSelectionTree.AllTypes = ModelExtensions.GetEnumAsSelectOptions <PageType>().OrderBy(x => x.Label).ToList();
            }
            #endregion

            #region << App options >>
            {
                foreach (var app in apps)
                {
                    pageSelectionTree.AllApps.Add(new SelectOption()
                    {
                        Value = app.Id.ToString(),
                        Label = app.Name
                    });
                    //Set App tree
                    var appSelectionTree = new AppSelectionTree();
                    appSelectionTree.AppId = app.Id;
                    foreach (var area in app.Sitemap.Areas)
                    {
                        appSelectionTree.AllAreas.Add(new SelectOption()
                        {
                            Value = area.Id.ToString(),
                            Label = area.Name
                        });
                        var areaSelectionTree = new AreaSelectionTree()
                        {
                            AreaId = area.Id
                        };
                        foreach (var node in area.Nodes)
                        {
                            areaSelectionTree.AllNodes.Add(new SelectOption()
                            {
                                Value = node.Id.ToString(),
                                Label = node.Name
                            });
                        }
                        areaSelectionTree.AllNodes = areaSelectionTree.AllNodes.OrderBy(x => x.Label).ToList();
                        appSelectionTree.AreaSelectionTree.Add(areaSelectionTree);
                    }
                    pageSelectionTree.AppSelectionTree.Add(appSelectionTree);

                    //Set Entities
                    foreach (var entity in app.Entities)
                    {
                        appSelectionTree.Entities.Add(new SelectOption()
                        {
                            Value = entity.Entity.Id.ToString(),
                            Label = entity.Entity.Name
                        });
                    }
                    appSelectionTree.Entities = appSelectionTree.Entities.OrderBy(x => x.Label).ToList();
                }
                pageSelectionTree.AllApps = pageSelectionTree.AllApps.OrderBy(x => x.Label).ToList();
            }
            #endregion

            #region << Entity options >>
            foreach (var entity in entities)
            {
                pageSelectionTree.AllEntities.Add(new SelectOption()
                {
                    Value = entity.Id.ToString(),
                    Label = entity.Name
                });
            }
            pageSelectionTree.AllEntities = pageSelectionTree.AllEntities.OrderBy(x => x.Label).ToList();
            #endregion

            #endregion

            ViewBag.PageSelectionTree    = pageSelectionTree;
            ViewBag.ErpPage              = erpPage;
            ViewBag.TypeOptionsFieldId   = typeOptionsFieldId;
            ViewBag.AppOptionsFieldId    = appOptionsFieldId;
            ViewBag.AreaOptionsFieldId   = areaOptionsFieldId;
            ViewBag.NodeOptionsFieldId   = nodeOptionsFieldId;
            ViewBag.EntityOptionsFieldId = entityOptionsFieldId;

            var pageSelectionTreeJson = JsonConvert.SerializeObject(pageSelectionTree);

            ViewBag.EmbededJs = "";
            #region << Generate js script >>
            if (mode == WvFieldRenderMode.Form)
            {
                var jsCompressor = new JavaScriptCompressor();

                #region << Init Scripts >>

                var fileName       = "form.js";
                var scriptEl       = "<script type=\"text/javascript\">";
                var scriptTemplate = FileService.GetEmbeddedTextResource(fileName, "WebVella.Erp.Plugins.SDK.Components.WvSdkPageSitemap", "WebVella.Erp.Plugins.SDK");

                scriptTemplate = scriptTemplate.Replace("\"{{PageSelectionTreeJson}}\";", pageSelectionTreeJson);
                scriptTemplate = scriptTemplate.Replace("{{typeOptionsFieldId}}", typeOptionsFieldId.ToString());
                scriptTemplate = scriptTemplate.Replace("{{appOptionsFieldId}}", appOptionsFieldId.ToString());
                scriptTemplate = scriptTemplate.Replace("{{areaOptionsFieldId}}", areaOptionsFieldId.ToString());
                scriptTemplate = scriptTemplate.Replace("{{nodeOptionsFieldId}}", nodeOptionsFieldId.ToString());
                scriptTemplate = scriptTemplate.Replace("{{entityOptionsFieldId}}", entityOptionsFieldId.ToString());
                scriptEl      += jsCompressor.Compress(scriptTemplate);
                //scriptEl += scriptTemplate;
                scriptEl += "</script>";

                ViewBag.EmbededJs = scriptEl;
                #endregion
            }
            #endregion

            ViewBag.RenderMode = mode;

            var applicationOptions = new List <SelectOption>();
            var areaOptions        = new List <SelectOption>();
            var nodeOptions        = new List <SelectOption>();
            var entityOptions      = new List <SelectOption>();

            #region << Init Options >>
            //AppOptions

            applicationOptions = pageSelectionTree.AllApps;
            applicationOptions.Insert(0, new SelectOption()
            {
                Value = "", Label = "not selected"
            });
            areaOptions.Insert(0, new SelectOption()
            {
                Value = "", Label = "not selected"
            });
            nodeOptions.Insert(0, new SelectOption()
            {
                Value = "", Label = "not selected"
            });
            entityOptions = pageSelectionTree.AllEntities;
            entityOptions.Insert(0, new SelectOption()
            {
                Value = "", Label = "not selected"
            });

            //App is selected
            if (erpPage.AppId != null)
            {
                var treeAppOptions = pageSelectionTree.AppSelectionTree.First(x => x.AppId == erpPage.AppId);

                areaOptions = treeAppOptions.AllAreas;
                if (erpPage.AreaId == null)
                {
                    areaOptions.Insert(0, new SelectOption()
                    {
                        Value = "", Label = "not selected"
                    });
                    nodeOptions.Insert(0, new SelectOption()
                    {
                        Value = "", Label = "not selected"
                    });
                }
                else
                {
                    var treeAreaOptions = treeAppOptions.AreaSelectionTree.FirstOrDefault(x => x.AreaId == erpPage.AreaId);
                    if (treeAreaOptions != null)
                    {
                        nodeOptions = treeAreaOptions.AllNodes;
                    }
                }

                if (treeAppOptions.Entities.Count > 0)
                {
                    entityOptions = treeAppOptions.Entities;
                }
                else
                {
                    entityOptions = pageSelectionTree.AllEntities;
                }
            }

            #endregion

            ViewBag.ApplicationOptions = applicationOptions;
            ViewBag.AreaOptions        = areaOptions;
            ViewBag.NodeOptions        = nodeOptions;
            ViewBag.EntityOptions      = entityOptions;

            if (mode == WvFieldRenderMode.Form)
            {
                return(await Task.FromResult <IViewComponentResult>(View("Form")));
            }
            else
            {
                return(await Task.FromResult <IViewComponentResult>(View("Display")));
            }
        }
Ejemplo n.º 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     = PcFieldCheckboxGridOptions.CopyFromBaseOptions(baseOptions);

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

                //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



                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 <KeyStringList>();
                    }
                    else if (valueResult is List <KeyStringList> )
                    {
                        model.Value = (List <KeyStringList>)valueResult;
                    }
                    else if (valueResult is string)
                    {
                        var stringProcessed = false;
                        if (String.IsNullOrWhiteSpace(valueResult))
                        {
                            model.Value     = new List <KeyStringList>();
                            stringProcessed = true;
                        }
                        if (!stringProcessed && (((string)valueResult).StartsWith("{") || ((string)valueResult).StartsWith("[")))
                        {
                            try
                            {
                                model.Value     = JsonConvert.DeserializeObject <List <KeyStringList> >(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")));
                            }
                        }
                    }
                    {
                        dynamic rowsOptions = context.DataModel.GetPropertyValueByDataSource(options.Rows);
                        if (rowsOptions == null)
                        {
                        }
                        if (rowsOptions is List <SelectOption> )
                        {
                            model.Rows = (List <SelectOption>)rowsOptions;
                        }
                        else if (rowsOptions is string)
                        {
                            var stringProcessed = false;
                            if (String.IsNullOrWhiteSpace(rowsOptions))
                            {
                                model.Rows      = new List <SelectOption>();
                                stringProcessed = true;
                            }
                            if (!stringProcessed && (((string)rowsOptions).StartsWith("{") || ((string)rowsOptions).StartsWith("[")))
                            {
                                try
                                {
                                    model.Rows      = JsonConvert.DeserializeObject <List <SelectOption> >(rowsOptions);
                                    stringProcessed = true;
                                }
                                catch
                                {
                                    stringProcessed          = false;
                                    ViewBag.ExceptionMessage = "Rows Json Deserialization failed!";
                                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                                }
                            }
                            if (!stringProcessed && ((string)rowsOptions).Contains(",") && !((string)rowsOptions).StartsWith("{") && !((string)rowsOptions).StartsWith("["))
                            {
                                var optionsArray = ((string)rowsOptions).Split(',');
                                var optionsList  = new List <SelectOption>();
                                foreach (var optionString in optionsArray)
                                {
                                    optionsList.Add(new SelectOption(optionString, optionString));
                                }
                                model.Rows = optionsList;
                            }
                        }
                    }
                    {
                        dynamic columnsOptions = context.DataModel.GetPropertyValueByDataSource(options.Columns);
                        if (columnsOptions == null)
                        {
                        }
                        if (columnsOptions is List <SelectOption> )
                        {
                            model.Columns = (List <SelectOption>)columnsOptions;
                        }
                        else if (columnsOptions is string)
                        {
                            var stringProcessed = false;
                            if (String.IsNullOrWhiteSpace(columnsOptions))
                            {
                                model.Columns   = new List <SelectOption>();
                                stringProcessed = true;
                            }
                            if (!stringProcessed && (((string)columnsOptions).StartsWith("{") || ((string)columnsOptions).StartsWith("[")))
                            {
                                try
                                {
                                    model.Columns   = JsonConvert.DeserializeObject <List <SelectOption> >(columnsOptions);
                                    stringProcessed = true;
                                }
                                catch
                                {
                                    stringProcessed          = false;
                                    ViewBag.ExceptionMessage = "Columns Json Deserialization failed!";
                                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                                }
                            }
                            if (!stringProcessed && ((string)columnsOptions).Contains(",") && !((string)columnsOptions).StartsWith("{") && !((string)columnsOptions).StartsWith("["))
                            {
                                var optionsArray = ((string)columnsOptions).Split(',');
                                var optionsList  = new List <SelectOption>();
                                foreach (var optionString in optionsArray)
                                {
                                    optionsList.Add(new SelectOption(optionString, optionString));
                                }
                                model.Columns = optionsList;
                            }
                        }
                    }

                    #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")));
            }
        }
Ejemplo n.º 19
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 baseOptions     = InitPcFieldBaseOptions(context);
                var instanceOptions = PcFieldTimeOptions.CopyFromBaseOptions(baseOptions);
                if (context.Options != null)
                {
                    instanceOptions = JsonConvert.DeserializeObject <PcFieldTimeOptions>(context.Options.ToString());
                }
                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")));
            }
        }
Ejemplo n.º 20
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 PcProjectWidgetBudgetOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetBudgetOptions>(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().GetTasks(projectId, null);
                    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, 1);
                    var nonBilledhours = Math.Round(loggedNonBillableMinutes / 60, 1);
                    var estimatedHours = Math.Round(projectEstimatedMinutes / 60, 1);

                    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 = (decimal)projectRecord["budget_amount"] - 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 <ErpChartDataset>()
                    {
                        new ErpChartDataset()
                        {
                            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.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 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 = "/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")));
            }
        }
Ejemplo n.º 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 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 logs = projectTimelogs.FindAll(x => (Guid)x["id"] == new Guid("c121c75f-c7bb-4a30-84e0-b6a5768fb28f") || (Guid)x["id"] == new Guid("a0b60e16-c13d-4214-ab4f-64f28f0db503")).ToList();

                    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")));
            }
        }
Ejemplo n.º 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 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 PcProjectWidgetTaskDistributionOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcProjectWidgetTaskDistributionOptions>(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().GetTaskQueue(projectId, null);

                    var users    = new UserService().GetAll();
                    var userDict = new Dictionary <Guid, EntityRecord>();

                    foreach (var task in projectTasks)
                    {
                        var ownerId    = (Guid?)task["owner_id"];
                        var taskStatus = (Guid)task["status_id"];
                        var endTime    = (DateTime?)task["end_time"];


                        var userRecord = new EntityRecord();
                        userRecord["overdue"] = (int)0;
                        userRecord["today"]   = (int)0;
                        userRecord["other"]   = (int)0;
                        if (ownerId == null && !userDict.ContainsKey(Guid.Empty))
                        {
                            userDict[Guid.Empty] = userRecord;
                        }
                        else if (!userDict.ContainsKey(ownerId.Value))
                        {
                            userDict[ownerId.Value] = userRecord;
                        }

                        var currentRecord = userDict[ownerId != null ? ownerId.Value : Guid.Empty];

                        if (endTime != null)
                        {
                            if (endTime.Value.AddDays(1) < DateTime.Now.Date)
                            {
                                currentRecord["overdue"] = ((int)currentRecord["overdue"]) + 1;
                            }
                            else if (endTime.Value >= DateTime.Now.Date && endTime.Value < DateTime.Now.Date.AddDays(1))
                            {
                                currentRecord["today"] = ((int)currentRecord["today"]) + 1;
                            }
                            else
                            {
                                currentRecord["other"] = ((int)currentRecord["other"]) + 1;
                            }
                        }
                        else
                        {
                            currentRecord["other"] = ((int)currentRecord["other"]) + 1;
                        }
                        userDict[ownerId != null ? ownerId.Value : Guid.Empty] = currentRecord;
                    }

                    var records = new List <EntityRecord>();
                    foreach (var key in userDict.Keys)
                    {
                        if (key == Guid.Empty)
                        {
                            var statRecord = userDict[key];
                            var row        = new EntityRecord();
                            var imagePath  = "/_content/WebVella.Erp.Web/assets/avatar.png";

                            row["user"]    = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> No owner";
                            row["overdue"] = statRecord["overdue"];
                            row["today"]   = statRecord["today"];
                            row["other"]   = statRecord["other"];
                            records.Add(row);
                        }
                        else
                        {
                            var user       = users.First(x => (Guid)x["id"] == key);
                            var statRecord = userDict[key];
                            var row        = new EntityRecord();
                            var imagePath  = "/_content/WebVella.Erp.Web/assets/avatar.png";
                            if (user["image"] != null && (string)user["image"] != "")
                            {
                                imagePath = "/fs" + (string)user["image"];
                            }

                            row["user"]    = $"<img src=\"{imagePath}\" class=\"rounded-circle\" width=\"24\"> {(string)user["username"]}";
                            row["overdue"] = statRecord["overdue"];
                            row["today"]   = statRecord["today"];
                            row["other"]   = statRecord["other"];
                            records.Add(row);
                        }
                    }
                    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")));
            }
        }
Ejemplo n.º 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 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);
                #endregion

                #region << Init DataSources >>
                if (context.Mode != ComponentMode.Options && context.Mode != ComponentMode.Help)
                {
                    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

                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")));
            }
        }
Ejemplo n.º 25
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 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) && 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;
                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")));
            }
        }
Ejemplo n.º 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 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 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 apps = new AppService().GetAllApplications().OrderBy(x => x.Weight).ToList();
                    //Generate Url
                    foreach (var app in apps)
                    {
                        app.HomePages = app.HomePages.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 = apps;
                }


                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")));
            }
        }
Ejemplo n.º 27
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.FlexSelfAlignTypeOptions     = 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")));
            }
        }