public async Task ItemList_Save_DoesSave()
        {
            // Arrange
            var planning = new Planning
            {
                Description      = Guid.NewGuid().ToString(),
                Enabled          = true,
                RelatedEFormId   = 35,
                RelatedEFormName = Guid.NewGuid().ToString(),
                RepeatType       = RepeatType.Day,
                UpdatedByUserId  = 1,
                CreatedByUserId  = 1,
                RepeatUntil      = new DateTime(2050, 1, 1, 1, 1, 1),
                DayOfWeek        = DayOfWeek.Friday,
                RepeatEvery      = 1,
                DayOfMonth       = 3,
                Version          = 1,
                WorkflowState    = Constants.WorkflowStates.Created,
                LocationCode     = "2",
                PlanningNumber   = "1",
            };

            // Act
            await planning.Create(DbContext);

            var planingNameTranslations = new List <PlanningNameTranslation>()
            {
                new PlanningNameTranslation()
                {
                    Name     = Guid.NewGuid().ToString(),
                    Language = new Language()
                    {
                        LanguageCode = "da", Name = "Danish"
                    },
                    Planning = planning
                }
            };

            foreach (var translationModel in planingNameTranslations)
            {
                await translationModel.Create(DbContext);
            }

            var planningLists = DbContext.Plannings
                                .AsNoTracking()
                                .ToList();

            var planingNameTranslationsList = DbContext.PlanningNameTranslation
                                              .AsNoTracking()
                                              .Where(x => x.Planning.Id == planningLists[0].Id)
                                              .ToList();

            var planningVersionsList = DbContext.PlanningVersions.AsNoTracking().ToList();

            var planingNameTranslationsListVersions = DbContext.PlanningNameTranslationVersions
                                                      .AsNoTracking()
                                                      .Where(x => x.PlanningNameTranslationId == planingNameTranslationsList[0].Id)
                                                      .ToList();

            // Assert
            Assert.AreEqual(1, planningLists.Count);
            Assert.AreEqual(1, planningVersionsList.Count);
            Assert.AreEqual(planingNameTranslations[0].Name, planingNameTranslationsList[0].Name);
            Assert.AreEqual(planning.CreatedByUserId, planningLists[0].CreatedByUserId);
            Assert.AreEqual(planning.UpdatedByUserId, planningLists[0].UpdatedByUserId);
            Assert.AreEqual(planning.Description, planningLists[0].Description);
            Assert.AreEqual(planning.Enabled, planningLists[0].Enabled);
            Assert.AreEqual(planning.RepeatType, planningLists[0].RepeatType);
            Assert.AreEqual(planning.RelatedEFormId, planningLists[0].RelatedEFormId);
            Assert.AreEqual(planning.RelatedEFormName, planningLists[0].RelatedEFormName);
            Assert.AreEqual(Constants.WorkflowStates.Created, planningLists[0].WorkflowState);
            Assert.AreEqual(planning.RepeatUntil, planningLists[0].RepeatUntil);
            Assert.AreEqual(planning.DayOfWeek, planningLists[0].DayOfWeek);
            Assert.AreEqual(planning.RepeatEvery, planningLists[0].RepeatEvery);
            Assert.AreEqual(planning.DayOfMonth, planningLists[0].DayOfMonth);
            Assert.AreEqual(planning.Id, planningLists[0].Id);
            Assert.AreEqual(planning.PlanningNumber, planningLists[0].PlanningNumber);
            Assert.AreEqual(planning.LocationCode, planningLists[0].LocationCode);
            Assert.AreEqual(1, planningLists[0].Version);

            // versions
            Assert.AreEqual(planingNameTranslations[0].Name, planingNameTranslationsListVersions[0].Name);
            Assert.AreEqual(planning.Description, planningVersionsList[0].Description);
            Assert.AreEqual(planning.Enabled, planningVersionsList[0].Enabled);
            Assert.AreEqual(planning.RepeatType, planningVersionsList[0].RepeatType);
            Assert.AreEqual(planning.RelatedEFormId, planningVersionsList[0].RelatedEFormId);
            Assert.AreEqual(planning.RelatedEFormName, planningVersionsList[0].RelatedEFormName);
            Assert.AreEqual(planning.Id, planningVersionsList[0].PlanningId);
            Assert.AreEqual(Constants.WorkflowStates.Created, planningVersionsList[0].WorkflowState);
            Assert.AreEqual(planning.RepeatUntil, planningVersionsList[0].RepeatUntil);
            Assert.AreEqual(planning.DayOfWeek, planningVersionsList[0].DayOfWeek);
            Assert.AreEqual(planning.DayOfMonth, planningVersionsList[0].DayOfMonth);
            Assert.AreEqual(planning.RepeatEvery, planningVersionsList[0].RepeatEvery);
            Assert.AreEqual(planning.PlanningNumber, planningVersionsList[0].PlanningNumber);
            Assert.AreEqual(planning.LocationCode, planningVersionsList[0].LocationCode);
            Assert.AreEqual(1, planningVersionsList[0].Version);
        }
