Merge pull request #383 from mifoscontributer/MIFOSX-429

Allow AssignStaff from command param and refactor method names
This commit is contained in:
Vishwas Babu A J
2013-06-21 08:11:27 -07:00
15 changed files with 149 additions and 89 deletions
@@ -0,0 +1 @@
INSERT INTO `m_permission` (`grouping`, `code`, `entity_name`, `action_name`, `can_maker_checker`) VALUES ('portfolio', 'ASSIGNSTAFF_CLIENT', 'CLIENT', 'ASSIGNSTAFF', 0);
@@ -537,16 +537,20 @@ public class CommandWrapper {
return this.actionName.equalsIgnoreCase("UNASSIGNSTAFF") && this.entityName.equalsIgnoreCase("CLIENT");
}
public boolean isAssignRole() {
public boolean isAssignGroupRole() {
return this.entityName.equalsIgnoreCase("GROUP") && this.actionName.equalsIgnoreCase("ASSIGNROLE");
}
public boolean isUnAssignRole() {
public boolean isUnAssignGroupRole() {
return this.entityName.equalsIgnoreCase("GROUP") && this.actionName.equalsIgnoreCase("UNASSIGNROLE");
}
public boolean isUpdateRole() {
public boolean isUpdateGroupRole() {
return this.entityName.equalsIgnoreCase("GROUP") && this.actionName.equalsIgnoreCase("UPDATEROLE");
}
public boolean isClientAssignStaff() {
return this.actionName.equalsIgnoreCase("ASSIGNSTAFF") && this.entityName.equalsIgnoreCase("CLIENT");
}
}
@@ -1062,4 +1062,13 @@ public class CommandWrapperBuilder {
this.href = "/clients/" + clientId + "?command=unassignStaff";
return this;
}
public CommandWrapperBuilder assignClientStaff(Long clientId) {
this.actionName = "ASSIGNSTAFF";
this.entityName = "CLIENT";
this.entityId = clientId;
this.clientId = clientId;
this.href = "/clients/" + clientId + "?command=assignStaff";
return this;
}
}
@@ -158,7 +158,9 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else if (wrapper.isClientActivation()) {
handler = this.applicationContext.getBean("activateClientCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isClientUnassignStaff()) {
handler = applicationContext.getBean("unassignClientStaffCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("unassignClientStaffCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isClientAssignStaff()) {
handler = this.applicationContext.getBean("assignClientStaffCommandHandler", NewCommandSourceHandler.class);
} else {
throw new UnsupportedCommandException(wrapper.commandName());
}
@@ -415,11 +417,11 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
handler = this.applicationContext.getBean("disassociateClientsFromGroupCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isSaveGroupCollectionSheet()) {
handler = this.applicationContext.getBean("saveGroupCollectionSheetCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isAssignRole()) {
} else if (wrapper.isAssignGroupRole()) {
handler = this.applicationContext.getBean("assignRoleCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUnAssignRole()) {
} else if (wrapper.isUnAssignGroupRole()) {
handler = this.applicationContext.getBean("unassignRoleCommandHandler", NewCommandSourceHandler.class);
} else if (wrapper.isUpdateRole()) {
} else if (wrapper.isUpdateGroupRole()) {
handler = this.applicationContext.getBean("updateGroupRoleCommandHandler", NewCommandSourceHandler.class);
} else {
throw new UnsupportedCommandException(wrapper.commandName());
@@ -473,7 +475,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
} else if (wrapper.isHolidayResource()) {
if (wrapper.isCreate()) {
handler = applicationContext.getBean("createHolidayCommandHandler", NewCommandSourceHandler.class);
handler = this.applicationContext.getBean("createHolidayCommandHandler", NewCommandSourceHandler.class);
}
} else {
throw new UnsupportedCommandException(wrapper.commandName());
@@ -1,32 +0,0 @@
package org.mifosplatform.infrastructure.core.exception;
/**
* A {@link RuntimeException} thrown when the authenticated user don't have
* enough permissions to access.
*/
public abstract class AbstractPlatformAccessDeniedException extends RuntimeException {
private final String globalisationMessageCode;
private final String defaultUserMessage;
private final Object[] defaultUserMessageArgs;
public AbstractPlatformAccessDeniedException(final String globalisationMessageCode, final String defaultUserMessage,
final Object... defaultUserMessageArgs) {
this.globalisationMessageCode = globalisationMessageCode;
this.defaultUserMessage = defaultUserMessage;
this.defaultUserMessageArgs = defaultUserMessageArgs;
}
public String getGlobalisationMessageCode() {
return this.globalisationMessageCode;
}
public String getDefaultUserMessage() {
return this.defaultUserMessage;
}
public Object[] getDefaultUserMessageArgs() {
return this.defaultUserMessageArgs;
}
}
@@ -1,11 +0,0 @@
package org.mifosplatform.infrastructure.security.exception;
import org.mifosplatform.infrastructure.core.exception.AbstractPlatformAccessDeniedException;
public class PermissionDeniedException extends AbstractPlatformAccessDeniedException {
public PermissionDeniedException(final String code, final String defaultMessage, final Long userId) {
super(code, defaultMessage, userId);
}
}
@@ -10,4 +10,6 @@ import org.mifosplatform.useradministration.domain.AppUser;
public interface PlatformSecurityContext {
AppUser authenticatedUser();
void validateAccessRights(String resourceOfficeHierarchy);
}
@@ -5,6 +5,7 @@
*/
package org.mifosplatform.infrastructure.security.service;
import org.mifosplatform.infrastructure.security.exception.NoAuthorizationException;
import org.mifosplatform.useradministration.domain.AppUser;
import org.mifosplatform.useradministration.exception.UnAuthenticatedUserException;
import org.springframework.security.core.Authentication;
@@ -22,9 +23,9 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo
@Override
public AppUser authenticatedUser() {
AppUser currentUser = null;
SecurityContext context = SecurityContextHolder.getContext();
final SecurityContext context = SecurityContextHolder.getContext();
if (context != null) {
Authentication auth = context.getAuthentication();
final Authentication auth = context.getAuthentication();
if (auth != null) {
currentUser = (AppUser) auth.getPrincipal();
}
@@ -34,4 +35,16 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo
return currentUser;
}
@Override
public void validateAccessRights(final String resourceOfficeHierarchy) {
final AppUser user = authenticatedUser();
final String userOfficeHierarchy = user.getOffice().getHierarchy();
if (!resourceOfficeHierarchy.startsWith(userOfficeHierarchy)) {
throw new NoAuthorizationException("The user doesn't have enough permissions to access the resource.");
}
}
}
@@ -197,6 +197,10 @@ public class ClientsApiResource {
if (is(commandParam, "activate")) {
final CommandWrapper commandRequest = builder.activateClient(clientId).build();
result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "assignStaff")) {
final CommandWrapper commandRequest = builder.assignClientStaff(clientId).build();
result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
} else if (is(commandParam, "unassignStaff")) {
final CommandWrapper commandRequest = builder.unassignClientStaff(clientId).build();
result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
@@ -204,7 +208,7 @@ public class ClientsApiResource {
}
if (result == null) {
throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "activate", "unassignStaff" });
throw new UnrecognizedQueryParamException("command", commandParam, new Object[] { "activate", "unassignStaff", "assignStaff" });
}
return this.toApiJsonSerializer.serialize(result);
@@ -350,4 +350,28 @@ public final class ClientDataValidator {
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
public void validateForAssignStaff(String json) {
if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); }
final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
final Set<String> supportedParametersUnassignStaff = new HashSet<String>(Arrays.asList(ClientApiConstants.staffIdParamName));
this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParametersUnassignStaff);
final JsonElement element = this.fromApiJsonHelper.parse(json);
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(ClientApiConstants.CLIENT_RESOURCE_NAME);
final String staffIdParameterName = ClientApiConstants.staffIdParamName;
final Long staffId = this.fromApiJsonHelper.extractLongNamed(staffIdParameterName, element);
baseDataValidator.reset().parameter(staffIdParameterName).value(staffId).notNull().longGreaterThanZero();
if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
}
}
@@ -443,4 +443,8 @@ public final class Client extends AbstractPersistable<Long> {
this.staff = null;
}
public void assignStaff(Staff staff) {
this.staff = staff;
}
}
@@ -0,0 +1,27 @@
package org.mifosplatform.portfolio.client.handler;
import org.mifosplatform.commands.handler.NewCommandSourceHandler;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.portfolio.client.service.ClientWritePlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AssignClientStaffCommandHandler implements NewCommandSourceHandler {
private final ClientWritePlatformService clientWritePlatformService;
@Autowired
public AssignClientStaffCommandHandler(final ClientWritePlatformService clientWritePlatformService) {
this.clientWritePlatformService = clientWritePlatformService;
}
@Transactional
@Override
public CommandProcessingResult processCommand(JsonCommand command) {
return this.clientWritePlatformService.assignClientStaff(command.entityId(), command);
}
}
@@ -20,4 +20,6 @@ public interface ClientWritePlatformService {
CommandProcessingResult unassignClientStaff(Long clientId, JsonCommand command);
CommandProcessingResult assignClientStaff(Long clientId, JsonCommand command);
}
@@ -17,7 +17,6 @@ import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.exception.PermissionDeniedException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.office.domain.Office;
import org.mifosplatform.organisation.office.domain.OfficeRepository;
@@ -37,7 +36,6 @@ import org.mifosplatform.portfolio.group.domain.GroupRepository;
import org.mifosplatform.portfolio.group.exception.GroupNotFoundException;
import org.mifosplatform.portfolio.note.domain.Note;
import org.mifosplatform.portfolio.note.domain.NoteRepository;
import org.mifosplatform.useradministration.domain.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -174,22 +172,14 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
public CommandProcessingResult updateClient(final Long clientId, final JsonCommand command) {
try {
AppUser user = context.authenticatedUser();
this.context.authenticatedUser();
this.fromApiJsonDeserializer.validateForUpdate(command.json());
final Client clientForUpdate = this.clientRepository.findOneWithNotFoundDetection(clientId);
final String clientHierarchy = clientForUpdate.getOffice().getHierarchy();
// Don't allow other office user to update
final Office loginUserOffice = user.getOffice();
final String userHierarchy = loginUserOffice.getHierarchy();
if (!clientHierarchy.startsWith(userHierarchy)) {
final String code = "error.msg.not.enough.permissions.to.access.resource";
final String defaultMessage = "The User with id " + user.getId() + " don't have permission to update this client";
throw new PermissionDeniedException(code, defaultMessage, user.getId());
}
this.context.validateAccessRights(clientHierarchy);
final Map<String, Object> changes = clientForUpdate.update(command);
@@ -284,4 +274,35 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP
.with(actualChanges) //
.build();
}
@Override
public CommandProcessingResult assignClientStaff(final Long clientId, final JsonCommand command) {
this.context.authenticatedUser();
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(5);
this.fromApiJsonDeserializer.validateForAssignStaff(command.json());
final Client clientForUpdate = this.clientRepository.findOneWithNotFoundDetection(clientId);
Staff staff = null;
final Long staffId = command.longValueOfParameterNamed(ClientApiConstants.staffIdParamName);
if (staffId != null) {
staff = this.staffRepository.findByOfficeWithNotFoundDetection(staffId, clientForUpdate.officeId());
clientForUpdate.assignStaff(staff);
}
this.clientRepository.saveAndFlush(clientForUpdate);
actualChanges.put(ClientApiConstants.staffIdParamName, staffId);
return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) //
.withOfficeId(clientForUpdate.officeId()) //
.withEntityId(clientForUpdate.getId()) //
.withClientId(clientId) //
.with(actualChanges) //
.build();
}
}
@@ -21,7 +21,6 @@ import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.security.exception.PermissionDeniedException;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.office.domain.Office;
import org.mifosplatform.organisation.office.domain.OfficeRepository;
@@ -46,7 +45,6 @@ import org.mifosplatform.portfolio.loanaccount.domain.Loan;
import org.mifosplatform.portfolio.loanaccount.domain.LoanRepository;
import org.mifosplatform.portfolio.note.domain.Note;
import org.mifosplatform.portfolio.note.domain.NoteRepository;
import org.mifosplatform.useradministration.domain.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -118,7 +116,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
final boolean active = command.booleanPrimitiveValueOfParameterNamed(GroupingTypesApiConstants.activeParamName);
final LocalDate activationDate = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName);
GroupLevel groupLevel = this.groupLevelRepository.findOne(groupingType.getId());
final GroupLevel groupLevel = this.groupLevelRepository.findOne(groupingType.getId());
final Group newGroup = Group.newGroup(groupOffice, staff, parentGroup, groupLevel, name, externalId, active, activationDate,
clientMembers, groupMembers);
@@ -188,7 +186,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
.withGroupId(groupId) //
.withEntityId(groupId) //
.build();
} catch (DataIntegrityViolationException dve) {
} catch (final DataIntegrityViolationException dve) {
handleGroupDataIntegrityIssues(command, dve, GroupTypes.GROUP);
return CommandProcessingResult.empty();
}
@@ -215,21 +213,13 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
private CommandProcessingResult updateGroupingType(final Long groupId, final JsonCommand command, final GroupTypes groupingType) {
try {
AppUser user = this.context.authenticatedUser();
this.context.authenticatedUser();
final Group groupForUpdate = this.groupRepository.findOneWithNotFoundDetection(groupId);
final Long officeId = groupForUpdate.officeId();
final Office groupOffice = groupForUpdate.getOffice();
final String groupHierarchy = groupOffice.getHierarchy();
//Don't allow other office user to update
final Office loginUserOffice = this.context.authenticatedUser().getOffice();
final String userHierarchy = loginUserOffice.getHierarchy();
if (!groupHierarchy.startsWith(userHierarchy)) {
final String code = "error.msg.not.enough.permissions.to.access.resource";
final String defaultMessage = "The User with id "+user.getId()+" don't have permission to update this "+ groupingType.getValue();
throw new PermissionDeniedException(code, defaultMessage, user.getId());
}
this.context.validateAccessRights(groupHierarchy);
final Map<String, Object> actualChanges = groupForUpdate.update(command);
@@ -243,7 +233,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
groupForUpdate.updateStaff(newStaff);
}
GroupLevel groupLevel = this.groupLevelRepository.findOne(groupForUpdate.getGroupLevel().getId());
final GroupLevel groupLevel = this.groupLevelRepository.findOne(groupForUpdate.getGroupLevel().getId());
/*
* Ignoring parentId param, if group for update is super parent.
@@ -464,9 +454,9 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
final Group groupForUpdate = this.groupRepository.findOneWithNotFoundDetection(groupId);
final Set<Client> clientMembers = assembleSetOfClients(groupForUpdate.officeId(), command);
Map<String, Object> actualChanges = new HashMap<String, Object>();
final Map<String, Object> actualChanges = new HashMap<String, Object>();
List<String> changes = groupForUpdate.associateClients(clientMembers);
final List<String> changes = groupForUpdate.associateClients(clientMembers);
if (!changes.isEmpty()) {
actualChanges.put(GroupingTypesApiConstants.clientMembersParamName, changes);
}
@@ -492,9 +482,9 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
// check if any client has got group loans
validateForJLGLoan(groupForUpdate.getId(), clientMembers);
Map<String, Object> actualChanges = new HashMap<String, Object>();
final Map<String, Object> actualChanges = new HashMap<String, Object>();
List<String> changes = groupForUpdate.disassociateClients(clientMembers);
final List<String> changes = groupForUpdate.disassociateClients(clientMembers);
if (!changes.isEmpty()) {
actualChanges.put(GroupingTypesApiConstants.clientMembersParamName, changes);
}
@@ -512,8 +502,8 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group
@Transactional
private void validateForJLGLoan(final Long groupId, final Set<Client> clientMembers) {
for (Client client : clientMembers) {
Collection<Loan> loans = this.loanRepository.findByClientIdAndGroupId(client.getId(), groupId);
for (final Client client : clientMembers) {
final Collection<Loan> loans = this.loanRepository.findByClientIdAndGroupId(client.getId(), groupId);
if (!CollectionUtils.isEmpty(loans)) {
final String defaultUserMessage = "Client with identifier " + client.getId()
+ " cannot be disassociated it has group loans.";