Search in sources :

Example 1 with Module

use of org.motechproject.mots.domain.Module in project mots by motech-implementations.

the class ModuleMapper method updateModuleFromDto.

/**
 * Update Module using data from DTO.
 * @param moduleDto DTO with new data
 * @param module Module to be updated
 */
private void updateModuleFromDto(ModuleDto moduleDto, Module module) {
    List<UnitDto> unitDtos = moduleDto.getChildren();
    List<Unit> units = module.getUnits();
    List<Unit> updatedUnits = new ArrayList<>();
    if (units == null) {
        units = new ArrayList<>();
    }
    if (unitDtos != null && !unitDtos.isEmpty()) {
        for (int i = 0; i < unitDtos.size(); i++) {
            UnitDto unitDto = unitDtos.get(i);
            Unit unit;
            if (StringUtils.isBlank(unitDto.getId())) {
                unit = new Unit();
            } else {
                unit = units.stream().filter(u -> u.getId().toString().equals(unitDto.getId())).findAny().orElseThrow(() -> new EntityNotFoundException("Cannot update module, because error occurred during unit list update"));
            }
            updateUnitFromDto(unitDto, unit);
            unit.setAllowReplay(BooleanUtils.isTrue(unit.getAllowReplay()));
            unit.setListOrder(i);
            updatedUnits.add(unit);
        }
    }
    updateFromDto(moduleDto, module);
    module.setUnits(updatedUnits);
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Mappings(org.mapstruct.Mappings) Mapping(org.mapstruct.Mapping) ChoiceDto(org.motechproject.mots.dto.ChoiceDto) CourseModule(org.motechproject.mots.domain.CourseModule) CallFlowElementType(org.motechproject.mots.domain.enums.CallFlowElementType) ArrayList(java.util.ArrayList) UnitDto(org.motechproject.mots.dto.UnitDto) BooleanUtils(org.apache.commons.lang.BooleanUtils) MessageDto(org.motechproject.mots.dto.MessageDto) MappingTarget(org.mapstruct.MappingTarget) Mapper(org.mapstruct.Mapper) MultipleChoiceQuestion(org.motechproject.mots.domain.MultipleChoiceQuestion) Module(org.motechproject.mots.domain.Module) EntityNotFoundException(org.motechproject.mots.exception.EntityNotFoundException) Mappers(org.mapstruct.factory.Mappers) MultipleChoiceQuestionDto(org.motechproject.mots.dto.MultipleChoiceQuestionDto) Choice(org.motechproject.mots.domain.Choice) Course(org.motechproject.mots.domain.Course) CallFlowElement(org.motechproject.mots.domain.CallFlowElement) ReportingPolicy(org.mapstruct.ReportingPolicy) ModuleDto(org.motechproject.mots.dto.ModuleDto) List(java.util.List) Message(org.motechproject.mots.domain.Message) Unit(org.motechproject.mots.domain.Unit) ModuleSimpleDto(org.motechproject.mots.dto.ModuleSimpleDto) Status(org.motechproject.mots.domain.enums.Status) CourseDto(org.motechproject.mots.dto.CourseDto) CallFlowElementDto(org.motechproject.mots.dto.CallFlowElementDto) ArrayList(java.util.ArrayList) EntityNotFoundException(org.motechproject.mots.exception.EntityNotFoundException) Unit(org.motechproject.mots.domain.Unit) UnitDto(org.motechproject.mots.dto.UnitDto)

Example 2 with Module

use of org.motechproject.mots.domain.Module in project mots by motech-implementations.

the class ModuleAssignmentServiceTest method shouldAssignModulesToDistrict.

@Test
public void shouldAssignModulesToDistrict() throws Exception {
    when(userService.getUserByUserName(eq(user.getUsername()))).thenReturn(user);
    when(communityHealthWorkerRepository.findByCommunityFacilityChiefdomDistrictIdAndSelected(any(), any())).thenReturn(Collections.singletonList(CHW));
    moduleAssignmentService.assignModulesToDistrict(districtAssignmentDto);
    ArgumentCaptor<DistrictAssignmentLog> districtAssignmentLogCaptor = ArgumentCaptor.forClass(DistrictAssignmentLog.class);
    verify(districtAssignmentLogRepository, times(2)).save(districtAssignmentLogCaptor.capture());
    List<DistrictAssignmentLog> districtAssignmentLogs = districtAssignmentLogCaptor.getAllValues();
    final Set<Module> passedModules = new HashSet<>(Arrays.asList(MODULE_2, MODULE_3));
    assertTrue(districtAssignmentLogs.stream().allMatch(l -> passedModules.contains(l.getModule())));
    for (DistrictAssignmentLog log : districtAssignmentLogs) {
        assertEquals(DISTRICT, log.getDistrict());
        assertEquals(districtAssignmentDto.getStartDate(), log.getStartDate().toString());
        assertEquals(districtAssignmentDto.getEndDate(), log.getEndDate().toString());
        assertEquals(user, log.getOwner());
    }
    ArgumentCaptor<AssignedModules> assignedModulesCaptor = ArgumentCaptor.forClass(AssignedModules.class);
    verify(assignedModulesRepository).save(assignedModulesCaptor.capture());
    final Set<Module> allModules = new HashSet<>(Arrays.asList(MODULE_1, MODULE_2, MODULE_3));
    assertEquals(allModules, assignedModulesCaptor.getValue().getModules());
    verify(ivrService).addSubscriberToGroups(eq(CHW.getIvrId()), eq(Collections.singletonList(IVR_GROUP)));
    verify(moduleProgressService).createModuleProgresses(any(), eq(Collections.singleton(MODULE_3)));
}
Also used : Arrays(java.util.Arrays) DistrictAssignmentLogRepository(org.motechproject.mots.repository.DistrictAssignmentLogRepository) ModuleProgress(org.motechproject.mots.domain.ModuleProgress) CommunityHealthWorkerRepository(org.motechproject.mots.repository.CommunityHealthWorkerRepository) Mockito.doThrow(org.mockito.Mockito.doThrow) ModuleAssignmentException(org.motechproject.mots.exception.ModuleAssignmentException) AssignedModules(org.motechproject.mots.domain.AssignedModules) Matchers.eq(org.mockito.Matchers.eq) DistrictAssignmentLog(org.motechproject.mots.domain.DistrictAssignmentLog) DistrictAssignmentDtoDataBuilder(org.motechproject.mots.testbuilder.DistrictAssignmentDtoDataBuilder) EntityNotFoundException(org.motechproject.mots.exception.EntityNotFoundException) DistrictAssignmentDto(org.motechproject.mots.dto.DistrictAssignmentDto) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) AssignedModulesDataBuilder(org.motechproject.mots.testbuilder.AssignedModulesDataBuilder) MotsException(org.motechproject.mots.exception.MotsException) Set(java.util.Set) UUID(java.util.UUID) Matchers.any(org.mockito.Matchers.any) List(java.util.List) District(org.motechproject.mots.domain.District) Optional(java.util.Optional) User(org.motechproject.mots.domain.security.User) ModuleDataBuilder(org.motechproject.mots.testbuilder.ModuleDataBuilder) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) ProgressStatus(org.motechproject.mots.domain.enums.ProgressStatus) CommunityHealthWorkerDataBuilder(org.motechproject.mots.testbuilder.CommunityHealthWorkerDataBuilder) CommunityHealthWorker(org.motechproject.mots.domain.CommunityHealthWorker) HashSet(java.util.HashSet) IvrException(org.motechproject.mots.exception.IvrException) ArgumentCaptor(org.mockito.ArgumentCaptor) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Module(org.motechproject.mots.domain.Module) ModuleProgressDataBuilder(org.motechproject.mots.testbuilder.ModuleProgressDataBuilder) PowerMockRunner(org.powermock.modules.junit4.PowerMockRunner) Before(org.junit.Before) InjectMocks(org.mockito.InjectMocks) ModuleRepository(org.motechproject.mots.repository.ModuleRepository) DistrictDataBuilder(org.motechproject.mots.testbuilder.DistrictDataBuilder) Assert.assertTrue(org.junit.Assert.assertTrue) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) EntityManager(javax.persistence.EntityManager) Mockito.verify(org.mockito.Mockito.verify) AssignedModulesRepository(org.motechproject.mots.repository.AssignedModulesRepository) Collections(java.util.Collections) DistrictRepository(org.motechproject.mots.repository.DistrictRepository) Assert.assertEquals(org.junit.Assert.assertEquals) TestUtils(org.motechproject.mots.utils.TestUtils) AssignedModules(org.motechproject.mots.domain.AssignedModules) DistrictAssignmentLog(org.motechproject.mots.domain.DistrictAssignmentLog) Module(org.motechproject.mots.domain.Module) HashSet(java.util.HashSet) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with Module