예제 #2
0
        public async Task PlanningCase_Save_DoesSave()
        {
            // Arrange
            var planning = new Planning();

            await planning.Create(DbContext);

            var commonTranslationModels = new List <PlanningNameTranslation>()
            {
                new PlanningNameTranslation()
                {
                    Name     = Guid.NewGuid().ToString(),
                    Language = new Language()
                    {
                        LanguageCode = "da", Name = "Danish"
                    },
                    Planning = planning
                }
            };

            foreach (var translationModel in commonTranslationModels)
            {
                await translationModel.Create(DbContext);
            }


            var planningCase = new PlanningCase
            {
                MicrotingSdkSiteId  = 24,
                MicrotingSdkCaseId  = 34,
                MicrotingSdkeFormId = 234,
                Status     = 66,
                PlanningId = planning.Id,
            };

            // Act
            await planningCase.Create(DbContext);

            var planningCases        = DbContext.PlanningCases.AsNoTracking().ToList();
            var planningCaseVersions = DbContext.PlanningCaseVersions.AsNoTracking().ToList();

            // Assert
            Assert.AreEqual(1, planningCases.Count);
            Assert.AreEqual(1, planningCaseVersions.Count);
            Assert.AreEqual(planningCase.MicrotingSdkSiteId, planningCases[0].MicrotingSdkSiteId);
            Assert.AreEqual(planningCase.MicrotingSdkCaseId, planningCases[0].MicrotingSdkCaseId);
            Assert.AreEqual(planningCase.MicrotingSdkeFormId, planningCases[0].MicrotingSdkeFormId);
            Assert.AreEqual(planningCase.Status, planningCases[0].Status);
            Assert.AreEqual(Constants.WorkflowStates.Created, planningCases[0].WorkflowState);
            Assert.AreEqual(planningCase.Id, planningCases[0].Id);
            Assert.AreEqual(planningCase.PlanningId, planningCases[0].PlanningId);
            Assert.AreEqual(1, planningCases[0].Version);

            Assert.AreEqual(planningCase.MicrotingSdkSiteId, planningCaseVersions[0].MicrotingSdkSiteId);
            Assert.AreEqual(planningCase.MicrotingSdkCaseId, planningCaseVersions[0].MicrotingSdkCaseId);
            Assert.AreEqual(planningCase.MicrotingSdkeFormId, planningCaseVersions[0].MicrotingSdkeFormId);
            Assert.AreEqual(planningCase.Status, planningCaseVersions[0].Status);
            Assert.AreEqual(Constants.WorkflowStates.Created, planningCaseVersions[0].WorkflowState);
            Assert.AreEqual(planningCase.Id, planningCaseVersions[0].PlanningCaseId);
            Assert.AreEqual(planningCase.PlanningId, planningCaseVersions[0].PlanningId);
            Assert.AreEqual(1, planningCaseVersions[0].Version);
        }
        public async Task <OperationDataResult <ExcelParseResult> > ImportPlannings(Stream excelStream)
        {
            try
            {
                var result = new ExcelParseResult();
                var core   = await _coreService.GetCore();

                await using var microtingDbContext = core.DbContextHelper.GetDbContext();

                var timeZone = await _userService.GetCurrentUserTimeZoneInfo();

                await using var dbContext = core.DbContextHelper.GetDbContext();
                var theLanguage = await dbContext.Languages
                                  .SingleAsync(x => x.LanguageCode == "da");

                var templatesDto = await core.TemplateItemReadAll(
                    false,
                    "",
                    "",
                    false,
                    "",
                    new List <int>(),
                    timeZone, theLanguage);

                // Parse excel file
                var fileResult = _planningExcelService.ParsePlanningImportFile(excelStream);

                // Get planning names list
                var planningNames = await _dbContext.PlanningNameTranslation
                                    .AsNoTracking()
                                    .Where(x => x.WorkflowState != Constants.WorkflowStates.Removed &&
                                           x.LanguageId == theLanguage.Id)
                                    .Select(x => x.Name)
                                    .ToListAsync();

                // Validation
                var excelErrors = new List <ExcelParseErrorModel>();

                List <string> languageCodes = new List <string>()
                {
                    "da",
                    "en-US",
                    "de-DE"
                };

                foreach (var excelModel in fileResult)
                {
                    if (string.IsNullOrEmpty(excelModel.EFormName))
                    {
                        var error = new ExcelParseErrorModel
                        {
                            Col     = PlanningImportExcelConsts.EformNameCol,
                            Row     = excelModel.ExcelRow,
                            Message = _itemsPlanningLocalizationService.GetString(
                                "EformNameIsEmpty")
                        };

                        excelErrors.Add(error);
                    }

                    if (string.IsNullOrEmpty(excelModel.PlanningName))
                    {
                        var error = new ExcelParseErrorModel
                        {
                            Col     = PlanningImportExcelConsts.PlanningItemNameCol,
                            Row     = excelModel.ExcelRow,
                            Message = _itemsPlanningLocalizationService.GetString(
                                "ItemNameIsEmpty")
                        };

                        excelErrors.Add(error);
                    }

                    if (!excelModel.Folders.Any())
                    {
                        var error = new ExcelParseErrorModel
                        {
                            Row     = excelModel.ExcelRow,
                            Message = _itemsPlanningLocalizationService.GetString(
                                "FolderNotFound")
                        };

                        excelErrors.Add(error);
                    }


                    //if (!string.IsNullOrEmpty(planningName))
                    //{
                    //    var error = new ExcelParseErrorModel
                    //    {
                    //        Col = PlanningImportExcelConsts.PlanningItemNameCol,
                    //        Row = excelModel.ExcelRow,
                    //        Message = _itemsPlanningLocalizationService.GetString(
                    //            "PlanningWithNameAlreadyExists",
                    //            excelModel.PlanningName)
                    //    };

                    //    excelErrors.Add(error);
                    //}

                    var templateByName = templatesDto
                                         .FirstOrDefault(x =>
                                                         x.Label ==
                                                         excelModel.EFormName);

                    if (templateByName == null)
                    {
                        var error = new ExcelParseErrorModel
                        {
                            Col     = PlanningImportExcelConsts.EformNameCol,
                            Row     = excelModel.ExcelRow,
                            Message = _itemsPlanningLocalizationService.GetString(
                                "EformNotFound")
                        };

                        excelErrors.Add(error);
                    }
                    else
                    {
                        excelModel.EFormId = templateByName.Id;
                    }
                }

                result.Errors = excelErrors;

                if (excelErrors.Any())
                {
                    return(new OperationDataResult <ExcelParseResult>(
                               true,
                               result));
                }


                // Process plannings
                //using (var transaction = await _dbContext.Database.BeginTransactionAsync())
                //{
                try
                {
                    // Process planning tags
                    var tags = await _dbContext.PlanningTags
                               //.AsNoTracking()
                               .Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
                               .Select(x => new
                    {
                        x.Id,
                        Name = x.Name,
                    }).ToListAsync();

                    // Trim tag names
                    foreach (var excelModel in fileResult)
                    {
                        for (var y = 0; y < excelModel.Tags.Count; y++)
                        {
                            excelModel.Tags[y] = excelModel.Tags[y].Trim();
                        }
                    }

                    var fileTags = fileResult.SelectMany(x => x.Tags)
                                   .GroupBy(x => x)
                                   .Select(x => x.Key)
                                   .ToList();

                    foreach (var fileTag in fileTags)
                    {
                        var planningTagExist = tags.FirstOrDefault(x =>
                                                                   x.Name ==
                                                                   fileTag);

                        if (planningTagExist == null)
                        {
                            var planningTag = new PlanningTag
                            {
                                Name            = fileTag,
                                CreatedByUserId = _userService.UserId,
                                UpdatedByUserId = _userService.UserId,
                            };
                            await planningTag.Create(_dbContext);
                        }
                    }

                    tags = await _dbContext.PlanningTags
                           .AsNoTracking()
                           .Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
                           .Select(x => new
                    {
                        x.Id,
                        Name = x.Name,
                    }).ToListAsync();

                    // Folders
                    var danishLanguage = await dbContext.Languages.SingleOrDefaultAsync(x => x.LanguageCode == "da");

                    var folders = await dbContext.Folders
                                  .Join(dbContext.FolderTranslations,
                                        folder => folder.Id,
                                        translation => translation.FolderId,
                                        (folder, translation) => new
                    {
                        folderWorkflowState      = folder.WorkflowState,
                        translationWorkflowState = translation.WorkflowState,
                        folder.Id,
                        translation.Name,
                        translation.Description,
                        folder.ParentId,
                        translation.LanguageId
                    })
                                  .AsNoTracking()
                                  .Where(x => x.LanguageId == danishLanguage.Id)
                                  .Where(x => x.folderWorkflowState != Constants.WorkflowStates.Removed)
                                  .Select(x => new PlanningImportFolderModel
                    {
                        Id          = x.Id,
                        Label       = x.Name,
                        Description = x.Description,
                        ParentId    = x.ParentId,
                    }).ToListAsync();

                    // Process folders
                    foreach (var excelModel in fileResult)
                    {
                        for (var i = 0; i < excelModel.Folders.Count; i++)
                        {
                            var level       = i + 1;
                            var folderModel = excelModel.Folders[i];

                            if (level == 1)
                            {
                                var mainFolder = folders.FirstOrDefault(x =>
                                                                        x.Label ==
                                                                        folderModel.Label.Split("|")[0] &&
                                                                        x.ParentId == null);

                                if (mainFolder == null)
                                {
                                    List <KeyValuePair <string, string> > names        = new List <KeyValuePair <string, string> >();
                                    List <KeyValuePair <string, string> > descriptions = new List <KeyValuePair <string, string> >();

                                    var sourceNames        = folderModel.Label.Split("|");
                                    var sourceDescriptions = folderModel.Description.Split("|");
                                    names.Add(new KeyValuePair <string, string>("da", sourceNames[0]));
                                    descriptions.Add(new KeyValuePair <string, string>("da", sourceDescriptions[0]));
                                    if (sourceNames.Length > 1)
                                    {
                                        names.Add(new KeyValuePair <string, string>("en-US", sourceNames[1]));
                                    }
                                    else
                                    {
                                        names.Add(new KeyValuePair <string, string>("en-US", ""));
                                    }
                                    if (sourceNames.Length > 2)
                                    {
                                        names.Add(new KeyValuePair <string, string>("de-DE", sourceNames[2]));
                                    }
                                    else
                                    {
                                        names.Add(new KeyValuePair <string, string>("de-DE", ""));
                                    }


                                    if (sourceDescriptions.Length > 1)
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("en-US", sourceDescriptions[1]));
                                    }
                                    else
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("en-US", ""));
                                    }
                                    if (sourceNames.Length > 2)
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("de-DE", sourceDescriptions[2]));
                                    }
                                    else
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("de-DE", ""));
                                    }
                                    folderModel.Id = await core.FolderCreate(
                                        names,
                                        descriptions,
                                        null);
                                }
                                else
                                {
                                    folderModel.Id = mainFolder.Id;
                                }

                                folderModel.Description = folderModel.Description.Split("|")[0];
                                folderModel.Label       = folderModel.Label.Split("|")[0];
                                folders.Add(folderModel);
                            }

                            if (level > 1)
                            {
                                var parentId = excelModel.Folders[i - 1].Id;

                                var sdkFolder = folders.FirstOrDefault(x =>
                                                                       x.Label ==
                                                                       folderModel.Label.Split("|")[0] &&
                                                                       x.ParentId == parentId);


                                if (sdkFolder == null)
                                {
                                    List <KeyValuePair <string, string> > names        = new List <KeyValuePair <string, string> >();
                                    List <KeyValuePair <string, string> > descriptions = new List <KeyValuePair <string, string> >();

                                    var sourceNames        = folderModel.Label.Split("|");
                                    var sourceDescriptions = folderModel.Description.Split("|");
                                    names.Add(new KeyValuePair <string, string>("da", sourceNames[0]));
                                    descriptions.Add(new KeyValuePair <string, string>("da", sourceDescriptions[0]));
                                    if (sourceNames.Length > 1)
                                    {
                                        names.Add(new KeyValuePair <string, string>("en-US", sourceNames[1]));
                                    }
                                    else
                                    {
                                        names.Add(new KeyValuePair <string, string>("en-US", ""));
                                    }
                                    if (sourceNames.Length > 2)
                                    {
                                        names.Add(new KeyValuePair <string, string>("de-DE", sourceNames[2]));
                                    }
                                    else
                                    {
                                        names.Add(new KeyValuePair <string, string>("de-DE", ""));
                                    }


                                    if (sourceDescriptions.Length > 1)
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("en-US", sourceDescriptions[1]));
                                    }
                                    else
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("en-US", ""));
                                    }
                                    if (sourceNames.Length > 2)
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("de-DE", sourceDescriptions[2]));
                                    }
                                    else
                                    {
                                        descriptions.Add(new KeyValuePair <string, string>("de-DE", ""));
                                    }

                                    folderModel.Id = await core.FolderCreate(
                                        names,
                                        descriptions,
                                        parentId);
                                }
                                else
                                {
                                    folderModel.Id = sdkFolder.Id;
                                }

                                folderModel.ParentId = parentId;

                                folderModel.Description = folderModel.Description.Split("|")[0];
                                folderModel.Label       = folderModel.Label.Split("|")[0];

                                folders.Add(folderModel);
                            }
                        }
                    }

                    // Process plannings
                    foreach (var excelModel in fileResult)
                    {
                        var tagIds = new List <int>();
                        if (excelModel.Tags.Any())
                        {
                            foreach (var tagName in excelModel.Tags)
                            {
                                var planningTagExist = tags.FirstOrDefault(x => x.Name == tagName);

                                if (planningTagExist != null)
                                {
                                    tagIds.Add(planningTagExist.Id);
                                }
                            }
                        }

                        var planningNameFromExcelModel = excelModel.PlanningName.Split("|").First();

                        var sdkFolder = excelModel.Folders.Last();
                        // Find planning name
                        var planningName = _dbContext.PlanningNameTranslation
                                           .Join(_dbContext.Plannings,
                                                 planningNameTranslation => planningNameTranslation.PlanningId,
                                                 plannings => plannings.Id,
                                                 (planningNameTranslation, planning) => new
                        {
                            planning.SdkFolderId,
                            planningNameTranslation.Name,
                            planningNameTranslation.PlanningId,
                            planning.WorkflowState
                        }).FirstOrDefault(x =>
                                          x.Name == planningNameFromExcelModel &&
                                          x.SdkFolderId == sdkFolder.Id &&
                                          x.WorkflowState != Constants.WorkflowStates.Removed);

                        if (planningName != null)
                        {
                            var planningFromDb = await _dbContext.Plannings
                                                 .Where(x => x.Id == planningName.PlanningId)
                                                 .FirstAsync();

                            var planningTranslations = _dbContext.PlanningNameTranslation
                                                       .Where(x => x.PlanningId == planningFromDb.Id)
                                                       .ToList();

                            // create or update name tranlations planning
                            var i = 1;
                            foreach (var translationText in excelModel.PlanningName.Split("|"))
                            {
                                var language = await dbContext.Languages.SingleAsync(x => x.Id == i);

                                var planningNameTranslation =
                                    planningTranslations
                                    .Where(x => x.PlanningId == planningFromDb.Id)
                                    .FirstOrDefault(x => x.LanguageId == i);
                                if (planningNameTranslation == null)
                                {
                                    planningNameTranslation = new PlanningNameTranslation
                                    {
                                        Name            = translationText,
                                        LanguageId      = language.Id,
                                        PlanningId      = planningFromDb.Id,
                                        CreatedByUserId = _userService.UserId,
                                        UpdatedByUserId = _userService.UserId,
                                    };
                                    await planningNameTranslation.Create(_dbContext);
                                }
                                else
                                {
                                    planningNameTranslation.UpdatedByUserId = _userService.UserId;
                                    planningNameTranslation.WorkflowState   = Constants.WorkflowStates.Created;

                                    await planningNameTranslation.Update(_dbContext);
                                }

                                i++;
                            }

                            if (excelModel.DayOfMonth != null && planningFromDb.DayOfMonth != excelModel.DayOfMonth)
                            {
                                planningFromDb.DayOfMonth = excelModel.DayOfMonth;
                            }
                            if (excelModel.DayOfWeek != null && planningFromDb.DayOfWeek != excelModel.DayOfWeek)
                            {
                                planningFromDb.DayOfWeek = excelModel.DayOfWeek;
                            }
                            if (excelModel.RepeatEvery != null && planningFromDb.RepeatEvery != excelModel.RepeatEvery)
                            {
                                planningFromDb.RepeatEvery = (int)excelModel.RepeatEvery;
                            }
                            if (excelModel.RepeatType != null && planningFromDb.RepeatType != excelModel.RepeatType)
                            {
                                planningFromDb.RepeatType = (RepeatType)excelModel.RepeatType;
                            }
                            if (excelModel.RepeatUntil != null && planningFromDb.RepeatUntil != excelModel.RepeatUntil)
                            {
                                planningFromDb.RepeatUntil = excelModel.RepeatUntil;
                            }
                            planningFromDb.UpdatedByUserId = _userService.UserId;
                            planningFromDb.StartDate       = DateTime.Now;
                            planningFromDb.WorkflowState   = Constants.WorkflowStates.Created;

                            var tagsIdForAddToPlanningTags = planningFromDb.PlanningsTags
                                                             .Where(x => tagIds.Any(y => x.PlanningTagId != y)).ToList();

                            var tagsIdForRemoveInPlanningTags = tagIds
                                                                .Where(x => planningFromDb.PlanningsTags.Any(y => x != y.PlanningTagId)).ToList();
                            if (tagsIdForAddToPlanningTags.Any())
                            {
                                foreach (var tagsIdForAddToPlanningTag in tagsIdForAddToPlanningTags)
                                {
                                    planningFromDb.PlanningsTags.Add(
                                        new PlanningsTags
                                    {
                                        CreatedByUserId = _userService.UserId,
                                        UpdatedByUserId = _userService.UserId,
                                        PlanningTagId   = tagsIdForAddToPlanningTag.PlanningTagId
                                    });
                                }
                            }
                            if (tagsIdForRemoveInPlanningTags.Any())
                            {
                                foreach (var tagsIdForAddToPlanningTag in tagsIdForAddToPlanningTags)
                                {
                                    await planningFromDb.PlanningsTags
                                    .Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
                                    .FirstOrDefault(x => x.PlanningTagId == tagsIdForAddToPlanningTag.PlanningTagId)
                                    .Delete(_dbContext);
                                }
                            }
                            await planningFromDb.Update(_dbContext);
                        }
                        else
                        {
                            sdkFolder = excelModel.Folders.Last();
                            var newPlanning = new Planning
                            {
                                CreatedByUserId  = _userService.UserId,
                                RepeatUntil      = excelModel.RepeatUntil,
                                DayOfWeek        = excelModel.DayOfWeek,
                                DayOfMonth       = excelModel.DayOfMonth,
                                Enabled          = true,
                                RelatedEFormId   = (int)excelModel.EFormId,
                                RelatedEFormName = excelModel.EFormName,
                                PlanningsTags    = new List <PlanningsTags>(),
                                SdkFolderName    = sdkFolder?.Label,
                                SdkFolderId      = sdkFolder?.Id,
                                StartDate        = DateTime.UtcNow,
                                RepeatEvery      = excelModel.RepeatEvery ?? 1,
                                RepeatType       = excelModel.RepeatType ?? RepeatType.Month,
                                IsLocked         = false,
                                IsEditable       = true,
                                IsHidden         = false
                            };

                            foreach (var tagId in tagIds)
                            {
                                newPlanning.PlanningsTags.Add(
                                    new PlanningsTags
                                {
                                    CreatedAt       = DateTime.UtcNow,
                                    CreatedByUserId = _userService.UserId,
                                    UpdatedAt       = DateTime.UtcNow,
                                    UpdatedByUserId = _userService.UserId,
                                    Version         = 1,
                                    PlanningTagId   = tagId
                                });
                            }

                            await newPlanning.Create(_dbContext);

                            var i = 1;
                            foreach (var translationText in excelModel.PlanningName.Split("|"))
                            {
                                var language = await dbContext.Languages.SingleAsync(x => x.Id == i);

                                var planningNameTranslation = new PlanningNameTranslation()
                                {
                                    Name       = translationText,
                                    LanguageId = language.Id,
                                    PlanningId = newPlanning.Id
                                };
                                await planningNameTranslation.Create(_dbContext);

                                i += 1;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw;
                }

                result.Message = _itemsPlanningLocalizationService.GetString("ImportCompletedSuccessfully");

                return(new OperationDataResult <ExcelParseResult>(
                           true,
                           result));
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                _logger.LogError(e, e.Message);
                return(new OperationDataResult <ExcelParseResult>(false,
                                                                  _itemsPlanningLocalizationService.GetString("ErrorWhileImportingExcelFile")));
            }
        }
