public override PickMap BusinessToData(PickMap pickMap, BUSPickMap businessEntity, TContext context, bool NewRecord)
        {
            PickMap dataEntity = base.BusinessToData(pickMap, businessEntity, context, NewRecord);

            dataEntity.Field           = businessEntity.Field;
            dataEntity.FieldId         = businessEntity.FieldId;
            dataEntity.BusCompFieldId  = businessEntity.BusCompFieldId;
            dataEntity.PickListFieldId = businessEntity.PickListFieldId;
            dataEntity.Constrain       = businessEntity.Constrain;
            return(dataEntity);
        }
        public ActionResult <object> Pick(RequestPickListModel model)
        {
            string  newPickedValue             = string.Empty;
            Control control                    = viewInfo.CurrentPopupControl ?? viewInfo.CurrentControl;
            Dictionary <string, object> result = new Dictionary <string, object>()
            {
                { "ErrorMessages", new object()
                  {
                  } },
                { "NewPickedValue", newPickedValue },
                { "Status", string.Empty }
            };

            if (control?.Field != null)
            {
                // Получение необходимых сущностей
                TBUSFactory       busFactory = new TBUSFactory();
                BusinessComponent busComp    = context.BusinessComponents
                                               .AsNoTracking()
                                               .Include(f => f.Fields)
                                               .ThenInclude(pl => pl.PickList)
                                               .Include(f => f.Fields)
                                               .ThenInclude(pl => pl.PickMaps)
                                               .FirstOrDefault(i => i.Id == control.Field.BusCompId);
                Field             field           = busComp.Fields.FirstOrDefault(i => i.Id == control.FieldId);
                PickList          pickList        = field.PickList;
                BusinessComponent pickListBusComp = context.BusinessComponents
                                                    .AsNoTracking()
                                                    .Include(f => f.Fields)
                                                    .FirstOrDefault(i => i.Id == pickList.BusCompId);
                List <PickMap>            pickMaps           = field.PickMaps;
                PickMap                   mapForCurrentField = pickMaps.FirstOrDefault(f => f.BusCompFieldId == field.Id);
                List <TBusinessComponent> pickListRecords    = ComponentsContext <TBusinessComponent> .GetPickListContext();

                // Пикнутая и текущая запись
                dynamic pickedRecord  = model.Value ?? busFactory.GetRecord(null, context, viewInfo, pickListBusComp, "Id", model.PickedRecord);
                dynamic currentRecord = busFactory.GetRecord(null, context, viewInfo, busComp);

                // Если произошел выбор записи из пиклсита
                if (model.IsPicked)
                {
                    // Пик на основе пикмапы
                    pickMaps.Where(c => c.Constrain == false).OrderBy(s => s.Sequence).ToList().ForEach(map =>
                    {
                        string componentField         = busComp.Fields.FirstOrDefault(i => i.Id == map.BusCompFieldId).Name;
                        string PLComponentField       = pickListBusComp.Fields.FirstOrDefault(i => i.Id == map.PickListFieldId).Name;
                        dynamic PLComponentFieldValue = pickedRecord.GetType().GetProperty(PLComponentField).GetValue(pickedRecord);
                        var PLComponentFieldType      = PLComponentFieldValue.GetType();
                        Type componentFieldType       = currentRecord.GetType().GetProperty(componentField).GetValue(currentRecord)?.GetType();
                        if (componentFieldType?.BaseType == typeof(Enum))
                        {
                            switch (componentFieldType.Name)
                            {
                            case "ActionType":
                                PLComponentFieldValue = (ActionType)Enum.Parse(typeof(ActionType), PLComponentFieldValue);
                                break;
                            }
                        }
                        try
                        {
                            currentRecord.GetType().GetProperty(componentField).SetValue(currentRecord, PLComponentFieldValue);
                        }
                        catch (RuntimeBinderException ex)
                        {
                            result["ErrorMessages"] = Utils.GetErrorsInfo(ex);
                            result["Status"]        = "Fail";
                        }
                        if (map.Id == mapForCurrentField.Id)
                        {
                            newPickedValue = PLComponentFieldValue.ToString();
                        }
                    });
                }

                // Если пользователь ввел значение сам или стер его
                else
                {
                    newPickedValue = string.Empty;
                    string componentField = busComp.Fields.FirstOrDefault(i => i.Id == mapForCurrentField.BusCompFieldId).Name;
                    // Если пиклист не позволяет принять введенное пользователем значение
                    if (pickList.Bounded)
                    {
                        // Если значение не пустое, то выполняется поиск такого значения в пиклисте
                        if (!string.IsNullOrWhiteSpace(model.Value))
                        {
                            // Если значение найдено, то оно пикается
                            if (pickListRecords.AsQueryable().Any($"{pickListBusComp.Fields.FirstOrDefault(i => i.Id == mapForCurrentField.PickListFieldId).Name} = \"{model.Value}\""))
                            {
                                dynamic      newValue = model.Value;
                                PropertyInfo property = currentRecord.GetType().GetProperty(componentField);
                                if (property?.Name == "ActionType")
                                {
                                    newValue       = ActionType.None;
                                    newPickedValue = "None";
                                }
                                currentRecord.GetType().GetProperty(componentField).SetValue(currentRecord, newValue);
                                newPickedValue = model.Value;
                            }
                            // Иначе текущая запись никак не меняется и на фронт возвращаетя старое значение
                            else
                            {
                                newPickedValue          = currentRecord.GetType().GetProperty(componentField).GetValue(currentRecord).ToString();
                                result["ErrorMessages"] = new object[] { "This pick list does not allow you to enter your values. Choose a value from the suggested." };
                                result["Status"]        = "Fail";
                            }
                        }
                        // Иначе в текущюю запись проставляется пустая строка, она же и возвращается на фронт
                        else
                        {
                            // Пик на основе пикмапы
                            pickMaps.Where(c => c.Constrain == false).OrderBy(s => s.Sequence).ToList().ForEach(map =>
                            {
                                // Для каждого поля из пикмапы установка дефолтового значения на основании его типа
                                dynamic newValue      = null;
                                componentField        = busComp.Fields.FirstOrDefault(i => i.Id == map.BusCompFieldId).Name;
                                PropertyInfo property = currentRecord.GetType().GetProperty(componentField);
                                Type propertyType     = property.GetType();
                                if (propertyType.GetTypeInfo().IsValueType)
                                {
                                    newValue = Activator.CreateInstance(propertyType);
                                }
                                if (property?.Name == "ActionType")
                                {
                                    newValue       = ActionType.None;
                                    newPickedValue = "None";
                                }
                                else
                                {
                                    newPickedValue = string.Empty;
                                }
                                currentRecord.GetType().GetProperty(componentField).SetValue(currentRecord, newValue);
                            });
                        }
                    }
                    // Иначе
                    else
                    {
                        currentRecord.GetType().GetProperty(componentField).SetValue(currentRecord, model.Value);
                        newPickedValue = model.Value;
                    }
                }

                // Установка текущей записи
                busFactory.SetRecord(null, context, viewInfo, busComp, currentRecord);
            }
            if (result["Status"].ToString() == string.Empty)
            {
                result["Status"] = "Done";
            }
            result["NewPickedValue"] = newPickedValue;
            return(result);
        }
        public ActionResult <object> PickListRecords()
        {
            Control control = viewInfo.CurrentPopupControl ?? viewInfo.CurrentControl;

            if (control?.Field != null)
            {
                // Получение необходимых сущностей
                BusinessComponent busComp = context.BusinessComponents
                                            .AsNoTracking()
                                            .Include(f => f.Fields)
                                            .ThenInclude(pl => pl.PickList)
                                            .Include(f => f.Fields)
                                            .ThenInclude(pl => pl.PickMaps)
                                            .FirstOrDefault(i => i.Id == control.Field.BusCompId);
                TBUSFactory               busFactory       = new TBUSFactory();
                TDataBUSFactory           dataBUSFactory   = new TDataBUSFactory();
                List <TBusinessComponent> businessEntities = new List <TBusinessComponent>();
                Field          field              = busComp.Fields.FirstOrDefault(i => i.Id == control.FieldId);
                PickList       pickList           = field.PickList;
                List <PickMap> pickMaps           = field.PickMaps;
                PickMap        mapForCurrentField = pickMaps.FirstOrDefault(f => f.BusCompFieldId == field.Id);

                // Текущая запись
                dynamic currentRecord = busFactory.GetRecord(null, context, viewInfo, busComp);
                DataBUSPickMapFR <TContext>  dataBUSPickMapFR  = new DataBUSPickMapFR <TContext>();
                DataBUSPickListFR <TContext> dataBUSPickListFR = new DataBUSPickListFR <TContext>();
                BUSUIPickListFR <TContext>   busUIPickListFR   = new BUSUIPickListFR <TContext>();

                // Мапа, на основании которой принимается решение о том, данные какого поля будут отображаться в пиклисте
                if (mapForCurrentField != null)
                {
                    IEnumerable <TTable> dataEntities      = orderedEntities.ToList();
                    List <PickMap>       constrainPickMaps = pickMaps.Where(c => c.Constrain).ToList();
                    if (currentRecord != null)
                    {
                        // Ограничение отбираемых для пиклсита записей по constrain пик мапам
                        constrainPickMaps.ForEach(constrainMap =>
                        {
                            BUSPickMap businessEntity            = dataBUSPickMapFR.DataToBusiness(constrainMap, context);
                            string constrainPickListField        = businessEntity.PickListFieldName;
                            string constrainComponentField       = businessEntity.BusCompFieldName;
                            dynamic constrainComponentFieldValue = currentRecord.GetType().GetProperty(constrainComponentField).GetValue(currentRecord);
                            if (constrainComponentFieldValue != null)
                            {
                                constrainComponentFieldValue = constrainComponentFieldValue.ToString();
                                dataEntities = dataEntities.AsQueryable().Where($"{constrainPickListField} = \"{constrainComponentFieldValue}\"").ToList();
                            }
                            else
                            {
                                dataEntities = new List <TTable>();
                            }
                        });
                    }
                    // Ограничение отбираемых для пиклсита записей по search spec на пиклисте
                    if (!string.IsNullOrWhiteSpace(pickList.SearchSpecification))
                    {
                        var conversionSearchSpecification = Utils.SearchSpecificationConversion(pickList.SearchSpecification, currentRecord);
                        dataEntities = dataEntities.AsQueryable().Where($"{conversionSearchSpecification}").ToList();
                    }

                    // Получение названий для филды с бизнес компоненты и пиклиста для отбора отображаемых записей и получение текущей
                    BUSPickMap businessEntity = dataBUSPickMapFR.DataToBusiness(mapForCurrentField, context);
                    string     componentField = businessEntity.BusCompFieldName;
                    string     pickListField  = businessEntity.PickListFieldName;
                    dataEntities.ToList().ForEach(dataEntity => businessEntities.Add(dataBUSFactory.DataToBusiness(dataEntity, context)));
                    ComponentsContext <TBusinessComponent> .SetPickListContext(businessEntities);

                    IQueryable displayedPickListRecords = businessEntities.AsQueryable().Select($"new(Id, {pickListField} as Value)");
                    UIPickList pickListInfo             = busUIPickListFR.BusinessToUI(dataBUSPickListFR.DataToBusiness(pickList, context));

                    // Установка текущей выбранной записи в пиклисте
                    if (currentRecord != null)
                    {
                        pickListInfo.CurrentRecordId = businessEntities.AsQueryable()
                                                       .FirstOrDefault($"{pickListField} = \"{currentRecord.GetType().GetProperty(componentField).GetValue(currentRecord)}\"")?.Id;
                    }

                    return(JsonConvert.SerializeObject(
                               new Dictionary <string, object>
                    {
                        { "PickListInfo", pickListInfo },
                        { "DisplayedPickListRecords", displayedPickListRecords }
                    }, Formatting.Indented, new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    }));
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
        public override BUSPickMap DataToBusiness(PickMap dataEntity, TContext context)
        {
            BUSPickMap businessEntity = base.DataToBusiness(dataEntity, context);

            // Field
            Field field = context.Fields
                          .AsNoTracking()
                          .Select(f => new
            {
                id        = f.Id,
                busComp   = f.BusComp,
                busCompId = f.BusCompId
            })
                          .Select(f => new Field
            {
                Id        = f.id,
                BusComp   = f.busComp,
                BusCompId = f.busCompId
            })
                          .FirstOrDefault(i => i.Id == dataEntity.FieldId);

            businessEntity.Field     = field;
            businessEntity.FieldId   = field.Id;
            businessEntity.BusComp   = field.BusComp;
            businessEntity.BusCompId = field.BusCompId;

            // BusCompField
            Field busCompField = context.Fields.AsNoTracking().FirstOrDefault(i => i.Id == dataEntity.BusCompFieldId);

            if (busCompField != null)
            {
                businessEntity.BusCompField     = busCompField;
                businessEntity.BusCompFieldId   = busCompField.Id;
                businessEntity.BusCompFieldName = busCompField.Name;
            }

            // PickListField
            Field pickListField = context.Fields
                                  .AsNoTracking()
                                  .Select(f => new
            {
                id        = f.Id,
                name      = f.Name,
                busComp   = f.BusComp,
                busCompId = f.BusCompId
            })
                                  .Select(f => new Field
            {
                Id        = f.id,
                Name      = f.name,
                BusComp   = f.busComp,
                BusCompId = f.busCompId
            })
                                  .FirstOrDefault(i => i.Id == dataEntity.PickListFieldId);

            if (pickListField != null)
            {
                businessEntity.PickListField     = pickListField;
                businessEntity.PickListFieldId   = pickListField.Id;
                businessEntity.PickListFieldName = pickListField.Name;
                businessEntity.PickListBusComp   = pickListField.BusComp;
                businessEntity.PickListBusCompId = pickListField.BusCompId;
            }

            businessEntity.Constrain = dataEntity.Constrain;
            return(businessEntity);
        }
Ejemplo n.º 5
0
        public override BUSPickMap UIToBusiness(UIPickMap UIEntity, TContext context, IViewInfo viewInfo, bool isNewRecord)
        {
            BUSPickMap businessEntity = base.UIToBusiness(UIEntity, context, viewInfo, isNewRecord);
            Field      field          = context.Fields.FirstOrDefault(i => i.Id.ToString() == ComponentsRecordsInfo.GetSelectedRecord("Field"));

            if (field == null)
            {
                businessEntity.ErrorMessage = "First you need create field.";
            }
            else
            {
                // Если запись новая и она не уникальна, записывается ошибка
                PickMap pickMap = field.PickMaps?.FirstOrDefault(n => n.Name == UIEntity.Name);
                if (pickMap != null && pickMap.Id != UIEntity.Id)
                {
                    businessEntity.ErrorMessage = $"Field pick map with this name is already exists in field {UIEntity.Name}.";
                }
                else
                {
                    businessEntity.Field   = field;
                    businessEntity.FieldId = field.Id;

                    // BusComp and pickList
                    PickList pickList = context.PickLists
                                        .AsNoTracking()
                                        .Select(pl => new
                    {
                        id      = pl.Id,
                        busComp = new
                        {
                            id     = pl.BusCompId,
                            fields = pl.BusComp.Fields.Select(field => new
                            {
                                id   = field.Id,
                                name = field.Name,
                            })
                        }
                    })
                                        .Select(pl => new PickList
                    {
                        Id      = pl.id,
                        BusComp = new BusinessComponent
                        {
                            Id     = pl.busComp.id,
                            Fields = pl.busComp.fields.Select(field => new Field
                            {
                                Id   = field.id,
                                Name = field.name
                            }).ToList()
                        }
                    })
                                        .FirstOrDefault(i => i.Id == field.PickListId);

                    // PickList
                    if (pickList != null)
                    {
                        businessEntity.PickList   = pickList;
                        businessEntity.PickListId = pickList.Id;

                        BusinessComponent busComp = context.BusinessComponents
                                                    .AsNoTracking()
                                                    .Select(bc => new
                        {
                            id     = bc.Id,
                            fields = bc.Fields.Select(field => new
                            {
                                id   = field.Id,
                                name = field.Name,
                            })
                        })
                                                    .Select(bc => new BusinessComponent
                        {
                            Id     = bc.id,
                            Fields = bc.fields.Select(field => new Field
                            {
                                Id   = field.id,
                                Name = field.name
                            }).ToList()
                        })
                                                    .FirstOrDefault(i => i.Id == field.BusCompId);

                        BusinessComponent pickListBusComp = pickList.BusComp;
                        businessEntity.BusComp   = busComp;
                        businessEntity.BusCompId = busComp.Id;

                        if (pickListBusComp != null)
                        {
                            businessEntity.PickListBusComp   = pickListBusComp;
                            businessEntity.PickListBusCompId = pickListBusComp.Id;

                            // BusCompField
                            Field busCompField = busComp.Fields.FirstOrDefault(n => n.Name == UIEntity.BusCompFieldName);
                            if (busCompField != null)
                            {
                                businessEntity.BusCompField     = busCompField;
                                businessEntity.BusCompFieldId   = busCompField.Id;
                                businessEntity.BusCompFieldName = busCompField.Name;
                            }

                            // PickListField
                            Field pickListField = pickListBusComp.Fields.FirstOrDefault(n => n.Name == UIEntity.PickListFieldName);
                            if (pickListField != null)
                            {
                                businessEntity.PickListField     = pickListField;
                                businessEntity.PickListFieldId   = pickListField.Id;
                                businessEntity.PickListFieldName = pickListField.Name;
                            }
                        }
                    }

                    businessEntity.Constrain = UIEntity.Constrain;
                }
            }
            return(businessEntity);
        }