use of org.motechproject.mots.domain.Module in project mots by motech-implementations.

the class ModuleAssignmentService method assignModules.

/**
 * Assign modules to CHW.
 * @param assignedModules modules assigned for CHW
 */
@SuppressWarnings("checkstyle:variabledeclarationusagedistance")
@Transactional
@PreAuthorize(RoleNames.HAS_ASSIGN_MODULES_ROLE)
public void assignModules(AssignedModules assignedModules) {
    AssignedModules existingAssignedModules = getAssignedModules(assignedModules.getHealthWorker().getId());
    CommunityHealthWorker assignedModulesChw = existingAssignedModules.getHealthWorker();
    Set<Module> oldModules = new HashSet<>(existingAssignedModules.getModules());
    existingAssignedModules.setModules(assignedModules.getModules());
    repository.save(existingAssignedModules);
    entityManager.flush();
    entityManager.refresh(existingAssignedModules);
    Set<Module> newModules = new HashSet<>(existingAssignedModules.getModules());
    Set<Module> modulesToAdd = getModulesToAdd(oldModules, newModules);
    Set<Module> modulesToRemove = getModulesToRemove(oldModules, newModules);
    validateModulesToUnassign(assignedModulesChw, modulesToRemove);
    String ivrId = assignedModulesChw.getIvrId();
    if (ivrId == null) {
        throw new ModuleAssignmentException("Could not assign module to CHW, because CHW has empty IVR id");
    }
    try {
        ivrService.addSubscriberToGroups(ivrId, getIvrGroupsFromModules(modulesToAdd));
        ivrService.removeSubscriberFromGroups(ivrId, getIvrGroupsFromModules(modulesToRemove));
    } catch (IvrException ex) {
        String message = "Could not assign or delete module for CHW, " + "because of IVR module assignment error.\n\n" + ex.getClearVotoInfo();
        throw new ModuleAssignmentException(message, ex);
    }
    moduleProgressService.removeModuleProgresses(assignedModulesChw, modulesToRemove);
    moduleProgressService.createModuleProgresses(assignedModulesChw, modulesToAdd);
}
Also used : AssignedModules(org.motechproject.mots.domain.AssignedModules) IvrException(org.motechproject.mots.exception.IvrException) ModuleAssignmentException(org.motechproject.mots.exception.ModuleAssignmentException) CommunityHealthWorker(org.motechproject.mots.domain.CommunityHealthWorker) CourseModule(org.motechproject.mots.domain.CourseModule) Module(org.motechproject.mots.domain.Module) HashSet(java.util.HashSet) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with Module