예제 #4
0
        public async Task UploadedData_Update_DoesUpdate()
        {
            // Arrange
            var planning = new Planning();

            await planning.Create(DbContext);

            var commonTranslationModels = new List <PlanningNameTranslation>()
            {
                new PlanningNameTranslation()
                {
                    Name     = Guid.NewGuid().ToString(),
                    Language = new Language()
                    {
                        LanguageCode = "da", Name = "Danish"
                    },
                    Planning = planning
                }
            };

            foreach (var translationModel in commonTranslationModels)
            {
                await translationModel.Create(DbContext);
            }

            var planningCase = new PlanningCase
            {
                MicrotingSdkSiteId  = 24,
                MicrotingSdkCaseId  = 34,
                MicrotingSdkeFormId = 234,
                Status     = 66,
                PlanningId = planning.Id,
            };

            await planningCase.Create(DbContext);

            var uploadedData = new UploadedData
            {
                PlanningCaseId = planningCase.Id,
                Checksum       = Guid.NewGuid().ToString(),
                Extension      = Guid.NewGuid().ToString(),
                CurrentFile    = Guid.NewGuid().ToString(),
                UploaderType   = Guid.NewGuid().ToString(),
                FileLocation   = Guid.NewGuid().ToString(),
                FileName       = Guid.NewGuid().ToString()
            };
            await uploadedData.Create(DbContext);

            var newCheckSum     = Guid.NewGuid().ToString();
            var newExtension    = Guid.NewGuid().ToString();
            var newCurrentFile  = Guid.NewGuid().ToString();
            var newUploaderType = Guid.NewGuid().ToString();
            var newFileLocation = Guid.NewGuid().ToString();
            var newFileName     = Guid.NewGuid().ToString();

            uploadedData.Checksum     = newCheckSum;
            uploadedData.Extension    = newExtension;
            uploadedData.CurrentFile  = newCurrentFile;
            uploadedData.UploaderType = newUploaderType;
            uploadedData.FileLocation = newFileLocation;
            uploadedData.FileName     = newFileName;
            //Act
            await uploadedData.Update(DbContext);

            var dbUploadedData          = DbContext.UploadedDatas.AsNoTracking().First();
            var uploadedDataList        = DbContext.UploadedDatas.AsNoTracking().ToList();
            var uploadedDataVersionList = DbContext.UploadedDataVersions.AsNoTracking().ToList();

            //Assert
            Assert.NotNull(dbUploadedData);

            Assert.AreEqual(1, uploadedDataList.Count);
            Assert.AreEqual(2, uploadedDataVersionList.Count);

            Assert.AreEqual(newCheckSum, dbUploadedData.Checksum);
            Assert.AreEqual(newExtension, dbUploadedData.Extension);
            Assert.AreEqual(newCurrentFile, dbUploadedData.CurrentFile);
            Assert.AreEqual(newUploaderType, dbUploadedData.UploaderType);
            Assert.AreEqual(newFileLocation, dbUploadedData.FileLocation);
            Assert.AreEqual(newFileName, dbUploadedData.FileName);
            Assert.AreEqual(uploadedData.PlanningCaseId, dbUploadedData.PlanningCaseId);
        }
        public async Task <OperationResult> Create(PlanningCreateModel model)
        {
            //await using var transaction = await _dbContext.Database.BeginTransactionAsync();
            var sdkCore =
                await _coreService.GetCore();

            await using var sdkDbContext = sdkCore.DbContextHelper.GetDbContext();
            try
            {
                var tagIds = new List <int>();

                tagIds.AddRange(model.TagsIds);

                var localeString = await _userService.GetCurrentUserLocale();

                if (string.IsNullOrEmpty(localeString))
                {
                    return(new OperationResult(
                               false,
                               _itemsPlanningLocalizationService.GetString("LocaleDoesNotExist")));
                }
                var language = sdkDbContext.Languages.Single(x => x.LanguageCode == localeString);
                if (model.BoundEform == null)
                {
                    return(new OperationResult(
                               false,
                               _itemsPlanningLocalizationService.GetString("InfoAboutEformIsNull")));
                }
                var template = await _coreService.GetCore().Result.TemplateItemRead(model.BoundEform.RelatedEFormId, language);

                if (template == null)
                {
                    return(new OperationResult(
                               false,
                               _itemsPlanningLocalizationService.GetString("EformNotFound")));
                }
                if (model.Folder == null)
                {
                    return(new OperationResult(
                               false,
                               _itemsPlanningLocalizationService.GetString("InfoAboutFolderIsNull")));
                }
                var sdkFolder = await sdkDbContext.Folders
                                .Include(x => x.Parent)
                                .FirstOrDefaultAsync(x => x.Id == model.Folder.EFormSdkFolderId);

                if (sdkFolder == null)
                {
                    return(new OperationResult(
                               false,
                               _itemsPlanningLocalizationService.GetString("FolderNotFound")));
                }

                var planning = new Planning
                {
                    Description      = model.Description,
                    BuildYear        = model.BuildYear,
                    Type             = model.Type,
                    LocationCode     = model.LocationCode,
                    CreatedByUserId  = _userService.UserId,
                    CreatedAt        = DateTime.UtcNow,
                    IsLocked         = false,
                    IsEditable       = true,
                    IsHidden         = false,
                    RepeatEvery      = model.Reiteration.RepeatEvery,
                    RepeatUntil      = model.Reiteration.RepeatUntil,
                    RepeatType       = model.Reiteration.RepeatType,
                    DayOfWeek        = model.Reiteration.DayOfWeek,
                    DayOfMonth       = model.Reiteration.DayOfMonth,
                    Enabled          = true,
                    RelatedEFormId   = model.BoundEform.RelatedEFormId,
                    RelatedEFormName = template.Label,
                    SdkFolderName    = sdkFolder.Name,
                    SdkFolderId      = model.Folder.EFormSdkFolderId,
                    PlanningsTags    = new List <PlanningsTags>(),
                    DaysBeforeRedeploymentPushMessageRepeat = model.Reiteration.PushMessageEnabled,
                    DaysBeforeRedeploymentPushMessage       = model.Reiteration.DaysBeforeRedeploymentPushMessage,
                    PushMessageOnDeployment = model.Reiteration.PushMessageOnDeployment,
                    StartDate = model.Reiteration.StartDate ?? DateTime.UtcNow
                };


                foreach (var tagId in tagIds)
                {
                    planning.PlanningsTags.Add(
                        new PlanningsTags
                    {
                        CreatedByUserId = _userService.UserId,
                        UpdatedByUserId = _userService.UserId,
                        PlanningTagId   = tagId
                    });
                }

                await planning.Create(_dbContext);

                var languages = await _dbContext.Languages.ToListAsync();

                foreach (var translation in model.TranslationsName)
                {
                    var languageId = languages.Where(x => x.Name == translation.Language || x.LanguageCode == translation.LocaleName)
                                     .Select(x => x.Id)
                                     .FirstOrDefault();
                    if (languageId == default)
                    {
                        return(new OperationResult(
                                   true,
                                   _itemsPlanningLocalizationService.GetString("LocaleDoesNotExist")));
                    }

                    var planningNameTranslations = new PlanningNameTranslation()
                    {
                        LanguageId      = languageId,
                        PlanningId      = planning.Id,
                        Name            = translation.Name,
                        CreatedByUserId = _userService.UserId,
                        UpdatedByUserId = _userService.UserId
                    };
                    await planningNameTranslations.Create(_dbContext);
                }

                //await transaction.CommitAsync();
                return(new OperationResult(
                           true,
                           _itemsPlanningLocalizationService.GetString("ListCreatedSuccessfully")));
            }
            catch (Exception e)
            {
                //await transaction.RollbackAsync();
                Trace.TraceError(e.Message);
                return(new OperationResult(false,
                                           _itemsPlanningLocalizationService.GetString("ErrorWhileCreatingList")));
            }
        }