use of org.motechproject.mots.domain.Module in project mots by motech-implementations.

the class ModuleAssignmentService method assignModulesToDistrict.

/**
 * Creates DistrictAssignmentLog for district assignment,
 * and assigns modules to each CHW from a district.
 * @param assignmentDto dto with district id, list of modules assigned to it
 *     and start and end dates
 */
@Transactional
@PreAuthorize(RoleNames.HAS_ASSIGN_MODULES_ROLE)
public void assignModulesToDistrict(DistrictAssignmentDto assignmentDto) {
    List<CommunityHealthWorker> communityHealthWorkers = communityHealthWorkerRepository.findByCommunityFacilityChiefdomDistrictIdAndSelected(UUID.fromString(assignmentDto.getDistrictId()), true);
    Set<Module> newChwModules = new HashSet<>();
    String userName = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User currentUser = userService.getUserByUserName(userName);
    for (String moduleId : assignmentDto.getModules()) {
        Module moduleToAssign = moduleRepository.findById(UUID.fromString(moduleId)).orElseThrow(() -> new EntityNotFoundException("No module found for Id: {0}", moduleId));
        newChwModules.add(moduleToAssign);
        assignmentLogRepository.save(new DistrictAssignmentLog(districtRepository.findOne(UUID.fromString(assignmentDto.getDistrictId())), LocalDate.parse(assignmentDto.getStartDate()), LocalDate.parse(assignmentDto.getEndDate()), moduleToAssign, currentUser));
    }
    for (CommunityHealthWorker chw : communityHealthWorkers) {
        AssignedModules existingAssignedModules = getAssignedModules(chw.getId());
        Set<Module> oldModules = existingAssignedModules.getModules();
        Set<Module> modulesToAdd = getModulesToAdd(oldModules, newChwModules);
        existingAssignedModules.getModules().addAll(modulesToAdd);
        repository.save(existingAssignedModules);
        entityManager.flush();
        entityManager.refresh(existingAssignedModules);
        String ivrId = existingAssignedModules.getHealthWorker().getIvrId();
        if (ivrId == null) {
            throw new ModuleAssignmentException("Could not assign module to CHW, because CHW has empty IVR id");
        }
        try {
            ivrService.addSubscriberToGroups(ivrId, getIvrGroupsFromModules(modulesToAdd));
        } catch (IvrException ex) {
            String message = "Could not assign or delete module for CHW, " + "because of IVR module assignment error.\n\n" + ex.getClearVotoInfo();
            throw new ModuleAssignmentException(message, ex);
        }
        moduleProgressService.createModuleProgresses(chw, modulesToAdd);
    }
}
Also used : AssignedModules(org.motechproject.mots.domain.AssignedModules) IvrException(org.motechproject.mots.exception.IvrException) User(org.motechproject.mots.domain.security.User) ModuleAssignmentException(org.motechproject.mots.exception.ModuleAssignmentException) CommunityHealthWorker(org.motechproject.mots.domain.CommunityHealthWorker) EntityNotFoundException(org.motechproject.mots.exception.EntityNotFoundException) CourseModule(org.motechproject.mots.domain.CourseModule) Module(org.motechproject.mots.domain.Module) DistrictAssignmentLog(org.motechproject.mots.domain.DistrictAssignmentLog) HashSet(java.util.HashSet) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with Module

use of org.motechproject.mots.domain.Module in project mots by motech-implementations.

the class ModuleService method updateModule.

/**
 * Update existing Module.
 * @param id id of Module to be updated
 * @param moduleDto Module DTO
 * @return updated Module
 */
@PreAuthorize(RoleNames.HAS_MANAGE_MODULES_ROLE)
public ModuleDto updateModule(UUID id, ModuleDto moduleDto) {
    Course course = getDraftCourse();
    CourseModule courseModule = course.findCourseModuleByModuleId(id);
    Module module = courseModule.getModule();
    if (!Status.DRAFT.equals(module.getStatus())) {
        throw new MotsException("Only Module draft can be updated");
    }
    moduleMapper.updateCourseModuleFromDto(moduleDto, courseModule);
    courseModule = courseModuleRepository.save(courseModule);
    return moduleMapper.toDto(courseModule);
}
Also used : CourseModule(org.motechproject.mots.domain.CourseModule) Course(org.motechproject.mots.domain.Course) CourseModule(org.motechproject.mots.domain.CourseModule) Module(org.motechproject.mots.domain.Module) MotsException(org.motechproject.mots.exception.MotsException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Aggregations

Module (org.motechproject.mots.domain.Module)10 CourseModule (org.motechproject.mots.domain.CourseModule)7 Course (org.motechproject.mots.domain.Course)5 EntityNotFoundException (org.motechproject.mots.exception.EntityNotFoundException)5 List (java.util.List)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 BooleanUtils (org.apache.commons.lang.BooleanUtils)3 StringUtils (org.apache.commons.lang.StringUtils)3 Mapper (org.mapstruct.Mapper)3 Mapping (org.mapstruct.Mapping)3 MappingTarget (org.mapstruct.MappingTarget)3 Mappings (org.mapstruct.Mappings)3 ReportingPolicy (org.mapstruct.ReportingPolicy)3 Mappers (org.mapstruct.factory.Mappers)3 AssignedModules (org.motechproject.mots.domain.AssignedModules)3 CallFlowElement (org.motechproject.mots.domain.CallFlowElement)3 Choice (org.motechproject.mots.domain.Choice)3 CommunityHealthWorker (org.motechproject.mots.domain.CommunityHealthWorker)3