diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/CrpProgramLeaderDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/CrpProgramLeaderDAO.java index faea091082..4bbabb0c73 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/CrpProgramLeaderDAO.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/CrpProgramLeaderDAO.java @@ -55,6 +55,8 @@ public interface CrpProgramLeaderDAO { public List findAll(); + public CrpProgramLeader getCrpProgramLeaderByProgram(long crpProgramID, long globalUnitID, long userID); + /** * This method saves the information of the given crpProgramLeader * diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/InstitutionTypeDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/InstitutionTypeDAO.java index c9c4e2fe1f..a383a62326 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/InstitutionTypeDAO.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/InstitutionTypeDAO.java @@ -54,6 +54,12 @@ public interface InstitutionTypeDAO { */ public List findAll(); + /** + * This method gets a list of institutionType that are IATI + * + * @return a list from InstitutionType; null if no exist records + */ + public List findAllIATITypes(); /** * This method saves the information of the given institutionType diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/ProjectCenterOutcomeDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/ProjectCenterOutcomeDAO.java index fc7496d3e9..4d22998f58 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/ProjectCenterOutcomeDAO.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/ProjectCenterOutcomeDAO.java @@ -54,6 +54,15 @@ public interface ProjectCenterOutcomeDAO { */ public List findAll(); + /** + * This method gets a list of projectCenterOutcome that are active + * + * @param PhaseID - phase identification + * @param ProjectID - project identification + * @param projectCenterOutcome identification. + * @return a list from ProjectCenterOutcome null if no exist records + */ + public List getProjectCenterOutcomeByPhase(Long phaseID, Long projectID, Long centerOutcomeID); /** * This method saves the information of the given projectCenterOutcome diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/RestApiAuditlogDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/RestApiAuditlogDAO.java new file mode 100644 index 0000000000..521ab94ec9 --- /dev/null +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/RestApiAuditlogDAO.java @@ -0,0 +1,12 @@ +package org.cgiar.ccafs.marlo.data.dao; + +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; + +/** + * + * @author tonyshikali + */ +public interface RestApiAuditlogDAO { + + public void logThis(RestApiAuditlog restApiAuditLog); +} diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/CrpProgramLeaderMySQLDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/CrpProgramLeaderMySQLDAO.java index dec511e03e..2e7833ba1f 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/CrpProgramLeaderMySQLDAO.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/CrpProgramLeaderMySQLDAO.java @@ -19,10 +19,13 @@ import org.cgiar.ccafs.marlo.data.dao.CrpProgramLeaderDAO; import org.cgiar.ccafs.marlo.data.model.CrpProgramLeader; +import java.util.ArrayList; import java.util.List; +import java.util.Map; -import javax.inject.Named; import javax.inject.Inject; +import javax.inject.Named; + import org.hibernate.SessionFactory; @Named @@ -68,6 +71,28 @@ public List findAll() { } + @Override + public CrpProgramLeader getCrpProgramLeaderByProgram(long crpProgramID, long globalUnitID, long userID) { + String query = "Select crp_program_leaders.id from crp_program_leaders " + + "INNER JOIN crp_programs ON crp_programs.id=crp_program_leaders.crp_program_id " + + "WHERE crp_program_leaders.is_active=1 and crp_program_leaders.crp_program_id=" + crpProgramID + " " + + "AND crp_programs.global_unit_id=" + globalUnitID + " " + "AND crp_program_leaders.user_id=" + userID; + List> rList = super.findCustomQuery(query.toString()); + List crpProgramLeaders = new ArrayList(); + if (rList != null) { + for (Map map : rList) { + CrpProgramLeader crpProgramLeader = this.find(Long.parseLong(map.get("id").toString())); + crpProgramLeaders.add(crpProgramLeader); + } + } + if (crpProgramLeaders.size() > 0) { + return crpProgramLeaders.get(0); + } else { + return null; + } + + } + @Override public CrpProgramLeader save(CrpProgramLeader crpProgramLeader) { if (crpProgramLeader.getId() == null) { diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/InstitutionTypeMySQLDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/InstitutionTypeMySQLDAO.java index 8bdecd242d..db675c33f9 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/InstitutionTypeMySQLDAO.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/InstitutionTypeMySQLDAO.java @@ -21,8 +21,9 @@ import java.util.List; -import javax.inject.Named; import javax.inject.Inject; +import javax.inject.Named; + import org.hibernate.SessionFactory; @Named @@ -68,6 +69,17 @@ public List findAll() { } + @Override + public List findAllIATITypes() { + String query = "from " + InstitutionType.class.getName() + " where is_legacy = 0"; + List list = super.findAll(query); + if (list.size() > 0) { + return list; + } + + return null; + } + @Override public InstitutionType save(InstitutionType institutionType) { if (institutionType.getId() == null) { diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/ProjectCenterOutcomeMySQLDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/ProjectCenterOutcomeMySQLDAO.java index b9c91d70b3..8952573346 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/ProjectCenterOutcomeMySQLDAO.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/ProjectCenterOutcomeMySQLDAO.java @@ -19,7 +19,9 @@ import org.cgiar.ccafs.marlo.data.dao.ProjectCenterOutcomeDAO; import org.cgiar.ccafs.marlo.data.model.ProjectCenterOutcome; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import javax.inject.Inject; import javax.inject.Named; @@ -27,7 +29,8 @@ import org.hibernate.SessionFactory; @Named -public class ProjectCenterOutcomeMySQLDAO extends AbstractMarloDAO implements ProjectCenterOutcomeDAO { +public class ProjectCenterOutcomeMySQLDAO extends AbstractMarloDAO + implements ProjectCenterOutcomeDAO { @Inject @@ -69,6 +72,28 @@ public List findAll() { } + @Override + public List getProjectCenterOutcomeByPhase(Long phaseID, Long projectID, Long centerOutcome) { + StringBuilder query = new StringBuilder(); + query.append("SELECT project_center_outcomes.id as projectCenterOutcomeId FROM project_center_outcomes "); + query.append("INNER JOIN phases ON project_center_outcomes.id_phase = phases.id "); + query.append("WHERE project_id = "); + query.append(projectID); + query.append(" AND center_outcome_id = "); + query.append(centerOutcome); + query.append(" AND phases.id = "); + query.append(phaseID); + List> list = super.findCustomQuery(query.toString()); + List ProjectCenterOutcomes = new ArrayList(); + for (Map map : list) { + String projectCenterOutcomeId = map.get("projectCenterOutcomeId").toString(); + long longProjectCenterOutcomeId = Long.parseLong(projectCenterOutcomeId); + ProjectCenterOutcome projectCenterOutcome = this.find(longProjectCenterOutcomeId); + ProjectCenterOutcomes.add(projectCenterOutcome); + } + return ProjectCenterOutcomes; + } + @Override public ProjectCenterOutcome save(ProjectCenterOutcome projectCenterOutcome) { if (projectCenterOutcome.getId() == null) { diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/RestApiAuditlogMySQLDAO.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/RestApiAuditlogMySQLDAO.java new file mode 100644 index 0000000000..52ee8e651d --- /dev/null +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/RestApiAuditlogMySQLDAO.java @@ -0,0 +1,27 @@ +package org.cgiar.ccafs.marlo.data.dao.mysql; + +import javax.inject.Inject; +import javax.inject.Named; +import org.cgiar.ccafs.marlo.data.dao.RestApiAuditlogDAO; +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; +import org.hibernate.SessionFactory; + +/** + * + * @author tonyshikali + */ +@Named +public class RestApiAuditlogMySQLDAO extends AbstractMarloDAO implements RestApiAuditlogDAO{ + + @Inject + public RestApiAuditlogMySQLDAO(SessionFactory sessionFactory) { + super(sessionFactory); + } + + @Override + public void logThis(RestApiAuditlog restApiAuditLog) { + super.saveEntity(restApiAuditLog); + } + + +} diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/CrpProgramLeaderManager.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/CrpProgramLeaderManager.java index 52423ad413..a591b6f437 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/CrpProgramLeaderManager.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/CrpProgramLeaderManager.java @@ -60,6 +60,8 @@ public interface CrpProgramLeaderManager { */ public CrpProgramLeader getCrpProgramLeaderById(long crpProgramLeaderID); + public CrpProgramLeader getCrpProgramLeaderByProgram(long crpProgramID, long globalUnitID, long userID); + /** * This method saves the information of the given crpProgramLeader * diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/InstitutionTypeManager.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/InstitutionTypeManager.java index da65cc15e5..20f68f26ec 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/InstitutionTypeManager.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/InstitutionTypeManager.java @@ -51,6 +51,12 @@ public interface InstitutionTypeManager { */ public List findAll(); + /** + * This method gets a list of institutionType that are IATI + * + * @return a list from InstitutionType; null if no exist records + */ + public List findAllIATITypes(); /** * This method gets a institutionType object by a given institutionType identifier. diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/ProjectCenterOutcomeManager.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/ProjectCenterOutcomeManager.java index 696ca27e0a..3fec79e8a0 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/ProjectCenterOutcomeManager.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/ProjectCenterOutcomeManager.java @@ -60,6 +60,16 @@ public interface ProjectCenterOutcomeManager { */ public ProjectCenterOutcome getProjectCenterOutcomeById(long projectCenterOutcomeID); + /** + * This method gets a list of projectCenterOutcome information by + * + * @param PhaseID - phase identification + * @param ProjectID - project identification + * @param projectCenterOutcome identification. + * @return list of ProjectCenterOutcome object references. + */ + public List getProjectCenterOutcomeByPhase(Long phaseID, Long ProjectID, Long centerOutcomeID); + /** * This method saves the information of the given projectCenterOutcome * @@ -69,6 +79,4 @@ public interface ProjectCenterOutcomeManager { * or -1 is some error occurred. */ public ProjectCenterOutcome saveProjectCenterOutcome(ProjectCenterOutcome projectCenterOutcome); - - } diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/RestApiAuditlogManager.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/RestApiAuditlogManager.java new file mode 100644 index 0000000000..8a390f116c --- /dev/null +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/RestApiAuditlogManager.java @@ -0,0 +1,13 @@ +package org.cgiar.ccafs.marlo.data.manager; + +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; + +/** + * + * @author tonyshikali + */ +public interface RestApiAuditlogManager { + + public void logApiCall(RestApiAuditlog restApiAuditlog); + +} diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/CrpProgramLeaderManagerImpl.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/CrpProgramLeaderManagerImpl.java index f5c00912fb..206980079d 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/CrpProgramLeaderManagerImpl.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/CrpProgramLeaderManagerImpl.java @@ -1,6 +1,6 @@ /***************************************************************** - * This file is part of Managing Agricultural Research for Learning & - * Outcomes Platform (MARLO). + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). * MARLO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or @@ -21,8 +21,8 @@ import java.util.List; -import javax.inject.Named; import javax.inject.Inject; +import javax.inject.Named; /** * @author Christian Garcia @@ -67,6 +67,12 @@ public CrpProgramLeader getCrpProgramLeaderById(long crpProgramLeaderID) { return crpProgramLeaderDAO.find(crpProgramLeaderID); } + @Override + public CrpProgramLeader getCrpProgramLeaderByProgram(long crpProgramID, long globalUnitID, long userID) { + + return crpProgramLeaderDAO.getCrpProgramLeaderByProgram(crpProgramID, globalUnitID, userID); + } + @Override public CrpProgramLeader saveCrpProgramLeader(CrpProgramLeader crpProgramLeader) { diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/InstitutionTypeManagerImpl.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/InstitutionTypeManagerImpl.java index 5ae110d3d4..740e99d044 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/InstitutionTypeManagerImpl.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/InstitutionTypeManagerImpl.java @@ -38,39 +38,36 @@ public class InstitutionTypeManagerImpl implements InstitutionTypeManager { @Inject public InstitutionTypeManagerImpl(InstitutionTypeDAO institutionTypeDAO) { this.institutionTypeDAO = institutionTypeDAO; - - } @Override public void deleteInstitutionType(long institutionTypeId) { - institutionTypeDAO.deleteInstitutionType(institutionTypeId); } @Override public boolean existInstitutionType(long institutionTypeID) { - return institutionTypeDAO.existInstitutionType(institutionTypeID); } @Override public List findAll() { - return institutionTypeDAO.findAll(); + } + @Override + public List findAllIATITypes() { + return this.institutionTypeDAO.findAllIATITypes(); } @Override public InstitutionType getInstitutionTypeById(long institutionTypeID) { - return institutionTypeDAO.find(institutionTypeID); } @Override public InstitutionType saveInstitutionType(InstitutionType institutionType) { - return institutionTypeDAO.save(institutionType); } -} +} \ No newline at end of file diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ProjectCenterOutcomeManagerImpl.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ProjectCenterOutcomeManagerImpl.java index d6e970b633..782ae97964 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ProjectCenterOutcomeManagerImpl.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/ProjectCenterOutcomeManagerImpl.java @@ -15,11 +15,15 @@ package org.cgiar.ccafs.marlo.data.manager.impl; +import org.cgiar.ccafs.marlo.config.APConstants; +import org.cgiar.ccafs.marlo.data.dao.PhaseDAO; import org.cgiar.ccafs.marlo.data.dao.ProjectCenterOutcomeDAO; import org.cgiar.ccafs.marlo.data.manager.ProjectCenterOutcomeManager; +import org.cgiar.ccafs.marlo.data.model.Phase; import org.cgiar.ccafs.marlo.data.model.ProjectCenterOutcome; import java.util.List; +import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Named; @@ -32,20 +36,46 @@ public class ProjectCenterOutcomeManagerImpl implements ProjectCenterOutcomeMana private ProjectCenterOutcomeDAO projectCenterOutcomeDAO; + private PhaseDAO phaseDAO; // Managers @Inject - public ProjectCenterOutcomeManagerImpl(ProjectCenterOutcomeDAO projectCenterOutcomeDAO) { + public ProjectCenterOutcomeManagerImpl(ProjectCenterOutcomeDAO projectCenterOutcomeDAO, PhaseDAO phaseDAO) { this.projectCenterOutcomeDAO = projectCenterOutcomeDAO; - + this.phaseDAO = phaseDAO; } @Override public void deleteProjectCenterOutcome(long projectCenterOutcomeId) { + ProjectCenterOutcome projectCenterOutcome = this.getProjectCenterOutcomeById(projectCenterOutcomeId); + Phase currentPhase = phaseDAO.find(projectCenterOutcome.getPhase().getId()); + if (currentPhase.getDescription().equals(APConstants.PLANNING)) { + if (projectCenterOutcome.getPhase().getNext() != null) { + this.deleteProjectCenterOutcomePhase(currentPhase, projectCenterOutcomeId, projectCenterOutcome); + } + } + // projectCenterOutcomeDAO.deleteProjectCenterOutcome(projectCenterOutcomeId); + } - projectCenterOutcomeDAO.deleteProjectCenterOutcome(projectCenterOutcomeId); + public void deleteProjectCenterOutcomePhase(Phase next, long projectCenterOutcomeID, + ProjectCenterOutcome projectCenterOutcome) { + Phase phase = phaseDAO.find(next.getId()); + List projectCenterOutcomeList = projectCenterOutcomeDAO.getProjectCenterOutcomeByPhase( + next.getId(), projectCenterOutcome.getProject().getId(), projectCenterOutcome.getCenterOutcome().getId()); + projectCenterOutcomeList = + projectCenterOutcomeList.stream() + .filter(c -> c.isActive() + && c.getProject().getId().longValue() == projectCenterOutcome.getProject().getId().longValue() + && c.getCenterOutcome().getId().longValue() == projectCenterOutcome.getCenterOutcome().getId().longValue()) + .collect(Collectors.toList()); + for (ProjectCenterOutcome projectCenterOutcomeDB : projectCenterOutcomeList) { + projectCenterOutcomeDAO.deleteProjectCenterOutcome(projectCenterOutcomeDB.getId()); + } + if (phase.getNext() != null) { + this.deleteProjectCenterOutcomePhase(next.getNext(), projectCenterOutcomeID, projectCenterOutcome); + } } @Override @@ -68,9 +98,45 @@ public ProjectCenterOutcome getProjectCenterOutcomeById(long projectCenterOutcom } @Override - public ProjectCenterOutcome saveProjectCenterOutcome(ProjectCenterOutcome projectCenterOutcome) { + public List getProjectCenterOutcomeByPhase(Long phaseID, Long ProjectID, Long centerOutcomeID) { + return projectCenterOutcomeDAO.getProjectCenterOutcomeByPhase(phaseID, ProjectID, centerOutcomeID); + } - return projectCenterOutcomeDAO.save(projectCenterOutcome); + public void saveInfoPhase(Phase next, long projectCenterOutcomeID, ProjectCenterOutcome projectCenterOutcome) { + Phase phase = phaseDAO.find(next.getId()); + List projectCenterOutcomeList = projectCenterOutcomeDAO.getProjectCenterOutcomeByPhase( + next.getId(), projectCenterOutcome.getProject().getId(), projectCenterOutcome.getCenterOutcome().getId()); + projectCenterOutcomeList = + projectCenterOutcomeList.stream() + .filter(c -> c.isActive() + && c.getProject().getId().longValue() == projectCenterOutcome.getProject().getId().longValue() + && c.getCenterOutcome().getId().longValue() == projectCenterOutcome.getCenterOutcome().getId().longValue()) + .collect(Collectors.toList()); + if (projectCenterOutcomeList.isEmpty()) { + ProjectCenterOutcome projectCenterOutcomeAdd = new ProjectCenterOutcome(); + projectCenterOutcomeAdd.setProject(projectCenterOutcome.getProject()); + projectCenterOutcomeAdd.setCenterOutcome(projectCenterOutcome.getCenterOutcome()); + projectCenterOutcomeAdd.setPhase(phase); + projectCenterOutcomeDAO.save(projectCenterOutcomeAdd); + } else { + + } + if (phase.getNext() != null) { + this.saveInfoPhase(phase.getNext(), projectCenterOutcomeID, projectCenterOutcome); + } + } + + @Override + public ProjectCenterOutcome saveProjectCenterOutcome(ProjectCenterOutcome projectCenterOutcome) { + Phase phase = projectCenterOutcome.getPhase(); + ProjectCenterOutcome projectCenterOutcomeDB = projectCenterOutcomeDAO.save(projectCenterOutcome); + + if (phase.getDescription().equals(APConstants.PLANNING)) { + if (phase.getNext() != null) { + this.saveInfoPhase(phase.getNext(), projectCenterOutcome.getId(), projectCenterOutcome); + } + } + return projectCenterOutcomeDB; } diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/RestApiAuditlogImpl.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/RestApiAuditlogImpl.java new file mode 100644 index 0000000000..2ad11921c6 --- /dev/null +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/RestApiAuditlogImpl.java @@ -0,0 +1,28 @@ +package org.cgiar.ccafs.marlo.data.manager.impl; + +import org.cgiar.ccafs.marlo.data.dao.RestApiAuditlogDAO; +import org.cgiar.ccafs.marlo.data.manager.RestApiAuditlogManager; +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; + +import javax.inject.Inject; +import javax.inject.Named; + +/** + * @author tonyshikali + */ +@Named +public class RestApiAuditlogImpl implements RestApiAuditlogManager { + + private final RestApiAuditlogDAO restApiuditLogDAO; + + @Inject + public RestApiAuditlogImpl(RestApiAuditlogDAO restApiuditLogDAO) { + this.restApiuditLogDAO = restApiuditLogDAO; + } + + @Override + public void logApiCall(RestApiAuditlog restApiAuditlog) { + restApiuditLogDAO.logThis(restApiAuditlog); + } + +} diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Institution.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Institution.java index ec5828893a..969c080486 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Institution.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Institution.java @@ -451,4 +451,4 @@ public String toString() { return "Institution [id=" + this.getId() + ", institutionType=" + institutionType + ", name=" + name + ", acronym=" + acronym + ", programId=" + programId + "]"; } -} \ No newline at end of file +} diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/InstitutionType.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/InstitutionType.java index d7863a52dc..37fbc5f35e 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/InstitutionType.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/InstitutionType.java @@ -38,6 +38,9 @@ public class InstitutionType extends MarloBaseEntity implements java.io.Serializ @Expose private Boolean old; + @Expose + private Boolean isLegacy; + @Expose private Boolean subDepartmentActive; @@ -87,6 +90,10 @@ public Set getInstitutions() { return institutions; } + public Boolean getIsLegacy() { + return isLegacy; + } + @Override public String getLogDeatil() { StringBuilder sb = new StringBuilder(); @@ -152,6 +159,10 @@ public void setInstitutions(Set institutions) { this.institutions = institutions; } + public void setIsLegacy(Boolean isLegacy) { + this.isLegacy = isLegacy; + } + @Override public void setModifiedBy(User modifiedBy) { diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Phase.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Phase.java index cb32945388..20a6233789 100644 --- a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Phase.java +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/Phase.java @@ -498,6 +498,7 @@ public Set getProjectInnovationGeographicScope return projectInnovationGeographicScopes; } + public Set getProjectInnovationInfos() { return projectInnovationInfos; } @@ -527,6 +528,7 @@ public Set getProjectLp6ContributionDeliverab return projectLp6ContributionDeliverables; } + public Set getProjectLp6Contributions() { return projectLp6Contributions; } @@ -849,6 +851,7 @@ public void setProjectExpectedStudySrfTargets(Set this.projectExpectedStudySrfTargets = projectExpectedStudySrfTargets; } + public void setProjectExpectedStudySubIdos(Set projectExpectedStudySubIdos) { this.projectExpectedStudySubIdos = projectExpectedStudySubIdos; } @@ -870,6 +873,7 @@ public void setProjectHighligthsTypes(Set projectHighligth this.projectHighligthsTypes = projectHighligthsTypes; } + public void setProjectInfos(Set projectInfos) { this.projectInfos = projectInfos; } @@ -880,7 +884,6 @@ public void setProjectInfos(Set projectInfos) { this.projectInnovationContribution = projectInnovationContribution; } - public void setProjectInnovationCountries(Set projectInnovationCountries) { this.projectInnovationCountries = projectInnovationCountries; } @@ -902,6 +905,7 @@ public void setProjectInnovationInfos(Set projectInnovati this.projectInnovationInfos = projectInnovationInfos; } + public void setProjectInnovationOrganizations(Set projectInnovationOrganizations) { this.projectInnovationOrganizations = projectInnovationOrganizations; } @@ -911,7 +915,6 @@ public void setProjectInnovationRegions(Set projectInno this.projectInnovationRegions = projectInnovationRegions; } - public void setProjectInnovationShareds(Set projectInnovationShareds) { this.projectInnovationShareds = projectInnovationShareds; } diff --git a/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/RestApiAuditlog.java b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/RestApiAuditlog.java new file mode 100644 index 0000000000..5990a109e9 --- /dev/null +++ b/marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/RestApiAuditlog.java @@ -0,0 +1,162 @@ +/***************************************************************** + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). + * MARLO is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * at your option) any later version. + * MARLO is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with MARLO. If not, see . + *****************************************************************/ + +package org.cgiar.ccafs.marlo.data.model; + +// Generated 8 Jan 2021, 07:21:08 by Hibernate Tools 4.0.0 + +import java.util.Date; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * RestApiAuditlog generated by hbm2java + */ +public class RestApiAuditlog implements java.io.Serializable { + + private static final long serialVersionUID = 1246424897358866286L; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + private long id; + private String action; + private String detail; + private Date createdDate; + private long entityId; + private String entityName; + private String entityJson; + private long userId; + private Long main; + private String modificationJustification; + private Long phase; + + public RestApiAuditlog() { + } + + public RestApiAuditlog(String action, String detail, Date createdDate, long entityId, String entityName, + String entityJson, long userId) { + this.action = action; + this.detail = detail; + this.createdDate = createdDate; + this.entityId = entityId; + this.entityName = entityName; + this.entityJson = entityJson; + this.userId = userId; + } + + public RestApiAuditlog(String action, String detail, Date createdDate, long entityId, String entityName, + String entityJson, long userId, Long main, String modificationJustification, Long phase) { + this.action = action; + this.detail = detail; + this.createdDate = createdDate; + this.entityId = entityId; + this.entityName = entityName; + this.entityJson = entityJson; + this.userId = userId; + this.main = main; + this.modificationJustification = modificationJustification; + this.phase = phase; + } + + public long getId() { + return this.id; + } + + public void setId(long id) { + this.id = id; + } + + public String getAction() { + return this.action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getDetail() { + return this.detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public long getEntityId() { + return this.entityId; + } + + public void setEntityId(long entityId) { + this.entityId = entityId; + } + + public String getEntityName() { + return this.entityName; + } + + public void setEntityName(String entityName) { + this.entityName = entityName; + } + + public String getEntityJson() { + return this.entityJson; + } + + public void setEntityJson(String entityJson) { + this.entityJson = entityJson; + } + + public long getUserId() { + return this.userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public Long getMain() { + return this.main; + } + + public void setMain(Long main) { + this.main = main; + } + + public String getModificationJustification() { + return this.modificationJustification; + } + + public void setModificationJustification(String modificationJustification) { + this.modificationJustification = modificationJustification; + } + + public Long getPhase() { + return this.phase; + } + + public void setPhase(Long phase) { + this.phase = phase; + } + +} diff --git a/marlo-data/src/main/resources/hibernate.cfg.xml b/marlo-data/src/main/resources/hibernate.cfg.xml index 3553c2a57c..cbbd2ed324 100644 --- a/marlo-data/src/main/resources/hibernate.cfg.xml +++ b/marlo-data/src/main/resources/hibernate.cfg.xml @@ -464,10 +464,11 @@ - + + diff --git a/marlo-data/src/main/resources/xmls/InstitutionTypes.hbm.xml b/marlo-data/src/main/resources/xmls/InstitutionTypes.hbm.xml index 4f3ef4ee61..78808d7440 100644 --- a/marlo-data/src/main/resources/xmls/InstitutionTypes.hbm.xml +++ b/marlo-data/src/main/resources/xmls/InstitutionTypes.hbm.xml @@ -20,7 +20,10 @@ - + + + + diff --git a/marlo-data/src/main/resources/xmls/RestApiAuditlog.hbm.xml b/marlo-data/src/main/resources/xmls/RestApiAuditlog.hbm.xml new file mode 100644 index 0000000000..18d91136f9 --- /dev/null +++ b/marlo-data/src/main/resources/xmls/RestApiAuditlog.hbm.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/PartnersSaveAction.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/PartnersSaveAction.java index 8f42e28c04..dbebede451 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/PartnersSaveAction.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/PartnersSaveAction.java @@ -81,7 +81,7 @@ public class PartnersSaveAction extends BaseAction { // Managers private LocElementManager locationManager; - private InstitutionTypeManager institutionManager; + private InstitutionTypeManager institutionTypeManager; private InstitutionManager institutionsManager; private ProjectManager projectManager; private FundingSourceManager fundingSourceManager; @@ -120,7 +120,7 @@ public PartnersSaveAction(APConfig config, LocElementManager locationManager, ReportSynthesisManager reportSynthesisManager) { super(config); this.locationManager = locationManager; - this.institutionManager = institutionManager; + this.institutionTypeManager = institutionManager; this.projectManager = projectManager; this.institutionsManager = institutionsManager; this.partnerRequestManager = partnerRequestManager; @@ -314,8 +314,11 @@ public void prepare() throws Exception { this.countriesList = locationManager.findAll().stream() .filter(c -> c.isActive() && c.getLocElementType().getId().longValue() == 2).collect(Collectors.toList()); - this.institutionTypesList = - institutionManager.findAll().stream().filter(c -> c.isActive() && !c.getOld()).collect(Collectors.toList());; + /* + * this.institutionTypesList = + * institutionTypeManager.findAll().stream().filter(c -> c.isActive() && !c.getOld()).collect(Collectors.toList()); + */ + this.institutionTypesList = institutionTypeManager.findAllIATITypes(); institutions = institutionsManager.findAll().stream().filter(c -> c.isActive()).collect(Collectors.toList()); institutions.sort((p1, p2) -> p1.getName().compareTo(p2.getName())); @@ -368,8 +371,8 @@ public String save() { partnerRequest.setLocElement(locationManager.getLocElementById(Long.parseLong(countryId))); partnerRequestModifications.setLocElement(locationManager.getLocElementById(Long.parseLong(countryId))); - partnerRequest.setInstitutionType(institutionManager.getInstitutionTypeById(partnerTypeId)); - partnerRequestModifications.setInstitutionType(institutionManager.getInstitutionTypeById(partnerTypeId)); + partnerRequest.setInstitutionType(institutionTypeManager.getInstitutionTypeById(partnerTypeId)); + partnerRequestModifications.setInstitutionType(institutionTypeManager.getInstitutionTypeById(partnerTypeId)); partnerRequest.setOffice(false); partnerRequestModifications.setOffice(false); partnerRequest.setPhase(this.getActualPhase()); diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectCenterMappingAction.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectCenterMappingAction.java index d8a8aacc22..08e5c101e7 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectCenterMappingAction.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectCenterMappingAction.java @@ -1,705 +1,721 @@ -/***************************************************************** - * This file is part of Managing Agricultural Research for Learning & - * Outcomes Platform (MARLO). - * MARLO is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * at your option) any later version. - * MARLO is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * You should have received a copy of the GNU General Public License - * along with MARLO. If not, see . - *****************************************************************/ - -package org.cgiar.ccafs.marlo.action.projects; - -import org.cgiar.ccafs.marlo.action.BaseAction; -import org.cgiar.ccafs.marlo.config.APConstants; -import org.cgiar.ccafs.marlo.data.manager.AuditLogManager; -import org.cgiar.ccafs.marlo.data.manager.CrpProgramManager; -import org.cgiar.ccafs.marlo.data.manager.GlobalUnitManager; -import org.cgiar.ccafs.marlo.data.manager.LiaisonInstitutionManager; -import org.cgiar.ccafs.marlo.data.manager.PhaseManager; -import org.cgiar.ccafs.marlo.data.manager.ProjectCenterOutcomeManager; -import org.cgiar.ccafs.marlo.data.manager.ProjectFocusManager; -import org.cgiar.ccafs.marlo.data.manager.ProjectInfoManager; -import org.cgiar.ccafs.marlo.data.manager.ProjectManager; -import org.cgiar.ccafs.marlo.data.manager.impl.CenterOutcomeManager; -import org.cgiar.ccafs.marlo.data.model.CenterOutcome; -import org.cgiar.ccafs.marlo.data.model.CenterTopic; -import org.cgiar.ccafs.marlo.data.model.CrpProgram; -import org.cgiar.ccafs.marlo.data.model.GlobalUnit; -import org.cgiar.ccafs.marlo.data.model.LiaisonInstitution; -import org.cgiar.ccafs.marlo.data.model.Phase; -import org.cgiar.ccafs.marlo.data.model.ProgramType; -import org.cgiar.ccafs.marlo.data.model.Project; -import org.cgiar.ccafs.marlo.data.model.ProjectCenterOutcome; -import org.cgiar.ccafs.marlo.data.model.ProjectFocus; -import org.cgiar.ccafs.marlo.data.model.ProjectInfo; -import org.cgiar.ccafs.marlo.security.Permission; -import org.cgiar.ccafs.marlo.utils.APConfig; -import org.cgiar.ccafs.marlo.utils.AutoSaveReader; -import org.cgiar.ccafs.marlo.validation.projects.ProjectCenterMappingValidator; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.inject.Inject; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Hermes Jiménez - CIAT/CCAFS - */ -public class ProjectCenterMappingAction extends BaseAction { - - private static final long serialVersionUID = 6623716093003057656L; - - private static final Logger LOG = LoggerFactory.getLogger(ProjectCenterMappingAction.class); - - - private ProjectManager projectManager; - - private CrpProgramManager programManager; - private GlobalUnitManager crpManager; - private ProjectFocusManager projectFocusManager; - private AuditLogManager auditLogManager; - private long projectID; - private GlobalUnit loggedCrp; - private Project project; - private List programFlagships; - private List regionFlagships; - private String transaction; - private List centerPrograms; - private List regionPrograms; - private ProjectInfoManager projectInfoManager; - private Project projectDB; - private ProjectCenterMappingValidator validator; - private long sharedPhaseID; - private PhaseManager phaseManager; - private List liaisonInstitutions; - private LiaisonInstitutionManager liaisonInstitutionManager; - private ProjectCenterOutcomeManager projectCenterOutcomeManager; - private CenterOutcomeManager centerOutcomeManager; - private List centerOutcomes; - - @Inject - public ProjectCenterMappingAction(APConfig config, ProjectManager projectManager, CrpProgramManager programManager, - GlobalUnitManager crpManager, ProjectFocusManager projectFocusManager, AuditLogManager auditLogManager, - ProjectInfoManager projectInfoManager, ProjectCenterMappingValidator validator, PhaseManager phaseManager, - LiaisonInstitutionManager liaisonInstitutionManager, ProjectCenterOutcomeManager projectCenterOutcomeManager, - CenterOutcomeManager centerOutcomeManager) { - super(config); - this.projectManager = projectManager; - this.programManager = programManager; - this.crpManager = crpManager; - this.projectFocusManager = projectFocusManager; - this.auditLogManager = auditLogManager; - this.projectInfoManager = projectInfoManager; - this.validator = validator; - this.phaseManager = phaseManager; - this.liaisonInstitutionManager = liaisonInstitutionManager; - this.projectCenterOutcomeManager = projectCenterOutcomeManager; - this.centerOutcomeManager = centerOutcomeManager; - } - - private Path getAutoSaveFilePath(Phase phase) { - // get the class simple name - String composedClassName = project.getClass().getSimpleName(); - // get the action name and replace / for _ - String actionFile = this.getActionName().replace("/", "_"); - // concatane name and add the .json extension - String autoSaveFile = project.getId() + "_" + composedClassName + "_" + phase.getName() + "_" + phase.getYear() - + "_" + actionFile + ".json"; - - return Paths.get(config.getAutoSaveFolder() + autoSaveFile); - } - - public List getCenterOutcomes() { - return centerOutcomes; - } - - public List getCenterPrograms() { - return centerPrograms; - } - - public long[] getFlagshipIds() { - - List projectFocuses = project.getFlagships(); - - if (projectFocuses != null) { - long[] ids = new long[projectFocuses.size()]; - for (int c = 0; c < ids.length; c++) { - ids[c] = projectFocuses.get(c).getId(); - } - return ids; - } - return null; - } - - public List getLiaisonInstitutions() { - return liaisonInstitutions; - } - - public GlobalUnit getLoggedCrp() { - return loggedCrp; - } - - public List getProgramFlagships() { - return programFlagships; - } - - public Project getProject() { - return project; - } - - public long getProjectID() { - return projectID; - } - - public List getRegionFlagships() { - return regionFlagships; - } - - - public List getRegionPrograms() { - return regionPrograms; - } - - public long[] getRegionsIds() { - - List projectFocuses = project.getRegions(); - - if (projectFocuses != null) { - long[] ids = new long[projectFocuses.size()]; - for (int c = 0; c < ids.length; c++) { - ids[c] = projectFocuses.get(c).getId(); - } - return ids; - } - return null; - } - - public long getSharedPhaseID() { - return sharedPhaseID; - } - - public String getTransaction() { - return transaction; - } - - @Override - public void prepare() throws Exception { - // Get current CRP - loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP); - loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId()); - - Phase phase = this.getActualPhase(); - sharedPhaseID = phase.getId(); - - try { - projectID = Long.parseLong(StringUtils.trim(this.getRequest().getParameter(APConstants.PROJECT_REQUEST_ID))); - } catch (Exception e) { - LOG.error("unable to parse projectID", e); - /** - * Original code swallows the exception and didn't even log it. Now we at least log it, - * but we need to revisit to see if we should continue processing or re-throw the exception. - */ - } - - if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) { - - transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID)); - // auditLogManager.getHistory Bring us the history with the transaction id - Project history = (Project) auditLogManager.getHistory(transaction); - - // In case there are some relationships that are displayed on the front in a particular field, add to this list by - // passing the name of the relationship and the name of the attribute with which it is displayed on the front - Map specialList = new HashMap<>(); - specialList.put(APConstants.PROJECT_FOCUSES_RELATION, "flagshipValue"); - - - if (history != null) { - project = history; - } else { - // not a valid transatacion - this.transaction = null; - this.setTransaction("-1"); - } - - } else { - // get project info for DB - project = projectManager.getProjectById(projectID); - } - - - if (project != null) { - // We validate if there is a draft version - // Get the path - Path path = this.getAutoSaveFilePath(phase); - // validate if file exist and user has enabled auto-save funcionallity - if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) { - - BufferedReader reader = null; - // instace de buffer from file - reader = new BufferedReader(new FileReader(path.toFile())); - Gson gson = new GsonBuilder().create(); - JsonObject jReader = gson.fromJson(reader, JsonObject.class); - reader.close(); - // instance class AutoSaveReader (made by US) - AutoSaveReader autoSaveReader = new AutoSaveReader(); - // We read the JSON serialized by the front-end and cast it to the object - project = (Project) autoSaveReader.readFromJson(jReader); - - // We load some BD objects, since the draft only keeps IDs and some data is shown with a different labe - Project projectDb = projectManager.getProjectById(project.getId()); - // load LiaisonInstitutionCenter info - if (project.getProjectInfo().getLiaisonInstitutionCenter() != null) { - projectDb.getProjectInfo().setLiaisonInstitutionCenter(liaisonInstitutionManager - .getLiaisonInstitutionById(project.getProjectInfo().getLiaisonInstitutionCenter().getId())); - } else { - projectDb.getProjectInfo().setLiaisonInstitutionCenter(null); - } - - - project.setProjectInfo(projectDb.getProjectInfo()); - project.getProjectInfo().setProjectEditLeader(projectDb.getProjecInfoPhase(phase).isProjectEditLeader()); - project.getProjectInfo().setAdministrative(projectDb.getProjecInfoPhase(phase).getAdministrative()); - project.getProjectInfo().setPhase(projectDb.getProjecInfoPhase(phase).getPhase()); - - - if (project.getCenterOutcomes() != null) { - for (ProjectCenterOutcome projectCenterOutcome : project.getCenterOutcomes()) { - projectCenterOutcome.setCenterOutcome( - centerOutcomeManager.getResearchOutcomeById(projectCenterOutcome.getCenterOutcome().getId())); - } - } - - // load fps value - List programs = new ArrayList<>(); - if (project.getFlagshipValue() != null) { - for (String programID : project.getFlagshipValue().trim().replace("[", "").replace("]", "").split(",")) { - try { - CrpProgram program = programManager.getCrpProgramById(Long.parseLong(programID.trim())); - programs.add(program); - } catch (Exception e) { - LOG.error("unable to add program to programs list", e); - /** - * Original code swallows the exception and didn't even log it. Now we at least log it, - * but we need to revisit to see if we should continue processing or re-throw the exception. - */ - } - } - } - - // load regions value - List regions = new ArrayList<>(); - if (project.getRegionsValue() != null) { - for (String programID : project.getRegionsValue().trim().replace("[", "").replace("]", "").split(",")) { - try { - CrpProgram program = programManager.getCrpProgramById(Long.parseLong(programID.trim())); - regions.add(program); - } catch (Exception e) { - LOG.error("unable to add program to regions list", e); - /** - * Original code swallows the exception and didn't even log it. Now we at least log it, - * but we need to revisit to see if we should continue processing or re-throw the exception. - */ - } - } - } - project.setFlagships(programs); - project.setRegions(regions); - - - // We change this variable so that the user knows that he is working on a draft version - - this.setDraft(true); - - } else { - this.setDraft(false); - - // Load the DB information and adjust it to the structures with the front end - project.setProjectInfo(project.getProjecInfoPhase(phase)); - if (project.getProjectInfo() == null) { - project.setProjectInfo(new ProjectInfo()); - } - - if (project.getProjectInfo().getLiaisonInstitutionCenter() != null - && project.getProjectInfo().getLiaisonInstitutionCenter().getId() != null) { - project.getProjectInfo().setLiaisonInstitutionCenter(liaisonInstitutionManager - .getLiaisonInstitutionById(project.getProjectInfo().getLiaisonInstitutionCenter().getId())); - } else { - project.getProjecInfoPhase(this.getActualPhase()).setLiaisonInstitutionCenter(null); - } - - // Load the center Programs - project.setFlagshipValue(""); - project.setRegionsValue(""); - List programs = new ArrayList<>(); - for (ProjectFocus projectFocuses : project.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(phase) - && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() - && c.getCrpProgram().getCrp().getId().equals(this.getLoggedCrp().getId())) - .collect(Collectors.toList())) { - programs.add(projectFocuses.getCrpProgram()); - if (project.getFlagshipValue().isEmpty()) { - project.setFlagshipValue(projectFocuses.getCrpProgram().getId().toString()); - } else { - project - .setFlagshipValue(project.getFlagshipValue() + "," + projectFocuses.getCrpProgram().getId().toString()); - } - } - - List regions = new ArrayList<>(); - - for (ProjectFocus projectFocuses : project.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(phase) - && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue() - && c.getCrpProgram().getCrp().getId().equals(this.getLoggedCrp().getId())) - .collect(Collectors.toList())) { - regions.add(projectFocuses.getCrpProgram()); - if (project.getRegionsValue() != null && project.getRegionsValue().isEmpty()) { - project.setRegionsValue(projectFocuses.getCrpProgram().getId().toString()); - } else { - project - .setRegionsValue(project.getRegionsValue() + "," + projectFocuses.getCrpProgram().getId().toString()); - } - } - - List projectCenterOutcomes = new ArrayList<>(); - for (ProjectCenterOutcome projectCenterOutcome : project.getProjectCenterOutcomes().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(phase)) - .collect(Collectors.toList())) { - projectCenterOutcome.setCenterOutcome( - centerOutcomeManager.getResearchOutcomeById(projectCenterOutcome.getCenterOutcome().getId())); - projectCenterOutcomes.add(projectCenterOutcome); - } - project.setCenterOutcomes(projectCenterOutcomes); - project.setFlagships(programs); - project.setRegions(regions); - } - - liaisonInstitutions = new ArrayList(); - // load the liasons intitutions for the crp - liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream() - .filter(c -> c.isActive() && c.getCrpProgram() != null - && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) - .collect(Collectors.toList())); - // load the flaghsips an regions - programFlagships = new ArrayList<>(); - regionFlagships = new ArrayList<>(); - programFlagships.addAll(loggedCrp.getCrpPrograms().stream() - .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) - .collect(Collectors.toList())); - - programFlagships.sort((p1, p2) -> p1.getCenterComposedName().compareTo(p2.getCenterComposedName())); - - - centerOutcomes = new ArrayList<>(); - - for (CrpProgram crpProgram : project.getFlagships()) { - crpProgram = programManager.getCrpProgramById(crpProgram.getId()); - List centerTopics = new ArrayList<>( - crpProgram.getResearchTopics().stream().filter(rt -> rt.isActive()).collect(Collectors.toList())); - for (CenterTopic centerTopic : centerTopics) { - List centerOutcomesList = new ArrayList<>( - centerTopic.getResearchOutcomes().stream().filter(ro -> ro.isActive()).collect(Collectors.toList())); - for (CenterOutcome centerOutcome : centerOutcomesList) { - centerOutcomes.add(centerOutcome); - } - } - } - - regionFlagships.addAll(loggedCrp.getCrpPrograms().stream() - .filter(c -> c.isActive() && c.getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue()) - .collect(Collectors.toList())); - - } - - projectDB = projectManager.getProjectById(projectID); - - // The base permission is established for the current section - - String params[] = {loggedCrp.getAcronym() + ""}; - this.setBasePermission(this.getText(Permission.SHARED_PROJECT_BASE_PERMISSION, params)); - - if (this.isHttpPost()) { - project.getProjecInfoPhase(this.getActualPhase()).setLiaisonInstitutionCenter(null); - project.setFlagshipValue(null); - project.setRegionsValue(null); - if (project.getCenterOutcomes() != null) { - project.getCenterOutcomes().clear(); - } - } - } - - @Override - public String save() { - if (this.hasPermission("canEdit")) { - Phase sharedPhase = phaseManager.getPhaseById(sharedPhaseID); - - // Load basic info project to be saved - projectDB.setProjectInfo(projectDB.getProjecInfoPhase(sharedPhase)); - - project.setCreateDate(projectDB.getCreateDate()); - project.getProjectInfo().setPresetDate(projectDB.getProjectInfo().getPresetDate()); - - project.getProjectInfo().setStatus(projectDB.getProjectInfo().getStatus()); - - if (project.getProjectInfo().getLiaisonInstitutionCenter() != null) { - if (project.getProjectInfo().getLiaisonInstitutionCenter().getId() == -1) { - project.getProjectInfo().setLiaisonInstitutionCenter(null); - } - } - - // Saving the flaghsips - if (project.getFlagshipValue() != null && project.getFlagshipValue().length() > 0) { - - List fpsPreview = projectDB.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) - && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() - && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) - .collect(Collectors.toList()); - for (ProjectFocus projectFocus : fpsPreview) { - if (!project.getFlagshipValue().contains(projectFocus.getCrpProgram().getId().toString())) { - projectFocusManager.deleteProjectFocus(projectFocus.getId()); - } - } - - for (String programID : project.getFlagshipValue().trim().split(",")) { - if (programID.length() > 0) { - CrpProgram program = - programManager.getCrpProgramById(Long.parseLong(programID.trim().replaceAll("[^0-9]", ""))); - ProjectFocus projectFocus = new ProjectFocus(); - projectFocus.setCrpProgram(program); - projectFocus.setProject(projectDB); - - projectFocus.setPhase(sharedPhase); - if (projectDB.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getCrpProgram().getId().longValue() == program.getId().longValue() - && c.getPhase().equals(sharedPhase)) - .collect(Collectors.toList()).isEmpty()) { - projectFocus.setPhase(sharedPhase); - projectFocusManager.saveProjectFocus(projectFocus); - } - } - - } - } else { - // Delete All flagships - for (ProjectFocus projectFocus : projectDB.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) - && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() - && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) - .collect(Collectors.toList())) { - projectFocusManager.deleteProjectFocus(projectFocus.getId()); - } - } - - - // Saving the regions - if (project.getRegionsValue() != null && project.getRegionsValue().length() > 0) { - - List regionsPreview = projectDB.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) - && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue() - && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) - .collect(Collectors.toList()); - for (ProjectFocus projectFocus : regionsPreview) { - if (!project.getRegionsValue().contains(projectFocus.getCrpProgram().getId().toString())) { - projectFocusManager.deleteProjectFocus(projectFocus.getId()); - } - } - - for (String programID : project.getRegionsValue().trim().split(",")) { - if (programID.length() > 0) { - CrpProgram program = programManager.getCrpProgramById(Long.parseLong(programID.trim())); - ProjectFocus projectFocus = new ProjectFocus(); - projectFocus.setCrpProgram(program); - projectFocus.setProject(projectDB); - projectFocus.setPhase(sharedPhase); - if (projectDB.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) - && c.getCrpProgram().getId().longValue() == program.getId().longValue()) - .collect(Collectors.toList()).isEmpty()) { - projectFocus.setPhase(sharedPhase); - projectFocusManager.saveProjectFocus(projectFocus); - } - } - } - } else { - // Delete All Regions - for (ProjectFocus projectFocus : projectDB.getProjectFocuses().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) - && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue() - && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) - .collect(Collectors.toList())) { - projectFocusManager.deleteProjectFocus(projectFocus.getId()); - } - } - - - // Saving Project Center Outcomes - if (project.getCenterOutcomes() != null && !project.getCenterOutcomes().isEmpty()) { - // Removing Project Center Outcomes - for (ProjectCenterOutcome projectCenterOutcome : projectDB.getProjectCenterOutcomes().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase)) - .collect(Collectors.toList())) { - if (!project.getCenterOutcomes().contains(projectCenterOutcome)) { - projectCenterOutcomeManager.deleteProjectCenterOutcome(projectCenterOutcome.getId()); - } - } - // Add Project Center Outcomes - for (ProjectCenterOutcome projectCenterOutcome : project.getCenterOutcomes()) { - if (projectCenterOutcome.getId() == null) { - projectCenterOutcome.setProject(project); - projectCenterOutcome.setPhase(sharedPhase); - projectCenterOutcome = projectCenterOutcomeManager.saveProjectCenterOutcome(projectCenterOutcome); - // This add centerOutcome to generate correct auditlog. - project.getProjectCenterOutcomes().add(projectCenterOutcome); - } - } - - } else { - // Removing All Project Center Outcomes - for (ProjectCenterOutcome projectCenterOutcome : projectDB.getProjectCenterOutcomes().stream() - .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase)) - .collect(Collectors.toList())) { - projectCenterOutcomeManager.deleteProjectCenterOutcome(projectCenterOutcome.getId()); - } - } - - - project.getProjectInfo().setCofinancing(projectDB.getProjectInfo().isCofinancing()); - - List relationsName = new ArrayList<>(); - relationsName.add(APConstants.PROJECT_FOCUSES_RELATION); - relationsName.add(APConstants.PROJECT_CLUSTER_ACTIVITIES_RELATION); - relationsName.add(APConstants.PROJECT_SCOPES_RELATION); - relationsName.add(APConstants.PROJECT_INFO_RELATION); - - project.getProjectInfo().setPhase(sharedPhase); - project.getProjectInfo().setProject(project); - project.getProjectInfo().setReporting(projectDB.getProjectInfo().getReporting()); - project.getProjectInfo().setAdministrative(projectDB.getProjectInfo().getAdministrative()); - project.getProjectInfo().setLocationRegional(projectDB.getProjectInfo().getLocationRegional()); - project.getProjectInfo().setLocationGlobal(projectDB.getProjectInfo().getLocationGlobal()); - project.getProjectInfo().setLocationRegional(projectDB.getProjectInfo().getLocationRegional()); - project.getProjectInfo().setLiaisonInstitution(projectDB.getProjectInfo().getLiaisonInstitution()); - - project.getProjectInfo().setModificationJustification(this.getJustification()); - project.getProjectInfo().setActiveSince(new Date()); - projectInfoManager.saveProjectInfo(project.getProjectInfo()); - - // Saving project and add relations we want to save on the history - - // List relationsName = new ArrayList<>(); - // relationsName.add(APConstants.PROJECT_FOCUSES_RELATION); - // relationsName.add(APConstants.PROJECT_INFO_RELATION); - // /** - // * The following is required because we need to update something on the @Project if we want a row created in - // the - // * auditlog table. - // */ - this.setModificationJustification(project); - projectManager.saveProject(project, this.getActionName(), relationsName, sharedPhase); - - Path path = this.getAutoSaveFilePath(sharedPhase); - // delete the draft file if exists - if (path.toFile().exists()) { - path.toFile().delete(); - } - - // check if there is a url to redirect - if (this.getUrl() == null || this.getUrl().isEmpty()) { - // check if there are missing field - if (!this.getInvalidFields().isEmpty()) { - this.setActionMessages(null); - // this.addActionMessage(Map.toString(this.getInvalidFields().toArray())); - List keys = new ArrayList(this.getInvalidFields().keySet()); - for (String key : keys) { - this.addActionMessage(key + ": " + this.getInvalidFields().get(key)); - } - } else { - this.addActionMessage("message:" + this.getText("saving.saved")); - } - } - - return SUCCESS; - } else - - { - return NOT_AUTHORIZED; - } - - } - - public void setCenterOutcomes(List centerOutcomes) { - this.centerOutcomes = centerOutcomes; - } - - public void setCenterPrograms(List centerPrograms) { - this.centerPrograms = centerPrograms; - } - - public void setLiaisonInstitutions(List liaisonInstitutions) { - this.liaisonInstitutions = liaisonInstitutions; - } - - public void setLoggedCrp(GlobalUnit loggedCrp) { - this.loggedCrp = loggedCrp; - } - - public void setProgramFlagships(List programFlagships) { - this.programFlagships = programFlagships; - } - - public void setProject(Project project) { - this.project = project; - } - - public void setProjectID(long projectID) { - this.projectID = projectID; - } - - public void setRegionFlagships(List regionFlagships) { - this.regionFlagships = regionFlagships; - } - - public void setRegionPrograms(List regionPrograms) { - this.regionPrograms = regionPrograms; - } - - public void setSharedPhaseID(long sharedPhaseID) { - this.sharedPhaseID = sharedPhaseID; - } - - public void setTransaction(String transaction) { - this.transaction = transaction; - } - - @Override - public void validate() { - // if is saving call the validator to check for the missing fields - if (save) { - validator.validate(this, project, true, sharedPhaseID); - } - } - -} +/***************************************************************** + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). + * MARLO is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * at your option) any later version. + * MARLO is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with MARLO. If not, see . + *****************************************************************/ + +package org.cgiar.ccafs.marlo.action.projects; + +import org.cgiar.ccafs.marlo.action.BaseAction; +import org.cgiar.ccafs.marlo.config.APConstants; +import org.cgiar.ccafs.marlo.data.manager.AuditLogManager; +import org.cgiar.ccafs.marlo.data.manager.CrpProgramManager; +import org.cgiar.ccafs.marlo.data.manager.GlobalUnitManager; +import org.cgiar.ccafs.marlo.data.manager.LiaisonInstitutionManager; +import org.cgiar.ccafs.marlo.data.manager.PhaseManager; +import org.cgiar.ccafs.marlo.data.manager.ProjectCenterOutcomeManager; +import org.cgiar.ccafs.marlo.data.manager.ProjectFocusManager; +import org.cgiar.ccafs.marlo.data.manager.ProjectInfoManager; +import org.cgiar.ccafs.marlo.data.manager.ProjectManager; +import org.cgiar.ccafs.marlo.data.manager.impl.CenterOutcomeManager; +import org.cgiar.ccafs.marlo.data.model.CenterOutcome; +import org.cgiar.ccafs.marlo.data.model.CenterTopic; +import org.cgiar.ccafs.marlo.data.model.CrpProgram; +import org.cgiar.ccafs.marlo.data.model.GlobalUnit; +import org.cgiar.ccafs.marlo.data.model.LiaisonInstitution; +import org.cgiar.ccafs.marlo.data.model.Phase; +import org.cgiar.ccafs.marlo.data.model.ProgramType; +import org.cgiar.ccafs.marlo.data.model.Project; +import org.cgiar.ccafs.marlo.data.model.ProjectCenterOutcome; +import org.cgiar.ccafs.marlo.data.model.ProjectFocus; +import org.cgiar.ccafs.marlo.data.model.ProjectInfo; +import org.cgiar.ccafs.marlo.security.Permission; +import org.cgiar.ccafs.marlo.utils.APConfig; +import org.cgiar.ccafs.marlo.utils.AutoSaveReader; +import org.cgiar.ccafs.marlo.validation.projects.ProjectCenterMappingValidator; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.inject.Inject; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Hermes Jiménez - CIAT/CCAFS + */ +public class ProjectCenterMappingAction extends BaseAction { + + private static final long serialVersionUID = 6623716093003057656L; + + private static final Logger LOG = LoggerFactory.getLogger(ProjectCenterMappingAction.class); + + + private ProjectManager projectManager; + + private CrpProgramManager programManager; + private GlobalUnitManager crpManager; + private ProjectFocusManager projectFocusManager; + private AuditLogManager auditLogManager; + private long projectID; + private GlobalUnit loggedCrp; + private Project project; + private List programFlagships; + private List regionFlagships; + private String transaction; + private List centerPrograms; + private List regionPrograms; + private ProjectInfoManager projectInfoManager; + private Project projectDB; + private ProjectCenterMappingValidator validator; + private long sharedPhaseID; + private PhaseManager phaseManager; + private List liaisonInstitutions; + private LiaisonInstitutionManager liaisonInstitutionManager; + private ProjectCenterOutcomeManager projectCenterOutcomeManager; + private CenterOutcomeManager centerOutcomeManager; + private List centerOutcomes; + private boolean canMapPrograms; + + @Inject + public ProjectCenterMappingAction(APConfig config, ProjectManager projectManager, CrpProgramManager programManager, + GlobalUnitManager crpManager, ProjectFocusManager projectFocusManager, AuditLogManager auditLogManager, + ProjectInfoManager projectInfoManager, ProjectCenterMappingValidator validator, PhaseManager phaseManager, + LiaisonInstitutionManager liaisonInstitutionManager, ProjectCenterOutcomeManager projectCenterOutcomeManager, + CenterOutcomeManager centerOutcomeManager) { + super(config); + this.projectManager = projectManager; + this.programManager = programManager; + this.crpManager = crpManager; + this.projectFocusManager = projectFocusManager; + this.auditLogManager = auditLogManager; + this.projectInfoManager = projectInfoManager; + this.validator = validator; + this.phaseManager = phaseManager; + this.liaisonInstitutionManager = liaisonInstitutionManager; + this.projectCenterOutcomeManager = projectCenterOutcomeManager; + this.centerOutcomeManager = centerOutcomeManager; + } + + private Path getAutoSaveFilePath(Phase phase) { + // get the class simple name + String composedClassName = project.getClass().getSimpleName(); + // get the action name and replace / for _ + String actionFile = this.getActionName().replace("/", "_"); + // concatane name and add the .json extension + String autoSaveFile = project.getId() + "_" + composedClassName + "_" + phase.getName() + "_" + phase.getYear() + + "_" + actionFile + ".json"; + + return Paths.get(config.getAutoSaveFolder() + autoSaveFile); + } + + public List getCenterOutcomes() { + return centerOutcomes; + } + + public List getCenterPrograms() { + return centerPrograms; + } + + public long[] getFlagshipIds() { + + List projectFocuses = project.getFlagships(); + + if (projectFocuses != null) { + long[] ids = new long[projectFocuses.size()]; + for (int c = 0; c < ids.length; c++) { + ids[c] = projectFocuses.get(c).getId(); + } + return ids; + } + return null; + } + + public List getLiaisonInstitutions() { + return liaisonInstitutions; + } + + public GlobalUnit getLoggedCrp() { + return loggedCrp; + } + + public List getProgramFlagships() { + return programFlagships; + } + + public Project getProject() { + return project; + } + + public long getProjectID() { + return projectID; + } + + public List getRegionFlagships() { + return regionFlagships; + } + + + public List getRegionPrograms() { + return regionPrograms; + } + + public long[] getRegionsIds() { + + List projectFocuses = project.getRegions(); + + if (projectFocuses != null) { + long[] ids = new long[projectFocuses.size()]; + for (int c = 0; c < ids.length; c++) { + ids[c] = projectFocuses.get(c).getId(); + } + return ids; + } + return null; + } + + public long getSharedPhaseID() { + return sharedPhaseID; + } + + public String getTransaction() { + return transaction; + } + + public boolean isCanMapPrograms() { + return canMapPrograms; + } + + + @Override + public void prepare() throws Exception { + // Get current CRP + loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP); + loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId()); + + Phase phase = this.getActualPhase(); + sharedPhaseID = phase.getId(); + canMapPrograms = false; + + try { + projectID = Long.parseLong(StringUtils.trim(this.getRequest().getParameter(APConstants.PROJECT_REQUEST_ID))); + } catch (Exception e) { + LOG.error("unable to parse projectID", e); + /** + * Original code swallows the exception and didn't even log it. Now we at least log it, + * but we need to revisit to see if we should continue processing or re-throw the exception. + */ + } + + if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) { + + transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID)); + // auditLogManager.getHistory Bring us the history with the transaction id + Project history = (Project) auditLogManager.getHistory(transaction); + + // In case there are some relationships that are displayed on the front in a particular field, add to this list by + // passing the name of the relationship and the name of the attribute with which it is displayed on the front + Map specialList = new HashMap<>(); + specialList.put(APConstants.PROJECT_FOCUSES_RELATION, "flagshipValue"); + + + if (history != null) { + project = history; + } else { + // not a valid transatacion + this.transaction = null; + this.setTransaction("-1"); + } + + } else { + // get project info for DB + project = projectManager.getProjectById(projectID); + } + + + if (project != null) { + // We validate if there is a draft version + // Get the path + Path path = this.getAutoSaveFilePath(phase); + // validate if file exist and user has enabled auto-save funcionallity + if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) { + + BufferedReader reader = null; + // instace de buffer from file + reader = new BufferedReader(new FileReader(path.toFile())); + Gson gson = new GsonBuilder().create(); + JsonObject jReader = gson.fromJson(reader, JsonObject.class); + reader.close(); + // instance class AutoSaveReader (made by US) + AutoSaveReader autoSaveReader = new AutoSaveReader(); + // We read the JSON serialized by the front-end and cast it to the object + project = (Project) autoSaveReader.readFromJson(jReader); + + // We load some BD objects, since the draft only keeps IDs and some data is shown with a different labe + Project projectDb = projectManager.getProjectById(project.getId()); + // load LiaisonInstitutionCenter info + if (project.getProjectInfo().getLiaisonInstitutionCenter() != null) { + projectDb.getProjectInfo().setLiaisonInstitutionCenter(liaisonInstitutionManager + .getLiaisonInstitutionById(project.getProjectInfo().getLiaisonInstitutionCenter().getId())); + } else { + projectDb.getProjectInfo().setLiaisonInstitutionCenter(null); + } + + + project.setProjectInfo(projectDb.getProjectInfo()); + project.getProjectInfo().setProjectEditLeader(projectDb.getProjecInfoPhase(phase).isProjectEditLeader()); + project.getProjectInfo().setAdministrative(projectDb.getProjecInfoPhase(phase).getAdministrative()); + project.getProjectInfo().setPhase(projectDb.getProjecInfoPhase(phase).getPhase()); + + + if (project.getCenterOutcomes() != null) { + for (ProjectCenterOutcome projectCenterOutcome : project.getCenterOutcomes()) { + projectCenterOutcome.setCenterOutcome( + centerOutcomeManager.getResearchOutcomeById(projectCenterOutcome.getCenterOutcome().getId())); + } + } + + // load fps value + List programs = new ArrayList<>(); + if (project.getFlagshipValue() != null) { + for (String programID : project.getFlagshipValue().trim().replace("[", "").replace("]", "").split(",")) { + try { + CrpProgram program = programManager.getCrpProgramById(Long.parseLong(programID.trim())); + programs.add(program); + } catch (Exception e) { + LOG.error("unable to add program to programs list", e); + /** + * Original code swallows the exception and didn't even log it. Now we at least log it, + * but we need to revisit to see if we should continue processing or re-throw the exception. + */ + } + } + } + + // load regions value + List regions = new ArrayList<>(); + if (project.getRegionsValue() != null) { + for (String programID : project.getRegionsValue().trim().replace("[", "").replace("]", "").split(",")) { + try { + CrpProgram program = programManager.getCrpProgramById(Long.parseLong(programID.trim())); + regions.add(program); + } catch (Exception e) { + LOG.error("unable to add program to regions list", e); + /** + * Original code swallows the exception and didn't even log it. Now we at least log it, + * but we need to revisit to see if we should continue processing or re-throw the exception. + */ + } + } + } + project.setFlagships(programs); + project.setRegions(regions); + + + // We change this variable so that the user knows that he is working on a draft version + + this.setDraft(true); + + } else { + this.setDraft(false); + + // Load the DB information and adjust it to the structures with the front end + project.setProjectInfo(project.getProjecInfoPhase(phase)); + if (project.getProjectInfo() == null) { + project.setProjectInfo(new ProjectInfo()); + } + + if (project.getProjectInfo().getLiaisonInstitutionCenter() != null + && project.getProjectInfo().getLiaisonInstitutionCenter().getId() != null) { + project.getProjectInfo().setLiaisonInstitutionCenter(liaisonInstitutionManager + .getLiaisonInstitutionById(project.getProjectInfo().getLiaisonInstitutionCenter().getId())); + } else { + project.getProjecInfoPhase(this.getActualPhase()).setLiaisonInstitutionCenter(null); + } + + // Load the center Programs + project.setFlagshipValue(""); + project.setRegionsValue(""); + List programs = new ArrayList<>(); + for (ProjectFocus projectFocuses : project.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(phase) + && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() + && c.getCrpProgram().getCrp().getId().equals(this.getLoggedCrp().getId())) + .collect(Collectors.toList())) { + programs.add(projectFocuses.getCrpProgram()); + if (project.getFlagshipValue().isEmpty()) { + project.setFlagshipValue(projectFocuses.getCrpProgram().getId().toString()); + } else { + project + .setFlagshipValue(project.getFlagshipValue() + "," + projectFocuses.getCrpProgram().getId().toString()); + } + } + + List regions = new ArrayList<>(); + + for (ProjectFocus projectFocuses : project.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(phase) + && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue() + && c.getCrpProgram().getCrp().getId().equals(this.getLoggedCrp().getId())) + .collect(Collectors.toList())) { + regions.add(projectFocuses.getCrpProgram()); + if (project.getRegionsValue() != null && project.getRegionsValue().isEmpty()) { + project.setRegionsValue(projectFocuses.getCrpProgram().getId().toString()); + } else { + project + .setRegionsValue(project.getRegionsValue() + "," + projectFocuses.getCrpProgram().getId().toString()); + } + } + + List projectCenterOutcomes = new ArrayList<>(); + for (ProjectCenterOutcome projectCenterOutcome : project.getProjectCenterOutcomes().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(phase)) + .collect(Collectors.toList())) { + projectCenterOutcome.setCenterOutcome( + centerOutcomeManager.getResearchOutcomeById(projectCenterOutcome.getCenterOutcome().getId())); + projectCenterOutcomes.add(projectCenterOutcome); + } + project.setCenterOutcomes(projectCenterOutcomes); + project.setFlagships(programs); + project.setRegions(regions); + } + + liaisonInstitutions = new ArrayList(); + // load the liasons intitutions for the crp + liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream() + .filter(c -> c.isActive() && c.getCrpProgram() != null + && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + // load the flaghsips an regions + programFlagships = new ArrayList<>(); + regionFlagships = new ArrayList<>(); + programFlagships.addAll(loggedCrp.getCrpPrograms().stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + + programFlagships.sort((p1, p2) -> p1.getCenterComposedName().compareTo(p2.getCenterComposedName())); + + + centerOutcomes = new ArrayList<>(); + + for (CrpProgram crpProgram : project.getFlagships()) { + crpProgram = programManager.getCrpProgramById(crpProgram.getId()); + List centerTopics = new ArrayList<>( + crpProgram.getResearchTopics().stream().filter(rt -> rt.isActive()).collect(Collectors.toList())); + for (CenterTopic centerTopic : centerTopics) { + List centerOutcomesList = new ArrayList<>( + centerTopic.getResearchOutcomes().stream().filter(ro -> ro.isActive()).collect(Collectors.toList())); + for (CenterOutcome centerOutcome : centerOutcomesList) { + centerOutcomes.add(centerOutcome); + } + } + } + + regionFlagships.addAll(loggedCrp.getCrpPrograms().stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + + } + + projectDB = projectManager.getProjectById(projectID); + // adjust crp programs leader to enable only modify centersoutcomes. + if (this.isRole("CRP-Admin") || this.isRole("SuperAdmin")) { + canMapPrograms = true; + } + + // The base permission is established for the current section + + String params[] = {loggedCrp.getAcronym() + ""}; + this.setBasePermission(this.getText(Permission.SHARED_PROJECT_BASE_PERMISSION, params)); + + if (this.isHttpPost()) { + project.getProjecInfoPhase(this.getActualPhase()).setLiaisonInstitutionCenter(null); + project.setFlagshipValue(null); + project.setRegionsValue(null); + if (project.getCenterOutcomes() != null) { + project.getCenterOutcomes().clear(); + } + } + } + + + @Override + public String save() { + if (this.hasPermission("canEdit")) { + Phase sharedPhase = phaseManager.getPhaseById(sharedPhaseID); + + // Load basic info project to be saved + projectDB.setProjectInfo(projectDB.getProjecInfoPhase(sharedPhase)); + + project.setCreateDate(projectDB.getCreateDate()); + project.getProjectInfo().setPresetDate(projectDB.getProjectInfo().getPresetDate()); + + project.getProjectInfo().setStatus(projectDB.getProjectInfo().getStatus()); + + if (project.getProjectInfo().getLiaisonInstitutionCenter() != null) { + if (project.getProjectInfo().getLiaisonInstitutionCenter().getId() == -1) { + project.getProjectInfo().setLiaisonInstitutionCenter(null); + } + } + + // Saving the flaghsips + if (project.getFlagshipValue() != null && project.getFlagshipValue().length() > 0) { + + List fpsPreview = projectDB.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) + && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() + && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) + .collect(Collectors.toList()); + for (ProjectFocus projectFocus : fpsPreview) { + if (!project.getFlagshipValue().contains(projectFocus.getCrpProgram().getId().toString())) { + projectFocusManager.deleteProjectFocus(projectFocus.getId()); + } + } + + for (String programID : project.getFlagshipValue().trim().split(",")) { + if (programID.length() > 0) { + CrpProgram program = + programManager.getCrpProgramById(Long.parseLong(programID.trim().replaceAll("[^0-9]", ""))); + ProjectFocus projectFocus = new ProjectFocus(); + projectFocus.setCrpProgram(program); + projectFocus.setProject(projectDB); + + projectFocus.setPhase(sharedPhase); + if (projectDB.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getCrpProgram().getId().longValue() == program.getId().longValue() + && c.getPhase().equals(sharedPhase)) + .collect(Collectors.toList()).isEmpty()) { + projectFocus.setPhase(sharedPhase); + projectFocusManager.saveProjectFocus(projectFocus); + } + } + + } + } else { + // Delete All flagships + for (ProjectFocus projectFocus : projectDB.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) + && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() + && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) + .collect(Collectors.toList())) { + projectFocusManager.deleteProjectFocus(projectFocus.getId()); + } + } + + + // Saving the regions + if (project.getRegionsValue() != null && project.getRegionsValue().length() > 0) { + + List regionsPreview = projectDB.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) + && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue() + && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) + .collect(Collectors.toList()); + for (ProjectFocus projectFocus : regionsPreview) { + if (!project.getRegionsValue().contains(projectFocus.getCrpProgram().getId().toString())) { + projectFocusManager.deleteProjectFocus(projectFocus.getId()); + } + } + + for (String programID : project.getRegionsValue().trim().split(",")) { + if (programID.length() > 0) { + CrpProgram program = programManager.getCrpProgramById(Long.parseLong(programID.trim())); + ProjectFocus projectFocus = new ProjectFocus(); + projectFocus.setCrpProgram(program); + projectFocus.setProject(projectDB); + projectFocus.setPhase(sharedPhase); + if (projectDB.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) + && c.getCrpProgram().getId().longValue() == program.getId().longValue()) + .collect(Collectors.toList()).isEmpty()) { + projectFocus.setPhase(sharedPhase); + projectFocusManager.saveProjectFocus(projectFocus); + } + } + } + } else { + // Delete All Regions + for (ProjectFocus projectFocus : projectDB.getProjectFocuses().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase) + && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue() + && c.getCrpProgram().getCrp().getId().equals(loggedCrp.getId())) + .collect(Collectors.toList())) { + projectFocusManager.deleteProjectFocus(projectFocus.getId()); + } + } + + + // Saving Project Center Outcomes + if (project.getCenterOutcomes() != null && !project.getCenterOutcomes().isEmpty()) { + // Removing Project Center Outcomes + for (ProjectCenterOutcome projectCenterOutcome : projectDB.getProjectCenterOutcomes().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase)) + .collect(Collectors.toList())) { + if (!project.getCenterOutcomes().contains(projectCenterOutcome)) { + projectCenterOutcomeManager.deleteProjectCenterOutcome(projectCenterOutcome.getId()); + } + } + // Add Project Center Outcomes + for (ProjectCenterOutcome projectCenterOutcome : project.getCenterOutcomes()) { + if (projectCenterOutcome.getId() == null) { + projectCenterOutcome.setProject(project); + projectCenterOutcome.setPhase(sharedPhase); + projectCenterOutcome = projectCenterOutcomeManager.saveProjectCenterOutcome(projectCenterOutcome); + // This add centerOutcome to generate correct auditlog. + project.getProjectCenterOutcomes().add(projectCenterOutcome); + } + } + + } else { + // Removing All Project Center Outcomes + for (ProjectCenterOutcome projectCenterOutcome : projectDB.getProjectCenterOutcomes().stream() + .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(sharedPhase)) + .collect(Collectors.toList())) { + projectCenterOutcomeManager.deleteProjectCenterOutcome(projectCenterOutcome.getId()); + } + } + + + project.getProjectInfo().setCofinancing(projectDB.getProjectInfo().isCofinancing()); + + List relationsName = new ArrayList<>(); + relationsName.add(APConstants.PROJECT_FOCUSES_RELATION); + relationsName.add(APConstants.PROJECT_CLUSTER_ACTIVITIES_RELATION); + relationsName.add(APConstants.PROJECT_SCOPES_RELATION); + relationsName.add(APConstants.PROJECT_INFO_RELATION); + + project.getProjectInfo().setPhase(sharedPhase); + project.getProjectInfo().setProject(project); + project.getProjectInfo().setReporting(projectDB.getProjectInfo().getReporting()); + project.getProjectInfo().setAdministrative(projectDB.getProjectInfo().getAdministrative()); + project.getProjectInfo().setLocationRegional(projectDB.getProjectInfo().getLocationRegional()); + project.getProjectInfo().setLocationGlobal(projectDB.getProjectInfo().getLocationGlobal()); + project.getProjectInfo().setLocationRegional(projectDB.getProjectInfo().getLocationRegional()); + project.getProjectInfo().setLiaisonInstitution(projectDB.getProjectInfo().getLiaisonInstitution()); + + project.getProjectInfo().setModificationJustification(this.getJustification()); + project.getProjectInfo().setActiveSince(new Date()); + projectInfoManager.saveProjectInfo(project.getProjectInfo()); + + // Saving project and add relations we want to save on the history + + // List relationsName = new ArrayList<>(); + // relationsName.add(APConstants.PROJECT_FOCUSES_RELATION); + // relationsName.add(APConstants.PROJECT_INFO_RELATION); + // /** + // * The following is required because we need to update something on the @Project if we want a row created in + // the + // * auditlog table. + // */ + this.setModificationJustification(project); + projectManager.saveProject(project, this.getActionName(), relationsName, sharedPhase); + + Path path = this.getAutoSaveFilePath(sharedPhase); + // delete the draft file if exists + if (path.toFile().exists()) { + path.toFile().delete(); + } + + // check if there is a url to redirect + if (this.getUrl() == null || this.getUrl().isEmpty()) { + // check if there are missing field + if (!this.getInvalidFields().isEmpty()) { + this.setActionMessages(null); + // this.addActionMessage(Map.toString(this.getInvalidFields().toArray())); + List keys = new ArrayList(this.getInvalidFields().keySet()); + for (String key : keys) { + this.addActionMessage(key + ": " + this.getInvalidFields().get(key)); + } + } else { + this.addActionMessage("message:" + this.getText("saving.saved")); + } + } + + return SUCCESS; + } else + + { + return NOT_AUTHORIZED; + } + + } + + public void setCanMapPrograms(boolean canMapPrograms) { + this.canMapPrograms = canMapPrograms; + } + + public void setCenterOutcomes(List centerOutcomes) { + this.centerOutcomes = centerOutcomes; + } + + public void setCenterPrograms(List centerPrograms) { + this.centerPrograms = centerPrograms; + } + + public void setLiaisonInstitutions(List liaisonInstitutions) { + this.liaisonInstitutions = liaisonInstitutions; + } + + public void setLoggedCrp(GlobalUnit loggedCrp) { + this.loggedCrp = loggedCrp; + } + + public void setProgramFlagships(List programFlagships) { + this.programFlagships = programFlagships; + } + + public void setProject(Project project) { + this.project = project; + } + + public void setProjectID(long projectID) { + this.projectID = projectID; + } + + public void setRegionFlagships(List regionFlagships) { + this.regionFlagships = regionFlagships; + } + + public void setRegionPrograms(List regionPrograms) { + this.regionPrograms = regionPrograms; + } + + public void setSharedPhaseID(long sharedPhaseID) { + this.sharedPhaseID = sharedPhaseID; + } + + public void setTransaction(String transaction) { + this.transaction = transaction; + } + + @Override + public void validate() { + // if is saving call the validator to check for the missing fields + if (save) { + validator.validate(this, project, true, sharedPhaseID); + } + } + +} diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectDescriptionAction.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectDescriptionAction.java index a9d00e2d05..9acb743135 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectDescriptionAction.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/projects/ProjectDescriptionAction.java @@ -126,6 +126,7 @@ public class ProjectDescriptionAction extends BaseAction { private CenterOutcomeManager centerOutcomeManager; private LiaisonUserManager liaisonUserManager; private HistoryComparator historyComparator; + private CrpProgramManager crpProgramManager; private List centerPrograms; private List regionPrograms; @@ -173,7 +174,8 @@ public ProjectDescriptionAction(APConfig config, ProjectManager projectManager, CrpClusterOfActivityManager crpClusterOfActivityManager, LocElementTypeManager locationManager, ProjectScopeManager projectLocationManager, HistoryComparator historyComparator, ProjectInfoManager projectInfoManagerManager, GlobalUnitProjectManager globalUnitProjectManager, - CenterOutcomeManager centerOutcomeManager, ProjectCenterOutcomeManager projectCenterOutcomeManager) { + CenterOutcomeManager centerOutcomeManager, ProjectCenterOutcomeManager projectCenterOutcomeManager, + CrpProgramManager crpProgramManager) { super(config); this.projectManager = projectManager; this.projectInfoManagerManager = projectInfoManagerManager; @@ -197,6 +199,7 @@ public ProjectDescriptionAction(APConfig config, ProjectManager projectManager, this.globalUnitProjectManager = globalUnitProjectManager; this.projectCenterOutcomeManager = projectCenterOutcomeManager; this.centerOutcomeManager = centerOutcomeManager; + this.crpProgramManager = crpProgramManager; } /** @@ -618,6 +621,7 @@ public void prepare() throws Exception { project.setFlagshipValue(""); project.setRegionsValue(""); List programs = new ArrayList<>(); + for (ProjectFocus projectFocuses : project.getProjectFocuses().stream() .filter(c -> c.isActive() && c.getPhase() != null && c.getPhase().equals(this.getActualPhase()) && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue() @@ -697,13 +701,29 @@ public void prepare() throws Exception { allOwners = new ArrayList(); // load the liason users for the crp - allOwners.addAll(loggedCrp.getLiasonUsers()); + if (this.isCenterGlobalUnit()) { + if (!this.getActualPhase().getCrp().isCenterType()) { + allOwners.addAll(this.getActualPhase().getCrp().getLiasonUsers()); + } else { + allOwners.addAll(loggedCrp.getLiasonUsers()); + } + } else { + allOwners.addAll(loggedCrp.getLiasonUsers()); + } + liaisonInstitutions = new ArrayList(); if (this.isCenterGlobalUnit()) { - liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream() - .filter(c -> c.isActive() && c.getCrpProgram() != null - && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) - .collect(Collectors.toList())); + // dperez 2019-11-20 + if (!this.getActualPhase().getCrp().isCenterType()) { + liaisonInstitutions.addAll(this.getActualPhase().getCrp().getLiaisonInstitutions().stream() + .filter(c -> c.isActive() && c.getCrpProgram() != null).collect(Collectors.toList())); + } else { + liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream() + .filter(c -> c.isActive() && c.getCrpProgram() != null + && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + } + } else { if (this.hasSpecificities(APConstants.CRP_PPA_ENABLE_PROJECT_DESCRIPTION)) { liaisonInstitutions @@ -738,9 +758,26 @@ public void prepare() throws Exception { // load the flaghsips an regions programFlagships = new ArrayList<>(); regionFlagships = new ArrayList<>(); - programFlagships.addAll(loggedCrp.getCrpPrograms().stream() - .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) - .collect(Collectors.toList())); + if (this.isCenterGlobalUnit()) { + if (!this.getActualPhase().getCrp().isCenterType()) { + List crpProgramList = crpProgramManager.findAll(); + crpProgramList = crpProgramList.stream() + .filter(c -> c.getCrp().getId().longValue() == this.getActualPhase().getCrp().getId().longValue()) + .collect(Collectors.toList()); + programFlagships.addAll(crpProgramList.stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + } else { + programFlagships.addAll(loggedCrp.getCrpPrograms().stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + } + } else { + programFlagships.addAll(loggedCrp.getCrpPrograms().stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + } + programFlagships.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); clusterofActivites = new ArrayList<>(); @@ -751,10 +788,28 @@ public void prepare() throws Exception { } // add regions programs - regionFlagships.addAll(loggedCrp.getCrpPrograms().stream() - .filter(c -> c.isActive() && c.getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue()) - .collect(Collectors.toList())); - regionFlagships.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); + if (this.isCenterGlobalUnit()) { + if (!this.getActualPhase().getCrp().isCenterType()) { + List crpProgramList = crpProgramManager.findAll(); + crpProgramList = crpProgramList.stream() + .filter(c -> c.getCrp().getId().longValue() == this.getActualPhase().getCrp().getId().longValue()) + .collect(Collectors.toList()); + regionFlagships.addAll(crpProgramList.stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + regionFlagships.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); + } else { + regionFlagships.addAll(loggedCrp.getCrpPrograms().stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + regionFlagships.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); + } + } else { + regionFlagships.addAll(loggedCrp.getCrpPrograms().stream() + .filter(c -> c.isActive() && c.getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue()) + .collect(Collectors.toList())); + regionFlagships.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym())); + } // Center Outcomes @@ -1070,6 +1125,11 @@ public String save() { projectCenterOutcome = projectCenterOutcomeManager.saveProjectCenterOutcome(projectCenterOutcome); // This add centerOutcome to generate correct auditlog. project.getProjectCenterOutcomes().add(projectCenterOutcome); + } else { + // update or reply info + ProjectCenterOutcome ProjectCenterOutcomeDB = + projectCenterOutcomeManager.getProjectCenterOutcomeById(projectCenterOutcome.getId()); + projectCenterOutcome = projectCenterOutcomeManager.saveProjectCenterOutcome(ProjectCenterOutcomeDB); } } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/superadmin/PartnerRequestAction.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/superadmin/PartnerRequestAction.java index dca95d4e03..4f1de84eec 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/superadmin/PartnerRequestAction.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/action/superadmin/PartnerRequestAction.java @@ -287,10 +287,14 @@ public void prepare() throws Exception { } else { this.countryOfficesList = new ArrayList<>(); } + this.countriesList = this.locElementManager.findAll().stream() .filter(c -> c.isActive() && c.getLocElementType().getId().longValue() == 2).collect(Collectors.toList()); - this.institutionTypesList = this.institutionTypeManager.findAll().stream() - .filter(it -> it.isActive() && !it.getOld()).collect(Collectors.toList()); + /* + * this.institutionTypesList = this.institutionTypeManager.findAll().stream() + * .filter(it -> it.isActive() && !it.getOld()).collect(Collectors.toList()); + */ + this.institutionTypesList = this.institutionTypeManager.findAllIATITypes(); this.countriesList.sort((p1, p2) -> p1.getName().compareTo(p2.getName())); } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/config/APConstants.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/config/APConstants.java index 8625d7502c..0c3d74d3a3 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/config/APConstants.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/config/APConstants.java @@ -612,6 +612,8 @@ public final class APConstants { public static final String CENTER_CRP_PHASE_YEAR = "center_crp_phase_year"; public static final String CENTER_CRP_PHASE_CYCLE = "center_crp_phase_cycle"; public static final String CENTER_CRP_PHASE = "center_crp_phase"; + public static final String CENTER_ADMIN = "CRP-Admin"; + public static final String CENTER_SUPER_ADMIN = "SuperAdmin"; public static final String CENTER_DELIVERABLE_ID = "deliverableID"; public static final String CENTER_PROGRAM_ID = "programID"; diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectExpenditureInterceptor.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectExpenditureInterceptor.java index 57128d2e24..97e07ed6aa 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectExpenditureInterceptor.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectExpenditureInterceptor.java @@ -127,9 +127,12 @@ void setPermissionParameters(ActionInvocation invocation) throws Exception { String params[] = {crp.getAcronym(), project.getId() + "", baseAction.getActionName().replaceAll(crp.getAcronym() + "/", "")}; if (baseAction.canAccessSuperAdmin() || baseAction.canEditCrpAdmin()) { - isAdmin = true; - canEdit = true; - editParameter = true; + if (!loggedCrp.isCenterType()) { + isAdmin = true; + canEdit = true; + editParameter = true; + } + } else { if (baseAction.getActualPhase().getDescription().equals(APConstants.REPORTING)) { diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectInterceptor.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectInterceptor.java index b5aa137dd2..4606519c19 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectInterceptor.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/interceptor/project/EditProjectInterceptor.java @@ -17,11 +17,13 @@ import org.cgiar.ccafs.marlo.action.BaseAction; import org.cgiar.ccafs.marlo.config.APConstants; +import org.cgiar.ccafs.marlo.data.manager.CrpProgramLeaderManager; import org.cgiar.ccafs.marlo.data.manager.GlobalUnitManager; import org.cgiar.ccafs.marlo.data.manager.GlobalUnitProjectManager; import org.cgiar.ccafs.marlo.data.manager.LiaisonUserManager; import org.cgiar.ccafs.marlo.data.manager.PhaseManager; import org.cgiar.ccafs.marlo.data.manager.ProjectManager; +import org.cgiar.ccafs.marlo.data.model.CrpProgramLeader; import org.cgiar.ccafs.marlo.data.model.GlobalUnit; import org.cgiar.ccafs.marlo.data.model.GlobalUnitProject; import org.cgiar.ccafs.marlo.data.model.Institution; @@ -29,6 +31,7 @@ import org.cgiar.ccafs.marlo.data.model.LiaisonUser; import org.cgiar.ccafs.marlo.data.model.Phase; import org.cgiar.ccafs.marlo.data.model.Project; +import org.cgiar.ccafs.marlo.data.model.ProjectFocus; import org.cgiar.ccafs.marlo.data.model.ProjectPartner; import org.cgiar.ccafs.marlo.data.model.ProjectSectionStatusEnum; import org.cgiar.ccafs.marlo.data.model.ProjectStatusEnum; @@ -68,15 +71,18 @@ public class EditProjectInterceptor extends AbstractInterceptor implements Seria private final PhaseManager phaseManager; private final GlobalUnitProjectManager globalUnitProjectManager; private final LiaisonUserManager liaisonUserManager; + private final CrpProgramLeaderManager crpProgramLeaderManager; @Inject public EditProjectInterceptor(ProjectManager projectManager, GlobalUnitManager crpManager, PhaseManager phaseManager, - GlobalUnitProjectManager globalUnitProjectManager, LiaisonUserManager liaisonUserManager) { + GlobalUnitProjectManager globalUnitProjectManager, LiaisonUserManager liaisonUserManager, + CrpProgramLeaderManager crpProgramLeaderManager) { this.projectManager = projectManager; this.crpManager = crpManager; this.phaseManager = phaseManager; this.globalUnitProjectManager = globalUnitProjectManager; this.liaisonUserManager = liaisonUserManager; + this.crpProgramLeaderManager = crpProgramLeaderManager; } @Override @@ -307,16 +313,63 @@ void setPermissionParameters(ActionInvocation invocation) throws Exception { } // Check if is a Shared project (Crp to Center) - if (!globalUnitProject.isOrigin()) { - canEdit = false; - if (actionName.equals(SharedProjectSectionStatusEnum.CENTER_MAPPING.getStatus())) { - if (baseAction.hasPermission(baseAction.generatePermission(Permission.SHARED_PROJECT_PERMISSION, params))) { + // to-do Change Logic to only has to edit program Leaders to modifiy this section. + /* + * if (!globalUnitProject.isOrigin()) { + * canEdit = false; + * if (actionName.equals(SharedProjectSectionStatusEnum.CENTER_MAPPING.getStatus())) { + * if (baseAction.hasPermission(baseAction.generatePermission(Permission.SHARED_PROJECT_PERMISSION, params))) { + * canEdit = true; + * } + * } + * } + */ + // Center + boolean isCenterProject = false; + if (loggedCrp.isCenterType()) { + isCenterProject = true; + if (!baseAction.isRole(APConstants.CENTER_ADMIN) && !baseAction.isRole(APConstants.CENTER_SUPER_ADMIN)) { + if (actionName.equals(SharedProjectSectionStatusEnum.CENTER_MAPPING.getStatus())) { + boolean isValidate = false; + for (ProjectFocus projectFocus : project.getProjectFocuses().stream() + .filter(c -> c.isActive() + && c.getPhase().getDescription().equals(baseAction.getActualPhase().getDescription()) + && c.getPhase().getYear() == baseAction.getActualPhase().getYear()) + .collect(Collectors.toList())) { + CrpProgramLeader crpProgramLeader = + crpProgramLeaderManager.getCrpProgramLeaderByProgram(projectFocus.getCrpProgram().getId().longValue(), + loggedCrp.getId().longValue(), baseAction.getCurrentUser().getId().longValue()); + if (crpProgramLeader != null) { + isValidate = true; + } + } + if (isValidate) { + canEdit = true; + editParameter = true; + } else { + canEdit = false; + } + } + } else { + if (actionName.equals(SharedProjectSectionStatusEnum.CENTER_MAPPING.getStatus())) { canEdit = true; + editParameter = true; + baseAction.setEditable(true); + baseAction.setEditStatus(true); + } else { + // check if project is from CRP shared or Center owner + if (baseAction.getActualPhase().getCrp().isCenterType()) { + canEdit = true; + editParameter = true; + baseAction.setEditable(true); + baseAction.setEditStatus(true); + } else { + canEdit = false; + editParameter = false; + } } } - } - if (!editParameter) { baseAction.setEditStatus(false); } @@ -327,13 +380,21 @@ void setPermissionParameters(ActionInvocation invocation) throws Exception { baseAction.setEditStatus(baseAction.isEditStatus() && globalUnitProject.isOrigin()); // Allow Superadmin edit - if (baseAction.canAccessSuperAdmin() && editParameter) { + if (baseAction.canAccessSuperAdmin() && editParameter && !isCenterProject) { baseAction.setEditableParameter(true); baseAction.setCanEdit(true); + baseAction.setEditable(true); baseAction.setEditStatus(true); } - - + // logic for superadmins in centers to allow only programs leaders AND CRP-Admin to modify + if (isCenterProject) { + if (canEdit && editParameter) { + baseAction.setEditableParameter(editParameter && canEdit && phase.getEditable()); + baseAction.setEditStatus(true); + } else { + baseAction.setEditableParameter(false); + } + } } else { throw new NullPointerException(); } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ARControlLists.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ARControlLists.java index fbf8958288..2c2121f0a5 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ARControlLists.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ARControlLists.java @@ -1,4 +1,5 @@ -/***************************************************************** +/** + * *************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO is free software: you can redistribute it and/or modify @@ -11,11 +12,13 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with MARLO. If not, see . - *****************************************************************/ - + * *************************************************************** + */ package org.cgiar.ccafs.marlo.rest.controller.v2.controllist; +import org.cgiar.ccafs.marlo.data.manager.RestApiAuditlogManager; import org.cgiar.ccafs.marlo.data.manager.UserManager; +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; import org.cgiar.ccafs.marlo.data.model.User; import org.cgiar.ccafs.marlo.rest.controller.v2.controllist.items.arcontrollists.BroadAreaItem; import org.cgiar.ccafs.marlo.rest.controller.v2.controllist.items.arcontrollists.BudgetTypeItem; @@ -59,6 +62,7 @@ import org.cgiar.ccafs.marlo.rest.errors.NotFoundException; import org.cgiar.ccafs.marlo.security.Permission; +import java.util.Date; import java.util.List; import javax.inject.Inject; @@ -119,6 +123,7 @@ public class ARControlLists { private BroadAreaItem broadAreaItem; private StatusOfResponseItem statusOfResponseItem; private MilestoneStatusItem milestoneStatusItem; + private RestApiAuditlogManager restApiAuditlogManager; private CrpGeoLocationMapItem crpGeoLocationMapItem; @Autowired @@ -140,7 +145,8 @@ public ARControlLists(CrossCuttingMarkerScoreItem crossCuttingMa TagItem tagItem, PartnershipMainAreaItem partnershipMainAreaItem, BudgetTypeItem bugdetTypeItem, BroadAreaItem broadAreaItem, StatusOfResponseItem statusOfResponseItem, MilestoneStatusItem milestoneStatusItem, - CrpGeoLocationMapItem crpGeoLocationMapItem, UserManager userManager) { + RestApiAuditlogManager restApiAuditlogManager, UserManager userManager, + CrpGeoLocationMapItem crpGeoLocationMapItem) { this.crossCuttingMarkerScoreItem = crossCuttingMarkerScoreItem; this.innovationTypesItem = innovationTypesItem; this.researchPartnershipsItem = researchPartnershipsItem; @@ -160,8 +166,9 @@ public ARControlLists(CrossCuttingMarkerScoreItem crossCuttingMa this.broadAreaItem = broadAreaItem; this.statusOfResponseItem = statusOfResponseItem; this.milestoneStatusItem = milestoneStatusItem; - this.crpGeoLocationMapItem = crpGeoLocationMapItem; + this.restApiAuditlogManager = restApiAuditlogManager; this.userManager = userManager; + this.crpGeoLocationMapItem = crpGeoLocationMapItem; } @ApiOperation(tags = {"${ARControlLists.budget-types.all.value}"}, @@ -208,7 +215,7 @@ public ResponseEntity deleteBudgetTypesByFinancialCode( /** * Find a Broad Area by id - * + * * @param id * @return a BroadAreaDTO with the Broad Area data. */ @@ -230,7 +237,7 @@ public ResponseEntity findBroadAreaById( /** * Find a Budget Type by id - * + * * @param id * @return a BudgetTypeDTO with the Budget Type data. */ @@ -250,7 +257,7 @@ public ResponseEntity findBudgetTypeById( /** * Find a Cross Cutting Marker by id - * + * * @param id * @return a CrossCuttingMarkerScoreDTO with the Cross Cutting Marker data. */ @@ -267,13 +274,20 @@ public ResponseEntity findBudgetTypeById( ResponseEntity response = this.crossCuttingMarkerItem.findCrossCuttingMarkerById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.cross-cutting-markers.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List cross-cutting-markers", "LIST cross-cutting-markers, Code: " + code, + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.CgiarCrossCuttingMarker", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } /** * Find a Cross Cutting Marker score by id - * + * * @param id * @return a CrossCuttingMarkerDTO with the Cross Cutting Marker data. */ @@ -289,17 +303,23 @@ public ResponseEntity findBudgetTypeById( this.crossCuttingMarkerScoreItem.findCrossCuttingMarkerScoreById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.cross-cutting-marker-scores.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List cross-cutting-marker-scores", + "LIST cross-cutting-marker-scores, Code: " + code, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.RepIndGenderYouthFocusLevel", "N/A", this.getCurrentUser().getId(), + null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } /** * Find a Innovation Type requesting by id - * + * * @param id * @return a InnovationTypesDTO with the Innovation Type data. */ - @ApiOperation(tags = "Table 4 - CRP Innovations", value = "${ARControlLists.innovation-types.code.value}", response = InnovationTypeDTO.class) @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @@ -310,6 +330,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.innovationTypesItem.findInnovationTypeById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.innovation-types.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List innovation-types", "LIST innovation-types, Code: " + code, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.RepIndInnovationType", "N/A", this.getCurrentUser().getId(), null, "", + null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } @@ -317,7 +344,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a Maturity of Change requesting by id - * + * * @param id * @return a MaturityOfChangeDTO with the Maturity of Change data. */ @@ -332,6 +359,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.maturityOfChangeItem.findMaturityOfChangeById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.maturities-of-change.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List maturities-of-change", "LIST maturities-of-change, Code: " + code, + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndStageStudy", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -339,7 +373,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a Milestone status by id - * + * * @param id * @return a MilestoneStatusDTO with the Milestone Status data. */ @@ -356,13 +390,19 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.milestoneStatusItem.findMilestoneStatusById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.milestone-statuses.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List milestone-statuses", + "LIST milestone-statuses, Code: " + code, new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.GeneralStatus", + "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } /** * Find a Organization Type requesting by id - * + * * @param id * @return a OrganizationTypeDTO with the Organization Type data. */ @@ -377,6 +417,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.organizationTypeItem.findOrganizationTypeById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.organization-types.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List organization-types", "LIST organization-types, Code: " + code, new Date(), + 0, "class org.cgiar.ccafs.marlo.data.model.RepIndOrganizationType", "N/A", this.getCurrentUser().getId(), + null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -384,7 +431,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a partnership Main Area by id - * + * * @param id * @return a PartnershipMainAreaDTO with the partnership Main Area */ @@ -399,6 +446,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.partnershipMainAreaItem.findPartnershipMainAreaById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.partnership-main-areas.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List partnership-main-areas", "LIST partnership-main-areas, Code: " + code, + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndPartnershipMainArea", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -406,7 +460,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a Policy Investment type by id - * + * * @param id * @return a policyInvestmentTypeDTO with the Cross Cutting Marker data. */ @@ -421,6 +475,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.policyInvestmentTypeItem.PolicyInvestmentTypeById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.policy-investment-types.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List policy-investment-types", "LIST policy-investment-types, Code: " + code, + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndPolicyInvestimentType", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -428,7 +489,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a Policy Level of Maturity by id - * + * * @param id * @return a PolicyLevelOfMaturityDTO with Policy Level of Maturity data. */ @@ -443,6 +504,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.policyMaturityLevelItem.PolicyMaturityLevelById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.policy-maturity-levels.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List policy-maturity-levels", "LIST policy-maturity-levels, Code: " + code, + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndStageProcess", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -450,7 +518,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a policy owner type by id - * + * * @param id * @return a PolicyOwnerTypeDTO with the policy owner type */ @@ -465,6 +533,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.policyOwnerTypeItem.findPolicyOwnerTypeById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.policy-owner-types.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List policy-owner-types", "LIST policy-owner-types, Code: " + code, new Date(), + 0, "class org.cgiar.ccafs.marlo.data.model.RepIndPolicyType", "N/A", this.getCurrentUser().getId(), null, "", + null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -472,7 +547,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a Stage of Innovation requesting by id - * + * * @param id * @return a StageOfInnovationDTO with the Stage of Innovation data. */ @@ -487,6 +562,13 @@ public ResponseEntity findInnovationTypeById( ResponseEntity response = this.stageOfInnovationItem.findStageOfInnovationById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.stage-of-innovations.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List stage-of-innovations", "LIST stage-of-innovations, Code: " + code, + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndStageInnovation", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -494,7 +576,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a Status of response by id - * + * * @param id * @return a StatusOfResponseDTO with the Status of response data. */ @@ -517,7 +599,7 @@ public ResponseEntity findInnovationTypeById( /** * Find a study Type by id - * + * * @param id * @return a CStudyTypeDTO with the study Type data. */ @@ -531,6 +613,12 @@ public ResponseEntity findStudyTypeById( ResponseEntity response = this.studyTypeItem.findStudyTypeById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.study-types.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List study-types", "LIST study-types, Code: " + code, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.StudyType", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -538,7 +626,7 @@ public ResponseEntity findStudyTypeById( /** * Find a Tag requesting by id - * + * * @param id * @return a TagDTO with the Tag data. */ @@ -551,6 +639,12 @@ public ResponseEntity findStudyTypeById( ResponseEntity response = this.tagItem.findTagById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ARControlLists.tags.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List tags", "LIST tags, Code: " + code, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.EvidenceTag", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -558,10 +652,9 @@ public ResponseEntity findStudyTypeById( /** * Get All the Broad Area items - * + * * @return a List of BroadArea with all Cross Cutting Markers Items. */ - @ApiOperation(tags = {"Table 12 - Examples of W1/2 Use"}, value = "${ARControlLists.broad-areas.all.value}", response = BroadAreaDTO.class, responseContainer = "List") @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @@ -572,11 +665,10 @@ public List getAllBroadAreas() { /** * Get All the Budget types items - * + * * @return a List of CrossCuttingMarkersDTO with all Cross Cutting Markers * Items. */ - @ApiOperation(tags = {"Table 13 - CRP Financial Report"}, value = "${ARControlLists.budget-types.all.value}", response = BudgetTypeDTO.class, responseContainer = "List") @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @@ -597,7 +689,7 @@ public List getAllBudgetTypesCGIAR() { /** * Get All the cross cutting markers of CRP Items * - * + * * @return a List of cross cutting markers */ @ApiOperation(tags = {"Table 2 - CRP Policies", "Table 3 - Outcome/ Impact Case Reports"}, @@ -607,16 +699,21 @@ public List getAllBudgetTypesCGIAR() { @RequestMapping(value = "/cross-cutting-markers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllCrossCuttingMarkers() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List cross-cutting-markers", + "LIST cross-cutting-markers", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.CgiarCrossCuttingMarker", + "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.crossCuttingMarkerItem.getAllCrossCuttingMarker(); } /** * Get All the Cross Cutting Markers items - * + * * @return a List of CrossCuttingMarkersDTO with all Cross Cutting Markers * Items. */ - @ApiOperation(tags = {"Table 2 - CRP Policies", "Table 3 - Outcome/ Impact Case Reports"}, value = "${ARControlLists.cross-cutting-marker-scores.all.value}", response = CrossCuttingMarkerScoreDTO.class, responseContainer = "List") @@ -624,12 +721,19 @@ public List getAllCrossCuttingMarkers() { @RequestMapping(value = "/cross-cutting-marker-scores", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllCrossCuttingMarkerScores() { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List cross-cutting-marker-scores", "LIST cross-cutting-marker-scores", new Date(), + 0, "class org.cgiar.ccafs.marlo.data.model.RepIndGenderYouthFocusLevel", "N/A", this.getCurrentUser().getId(), + null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.crossCuttingMarkerScoreItem.getAllCrossCuttingMarkersScores(); } /** * Get All the Innovation Types items - * + * * @return a List of InnovationTypesDTO with all Innovation Types Items. */ @ApiOperation(tags = "Table 4 - CRP Innovations", value = "${ARControlLists.innovation-types.all.value}", @@ -637,15 +741,20 @@ public List getAllCrossCuttingMarkerScores() { @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/innovation-types", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllInnovationTypes() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List innovation-types", "LIST innovation-types", + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndInnovationType", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.innovationTypesItem.getAllInnovationTypes(); } /** * Get All the Maturity of Change Items * - * + * * @return a List of MaturityOfChangeDTO with all Maturity of Change Items. */ - @ApiOperation(tags = "Table 3 - Outcome/ Impact Case Reports", value = "${ARControlLists.maturities-of-change.all.value}", response = MaturityOfChangeDTO.class, responseContainer = "List") @@ -653,15 +762,20 @@ public List getAllInnovationTypes() { @RequestMapping(value = "/maturities-of-change", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllMaturityOfChanges() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List maturities-of-change", + "LIST maturities-of-change", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndStageStudy", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.maturityOfChangeItem.getAllMaturityOfChanges(); } /** * Get All the milestone Statuses items - * + * * @return a List of MilestoneStatusDTO with all Milestone Statuses Items. */ - @ApiOperation(tags = {"Table 5 - Status of Planned Outcomes and Milestones"}, value = "${ARControlLists.milestone-statuses.all.value}", response = MilestoneStatusDTO.class, responseContainer = "List") @@ -669,12 +783,18 @@ public List getAllMaturityOfChanges() { @RequestMapping(value = "/milestone-statuses", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllMilestoneStatuses() { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List milestone-statuses", "LIST milestone-statuses", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.GeneralStatus", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.milestoneStatusItem.getAllMilestoneStatus(); } /** * Get All the Stage of Innovations items - * + * * @return a List of StageOfInnovationDTO with all RepIndStageInnovation * Items. */ @@ -684,12 +804,18 @@ public List getAllMilestoneStatuses() { @RequestMapping(value = "/organization-types", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllOrganizationTypes() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List organization-types", + "LIST organization-types", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndOrganizationType", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.organizationTypeItem.getAllOrganizationTypes(); } /** * Get All the cross cutting markers of CRP Items * - * + * * @return a List of cross cutting markers */ @ApiOperation(tags = {"Table 8 - Key external partnerships"}, @@ -699,12 +825,18 @@ public List getAllOrganizationTypes() { @RequestMapping(value = "/partnership-main-areas", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllPartnershipMainArea() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List partnership-main-areas", + "LIST partnership-main-areas", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndPartnershipMainArea", + "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.partnershipMainAreaItem.getAllPartnershipMainAreas(); } /** * get all policy investiment types - * + * * @return a List of policyInvestmentTypeDTO with all * RepIndPolicyInvestimentType Items. */ @@ -714,28 +846,40 @@ public List getAllPartnershipMainArea() { @RequestMapping(value = "/policy-investment-types", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllPolicyInvestmentType() { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("AR Control List policy-investment-types", "LIST policy-investment-types", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.RepIndPolicyInvestimentType", "N/A", this.getCurrentUser().getId(), + null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.policyInvestmentTypeItem.getAllPolicyInvestmentType(); } /** * Get All the Policy level of maturity items - * + * * @return a List of PolicyLevelOfMaturityDTO with all olicy level of * maturity Items. */ - @ApiOperation(tags = "Table 2 - CRP Policies", value = "${ARControlLists.policy-maturity-levels.all.value}", response = PolicyMaturityLevelDTO.class, responseContainer = "List") @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/policy-maturity-levels", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllPolicyMaturityLevels() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List policy-maturity-levels", + "LIST policy-maturity-levels", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndStageProcess", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.policyMaturityLevelItem.getAllPolicyMaturityLevel(); } /** * Get All the policy owner types - * + * * @return a List of PolicyOwnerTypeDTO with all the policy owner types */ @ApiOperation(tags = "Table 2 - CRP Policies", value = "${ARControlLists.policy-owner-types.all.value}", @@ -744,12 +888,18 @@ public List getAllPolicyMaturityLevels() { @RequestMapping(value = "/policy-owner-types", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllPolicyOwnerTypes() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List policy-owner-types", + "LIST policy-owner-types", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndPolicyType", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.policyOwnerTypeItem.getAllPolicyOwnerTypes(); } /** * Get All the Stage of Innovations items - * + * * @return a List of StageOfInnovationDTO with all RepIndStageInnovation * Items. */ @@ -759,15 +909,20 @@ public List getAllPolicyOwnerTypes() { @RequestMapping(value = "/stage-of-innovations", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllStageOfInnovations() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List stage-of-innovations", + "LIST stage-of-innovations", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndStageInnovation", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.stageOfInnovationItem.getAllStageOfInnovations(); } /** * Get All the Status of response Items * - * + * * @return a List of StatusOfResponseDTO with all Status of response Items. */ - @ApiOperation(tags = "Table 11 - Update on Actions Taken in Response to Relevant Evaluations", value = "${ARControlLists.status-of-response.all.value}", response = StatusOfResponseDTO.class, responseContainer = "List") @@ -780,7 +935,7 @@ public List getAllStatusOfResponse() { /** * Get All the Study types items - * + * * @return a List of StudyTypesDTO with all Study types items */ @ApiOperation(tags = "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)", @@ -788,12 +943,17 @@ public List getAllStatusOfResponse() { @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/study-types", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllStudyTypes() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List study-types", "LIST study-types", new Date(), + 0, "class org.cgiar.ccafs.marlo.data.model.StudyType", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.studyTypeItem.getAllStudyTypes(); } /** * Get All tags Items * - * + * * @return a List of TagDTO with all tags Items. */ @ApiOperation(tags = "Table 3 - Outcome/ Impact Case Reports", value = "${ARControlLists.tags.all.value}", @@ -801,6 +961,11 @@ public List getAllStudyTypes() { @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/tags", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllTags() { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("AR Control List tags", "LIST tags", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.EvidenceTag", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.tagItem.getAllTags(); } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/FinancialSummary.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/FinancialSummary.java new file mode 100644 index 0000000000..064f838368 --- /dev/null +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/FinancialSummary.java @@ -0,0 +1,141 @@ +/***************************************************************** + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). + * MARLO is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * at your option) any later version. + * MARLO is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with MARLO. If not, see . + *****************************************************************/ + +/************** + * @author Diego Perez - CIAT/CCAFS + **************/ + +package org.cgiar.ccafs.marlo.rest.controller.v2.controllist; + +import org.cgiar.ccafs.marlo.data.manager.UserManager; +import org.cgiar.ccafs.marlo.data.model.User; +import org.cgiar.ccafs.marlo.rest.controller.v2.controllist.items.FinancialSumary.FinancialSummaryItem; +import org.cgiar.ccafs.marlo.rest.dto.FinancialSumaryDTO; +import org.cgiar.ccafs.marlo.rest.dto.NewFinancialSummaryDTO; +import org.cgiar.ccafs.marlo.rest.errors.NotFoundException; +import org.cgiar.ccafs.marlo.security.Permission; + +import javax.validation.Valid; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.apache.shiro.subject.Subject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Api(tags = "Table 13 - CRP Financial Report") +public class FinancialSummary { + + private static final Logger LOG = LoggerFactory.getLogger(FinancialSummary.class); + @Autowired + private Environment env; + private final UserManager userManager; + private FinancialSummaryItem financialSummaryItem; + + public FinancialSummary(UserManager userManager, FinancialSummaryItem financialSummaryItem) { + super(); + this.financialSummaryItem = financialSummaryItem; + this.userManager = userManager; + } + + @ApiOperation(tags = {"Table 13 - CRP Financial Report"}, value = "${FinancialSummary.Example.POST.value}", + response = FinancialSumaryDTO.class) + @RequiresPermissions(Permission.FULL_CREATE_REST_API_PERMISSION) + @RequestMapping(value = "/{CGIAREntity}/FinancialSummary", method = RequestMethod.POST, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity createFinancialSummary( + @ApiParam(value = "${FinancialSummary.Example.POST.param.CGIAR}", required = true) @PathVariable String CGIAREntity, + @ApiParam(value = "${FinancialSummary.Example.POST.param.financialmodel}", + required = true) @Valid @RequestBody NewFinancialSummaryDTO newFinancialSummaryDTO) { + Long financialSummaryId = + financialSummaryItem.createFinancialSummary(newFinancialSummaryDTO, CGIAREntity, this.getCurrentUser()); + ResponseEntity response = new ResponseEntity(financialSummaryId, HttpStatus.OK); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("Expenditure.Example.GET.id.404")); + } + return response; + } + + @ApiOperation(tags = {"Table 13 - CRP Financial Report"}, value = "${FinancialSummary.Example.GET.value}", + response = FinancialSumaryDTO.class) + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/{CGIAREntity}/FinancialSumamary", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity findFinancialSummaryById( + @ApiParam(value = "${FinancialSummary.Example.GET.param.CGIAR}", required = true) @PathVariable String CGIAREntity, + @ApiParam(value = "${FinancialSummary.Example.GET.year.value}", required = true) @RequestParam Integer year, + @ApiParam(value = "${FinancialSummary.Example.GET.phase.value}", required = true) @RequestParam String phase) { + + ResponseEntity response = null; + try { + response = this.financialSummaryItem.findFinancialSumaryList(CGIAREntity, year, phase, this.getCurrentUser()); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("Expenditure.Example.GET.id.404")); + } + } catch (Exception e) { + LOG.trace("Error findFinancialSummaryById"); + e.printStackTrace(); + } + return response; + } + + private User getCurrentUser() { + Subject subject = SecurityUtils.getSubject(); + Long principal = (Long) subject.getPrincipal(); + User user = this.userManager.getUser(principal); + return user; + } + + @ApiOperation(tags = {"Table 13 - CRP Financial Report"}, value = "${FinancialSummary.Example.PUT.value}", + response = FinancialSumaryDTO.class) + @RequiresPermissions(Permission.FULL_CREATE_REST_API_PERMISSION) + @RequestMapping(value = "/{CGIAREntity}/FinancialSummary/{id}", method = RequestMethod.PUT, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity updateFinancialSummary( + @ApiParam(value = "${FinancialSummary.Example.PUT.param.CGIAR}", required = true) @PathVariable String CGIAREntity, + @ApiParam(value = "${FinancialSummary.Example.PUT.param.financialmodel}", + required = true) @Valid @RequestBody NewFinancialSummaryDTO newFinancialSummaryDTO) + throws Exception { + Long financialSummaryId = null; + try { + financialSummaryId = + financialSummaryItem.updateFinancialSummary(newFinancialSummaryDTO, CGIAREntity, this.getCurrentUser()); + } catch (Exception e) { + e.printStackTrace(); + } + + ResponseEntity response = new ResponseEntity(financialSummaryId, HttpStatus.OK); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("FinancialSummary.Example.GET.id.404")); + } + return response; + } + +} diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/GeneralLists.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/GeneralLists.java index a53867fcb3..cd348d34fe 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/GeneralLists.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/GeneralLists.java @@ -15,7 +15,9 @@ package org.cgiar.ccafs.marlo.rest.controller.v2.controllist; +import org.cgiar.ccafs.marlo.data.manager.RestApiAuditlogManager; import org.cgiar.ccafs.marlo.data.manager.UserManager; +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; import org.cgiar.ccafs.marlo.data.model.User; import org.cgiar.ccafs.marlo.rest.controller.v2.controllist.items.generallists.FlagshipProgramItem; import org.cgiar.ccafs.marlo.rest.controller.v2.controllist.items.generallists.GeneralAcronymItem; @@ -35,6 +37,7 @@ import org.cgiar.ccafs.marlo.rest.errors.NotFoundException; import org.cgiar.ccafs.marlo.security.Permission; +import java.util.Date; import java.util.List; import javax.inject.Inject; @@ -79,6 +82,7 @@ public class GeneralLists { private GlobalUnitTypeItem globalUnitTypeItem; private FlagshipProgramItem flagshipProgramItem; private GeneralAcronymItem generalAcronymItem; + private RestApiAuditlogManager restApiAuditlogManager; @Autowired private Environment env; @@ -87,13 +91,14 @@ public class GeneralLists { public GeneralLists(LocationItem countryItem, GeographicScopeItem geographicScopeItem, GlobalUnitItem globalUnitItem, GlobalUnitTypeItem globalUnitTypeItem, FlagshipProgramItem flagshipProgramItem, GeneralAcronymItem generalAcronymItem, - UserManager userManager) { + RestApiAuditlogManager restApiAuditlogManager, UserManager userManager) { this.locationItem = countryItem; this.geographicScopeItem = geographicScopeItem; this.globalUnitItem = globalUnitItem; this.globalUnitTypeItem = globalUnitTypeItem; this.flagshipProgramItem = flagshipProgramItem; this.generalAcronymItem = generalAcronymItem; + this.restApiAuditlogManager = restApiAuditlogManager; this.userManager = userManager; } @@ -153,6 +158,12 @@ public ResponseEntity> findAcronymByAcronym( ResponseEntity> response = this.generalAcronymItem.findGeneralAcronymByAcronym(acronym); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.acronyms.acronym.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List acronyms", + "LIST cgiar-entities, Acronym: " + acronym, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.GeneralAcronym", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } @@ -176,6 +187,12 @@ public ResponseEntity findCountryByNumericISOCode( ResponseEntity response = this.locationItem.getContryByAlpha2ISOCode(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.countries.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List countries", "LIST countries, Code: " + code, + new Date(), response.getBody().getCode(), "class org.cgiar.ccafs.marlo.data.model.LocElement", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; @@ -200,6 +217,12 @@ public ResponseEntity findFlagshipProgramBySmoCode( ResponseEntity response = this.flagshipProgramItem.findFlagshipProgramBySmoCode(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.flagships-modules.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("General List flagships-modules", "LIST flagships-modules, Code: " + code, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.CrpProgram", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } @@ -223,6 +246,13 @@ public ResponseEntity findGeographicScopeById( ResponseEntity response = this.geographicScopeItem.findGeographicScopesById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.geographic-scopes.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("General List geographic-scopes", "LIST geographic-scopes, Code: " + code, new Date(), + response.getBody().getCode(), "class org.cgiar.ccafs.marlo.data.model.RepIndGeographicScope", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } @@ -252,6 +282,12 @@ public ResponseEntity findGeographicScopeById( ResponseEntity response = this.globalUnitItem.findGlobalUnitByCGIRARId(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.cgiar-entities.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("General List cgiar-entities", "LIST cgiar-entities, Code: " + code, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.GlobalUnit", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } @@ -270,6 +306,12 @@ public ResponseEntity findGlobalUnitTypeByCode( ResponseEntity response = this.globalUnitTypeItem.findGlobalUnitTypeById(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.cgiar-entity-types.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List ", "LIST cgiar-entities, Code: " + code, + new Date(), response.getBody().getCode(), "class org.cgiar.ccafs.marlo.data.model.GlobalUnitType", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } @@ -290,6 +332,12 @@ public ResponseEntity findtRegionByCode( ResponseEntity response = this.locationItem.getRegionByCode(code); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.un-regions.code.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List un-regions", "LIST un-regions, Code: " + code, + new Date(), response.getBody().getUM49Code(), "class org.cgiar.ccafs.marlo.data.model.LocElement", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } return response; } @@ -305,6 +353,12 @@ public ResponseEntity findtRegionByCode( @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/acronyms", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllAcronyms() { + + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List acronyms", "LIST acronyms", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.GeneralAcronym", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.generalAcronymItem.getAllGeneralAcronyms(); } @@ -321,6 +375,12 @@ public List getAllAcronyms() { @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/countries", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllContries() { + + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List countries", "LIST countries", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.LocElement", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.locationItem.getAllCountries(); } @@ -337,6 +397,13 @@ public List getAllContries() { @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/flagships-modules", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllFlagshipsPrograms() { + + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("General List flagships-modules", "LIST flagships-modules", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.CrpProgram", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.flagshipProgramItem.getAllCrpPrograms(); } @@ -355,6 +422,13 @@ public List getAllFlagshipsPrograms() { @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/geographic-scopes", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllGeographicScopes() { + + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List geographic-scopes", "LIST geographic-scopes", + new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.RepIndGeographicScope", "N/A", + this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.geographicScopeItem.getAllGeographicScopes(); } // (Optional) Entity type can be Center, CRP or Platform. Please refer to the entity-type control list. (edited) @@ -382,7 +456,14 @@ public ResponseEntity> getAllGlobalUnits( ResponseEntity> response = this.globalUnitItem.getAllGlobaUnits(typeId); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("GeneralLists.cgiar-entities.all.404")); + } else { + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("General List cgiar-entities", "LIST cgiar-entities, Type: " + typeId, new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.GlobalUnit", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); } + return response; } @@ -397,6 +478,13 @@ public ResponseEntity> getAllGlobalUnits( @RequestMapping(value = "/cgiar-entity-types", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllGlobalUnitTypes() { + + // Log Action + RestApiAuditlog restApiAuditLog = + new RestApiAuditlog("General List cgiar-entity-types", "LIST cgiar-entity-types", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.GlobalUnitType", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.globalUnitTypeItem.getAllGlobalUnitTypes(); } @@ -424,6 +512,12 @@ public ResponseEntity> getAllOneCGIARGlobalUnits() { @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) @RequestMapping(value = "/un-regions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public List getAllRegions() { + + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("General List un-regions", "LIST un-regions", new Date(), 0, + "class org.cgiar.ccafs.marlo.data.model.LocElement", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.locationItem.getAllRegions(); } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ImpactPathway.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ImpactPathway.java index 20f806a21e..6aed2d5576 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ImpactPathway.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/ImpactPathway.java @@ -28,7 +28,11 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.apache.shiro.subject.Subject; +import org.cgiar.ccafs.marlo.data.manager.UserManager; +import org.cgiar.ccafs.marlo.data.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -55,12 +59,14 @@ public class ImpactPathway { // private InstitutionItem institutionItem; - // private final UserManager userManager; + private final UserManager userManager; // @Inject - public ImpactPathway(OutcomeItem outcomeItem, MilestoneItem milestoneItem) { + public ImpactPathway(OutcomeItem outcomeItem, MilestoneItem milestoneItem, + UserManager userManager) { this.outcomeItem = outcomeItem; this.milestoneItem = milestoneItem; + this.userManager = userManager; } @ApiOperation(tags = {"Table 5 - Status of Planned Outcomes and Milestones"}, @@ -72,7 +78,7 @@ public ResponseEntity findMilestoneById( @ApiParam(value = "${ImpactPathway.milestones.id.param.CGIAR}", required = true) @PathVariable String CGIAREntity, @ApiParam(value = "${ImpactPathway.milestones.id.param.id}", required = true) @PathVariable String id, @ApiParam(value = "${ImpactPathway.milestones.id.param.year}", required = true) @RequestParam Integer year) { - ResponseEntity response = this.milestoneItem.findMilestoneById(id, CGIAREntity, year); + ResponseEntity response = this.milestoneItem.findMilestoneById(id, CGIAREntity, year, getCurrentUser()); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ImpactPathway.milestones.id.404")); } @@ -88,7 +94,7 @@ public ResponseEntity findOutcomeById( @ApiParam(value = "${ImpactPathway.outcomes.id.param.CGIAR}", required = true) @PathVariable String CGIAREntity, @ApiParam(value = "${ImpactPathway.outcomes.id.param.id}", required = true) @PathVariable String id, @ApiParam(value = "${ImpactPathway.outcomes.id.param.year}", required = true) @RequestParam Integer year) { - ResponseEntity response = this.outcomeItem.findOutcomeById(id, CGIAREntity, year); + ResponseEntity response = this.outcomeItem.findOutcomeById(id, CGIAREntity, year, getCurrentUser()); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new NotFoundException("404", this.env.getProperty("ImpactPathway.outcomes.id.404")); } @@ -110,7 +116,7 @@ public List getAllMilestones( @ApiParam(value = "${ImpactPathway.milestones.all.param.reportYear}", required = true) @RequestParam("reportYear") Integer repoYear) throws NotFoundException { - List response = this.milestoneItem.getAllMilestones(flagshipId, CGIAREntity, repoYear); + List response = this.milestoneItem.getAllMilestones(flagshipId, CGIAREntity, repoYear, getCurrentUser()); if (response == null || response.isEmpty()) { throw new NotFoundException("404", this.env.getProperty("ImpactPathway.milestones.all.404")); } @@ -132,10 +138,18 @@ public List getAllOutcomes( @ApiParam(value = "${ImpactPathway.outcomes.all.param.reportYear}", required = true) @RequestParam("reportYear") Integer repoYear) throws NotFoundException { - List response = this.outcomeItem.getAllOutcomes(flagshipId, CGIAREntity, targetYear, repoYear); + List response = this.outcomeItem.getAllOutcomes(flagshipId, CGIAREntity, targetYear, repoYear, getCurrentUser()); if (response == null || response.isEmpty()) { throw new NotFoundException("404", this.env.getProperty("ImpactPathway.outcomes.all.404")); } return response; } + + private User getCurrentUser() { + Subject subject = SecurityUtils.getSubject(); + Long principal = (Long) subject.getPrincipal(); + User user = this.userManager.getUser(principal); + return user; + } + } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/SrfLists.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/SrfLists.java index 91a40b726a..470d890580 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/SrfLists.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/SrfLists.java @@ -1,4 +1,4 @@ -/***************************************************************** +/** *************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO is free software: you can redistribute it and/or modify @@ -11,8 +11,8 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with MARLO. If not, see . - *****************************************************************/ - + * *************************************************************** + */ package org.cgiar.ccafs.marlo.rest.controller.v2.controllist; import org.cgiar.ccafs.marlo.rest.controller.v2.controllist.items.srflist.SrfCrossCuttingIssueItem; @@ -36,7 +36,14 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import java.util.Date; +import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.apache.shiro.subject.Subject; +import org.cgiar.ccafs.marlo.data.manager.RestApiAuditlogManager; +import org.cgiar.ccafs.marlo.data.manager.UserManager; +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; +import org.cgiar.ccafs.marlo.data.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -59,208 +66,252 @@ @Named public class SrfLists { - private static final Logger LOG = LoggerFactory.getLogger(SrfLists.class); - @Autowired - private Environment env; - - private SrfSloItem srfSloItem; - private SrfIdoItem srfIdoItem; - private SrfCrossCuttingIssueItem srfCrossCuttingIssueItem; - private SrfSubIdoItem srfSubIdoItem; - private SrfSloTargetItem srfSloIndicatorTargetItem; + private static final Logger LOG = LoggerFactory.getLogger(SrfLists.class); - @Inject - public SrfLists(SrfSloItem srfSloItem, SrfIdoItem srfIdoItem, - SrfCrossCuttingIssueItem srfCrossCuttingIssueItem, SrfSubIdoItem srfSubIdoItem, - SrfSloTargetItem srfSloIndicatorTargetItem) { - this.srfSloItem = srfSloItem; - this.srfIdoItem = srfIdoItem; - this.srfCrossCuttingIssueItem = srfCrossCuttingIssueItem; - this.srfSubIdoItem = srfSubIdoItem; - this.srfSloIndicatorTargetItem = srfSloIndicatorTargetItem; + private RestApiAuditlogManager restApiAuditlogManager; + + @Autowired + private Environment env; + private final UserManager userManager; - } + private SrfSloItem srfSloItem; + private SrfIdoItem srfIdoItem; + private SrfCrossCuttingIssueItem srfCrossCuttingIssueItem; + private SrfSubIdoItem srfSubIdoItem; + private SrfSloTargetItem srfSloIndicatorTargetItem; - /** - * Find a SRF IDO requesting by Id - * - * @param id - * @return a SrfIdoDTO with the SRL IDO data. - */ - @ApiOperation(value = "${SrfList.srf-ido.code.value}", response = SrfIdoDTO.class) - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-idos/{code}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity - findSrfIdoById(@ApiParam(value = "${SrfList.srf-ido.code.param.code}", required = true) @PathVariable String code) { - ResponseEntity response = this.srfIdoItem.findSrfIdobyId(code); - if (response.getStatusCode() == HttpStatus.NOT_FOUND) { - throw new NotFoundException("404", this.env.getProperty("SrfList.srf-ido.code.404")); + @Inject + public SrfLists(SrfSloItem srfSloItem, SrfIdoItem srfIdoItem, + SrfCrossCuttingIssueItem srfCrossCuttingIssueItem, SrfSubIdoItem srfSubIdoItem, + SrfSloTargetItem srfSloIndicatorTargetItem, RestApiAuditlogManager restApiAuditlogManager, + UserManager userManager) { + this.srfSloItem = srfSloItem; + this.srfIdoItem = srfIdoItem; + this.srfCrossCuttingIssueItem = srfCrossCuttingIssueItem; + this.srfSubIdoItem = srfSubIdoItem; + this.srfSloIndicatorTargetItem = srfSloIndicatorTargetItem; + this.restApiAuditlogManager = restApiAuditlogManager; + this.userManager = userManager; } - return response; - } - /** - * Find a SRF-SLO requesting by Id - * - * @param id - * @return a SrfSloDTO with the SRL-SLO data. - */ - @ApiIgnore - @ApiOperation(value = "${SrfList.srf-slo.code.value}", response = SrfSloDTO.class) - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-slos/{code}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity - findSrfSloById(@ApiParam(value = "${SrfList.srf-slo.code.param.code}", required = true) @PathVariable Long code) { - ResponseEntity response = this.srfSloItem.findSrfSlobyId(code); - if (response.getStatusCode() == HttpStatus.NOT_FOUND) { - throw new NotFoundException("404", this.env.getProperty("SrfList.srf-slo.code.404")); + private User getCurrentUser() { + Subject subject = SecurityUtils.getSubject(); + Long principal = (Long) subject.getPrincipal(); + User user = this.userManager.getUser(principal); + return user; } - return response; - } - /** - * Find a SLO indicator Target requesting by code - * - * @param id - * @return a SrfSloIndicatorTargetDTO with the SLO indicator Target data. - */ - - @ApiOperation( - tags = {"Table 1 - Progress towards SRF targets", "Table 3 - Outcome/ Impact Case Reports", - "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, - value = "${SrfList.slo-targets.code.value}", response = SrfSloIndicatorTargetDTO.class) - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/slo-targets/{code:.+}", method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity findSrfSloTargetByCode( - @ApiParam(value = "${SrfList.slo-targets.code.param.code}", required = true) @PathVariable String code) { - ResponseEntity response = this.srfSloIndicatorTargetItem.findSrfSloIndicatorTargetbyId(code); - if (response.getStatusCode() == HttpStatus.NOT_FOUND) { - throw new NotFoundException("404", this.env.getProperty("SrfList.slo-targets.code.404")); + /** + * Find a SRF IDO requesting by Id + * + * @param id + * @return a SrfIdoDTO with the SRL IDO data. + */ + @ApiOperation(value = "${SrfList.srf-ido.code.value}", response = SrfIdoDTO.class) + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-idos/{code}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity + findSrfIdoById(@ApiParam(value = "${SrfList.srf-ido.code.param.code}", required = true) @PathVariable String code) { + ResponseEntity response = this.srfIdoItem.findSrfIdobyId(code); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("SrfList.srf-ido.code.404")); + } else { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-idos", "LIST srf-idos, Code: " + code, new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfIdo", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + } + return response; } - return response; - } - /** - * Find a SRF Cross Cutting Issue requesting by Id - * - * @param id - * @return a SrfCrossCuttingIssueDTO with the SRF Cross Cutting Issue data. - */ - @ApiIgnore - @ApiOperation(value = "${SrfList.srf-cross-cutting-issue.code.value}", response = SrfCrossCuttingIssueDTO.class) - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-cross-cutting-issues/{code}", method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity findSrfSrfCrossCuttingIssueById( - @ApiParam(value = "${SrfList.srf-cross-cutting-issue.code.param.code}", required = true) @PathVariable Long code) { - ResponseEntity response = this.srfCrossCuttingIssueItem.findSrfCrossCuttingIssuebyId(code); - if (response.getStatusCode() == HttpStatus.NOT_FOUND) { - throw new NotFoundException("404", this.env.getProperty("SrfList.srf-cross-cutting-issue.code.404")); + /** + * Find a SRF-SLO requesting by Id + * + * @param id + * @return a SrfSloDTO with the SRL-SLO data. + */ + @ApiIgnore + @ApiOperation(value = "${SrfList.srf-slo.code.value}", response = SrfSloDTO.class) + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-slos/{code}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity + findSrfSloById(@ApiParam(value = "${SrfList.srf-slo.code.param.code}", required = true) @PathVariable Long code) { + ResponseEntity response = this.srfSloItem.findSrfSlobyId(code); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("SrfList.srf-slo.code.404")); + } else { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-slos", "LIST srf-slos, Code: " + code, new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfSlo", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + } + return response; } - return response; - } - - /** - * Find a SRF-SubIdo requesting by Id - * - * @param id - * @return a SrfSubIdoDTO with the SRF-SubIdo data. - */ - @ApiOperation( - tags = {"Table 2 - CRP Policies", "Table 3 - Outcome/ Impact Case Reports", - "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, - value = "${SrfList.srf-sub-idos.code.value}", response = SrfSubIdoDTO.class) - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-sub-idos/{code:.+}", method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity findSrfSubIdoByCode( - @ApiParam(value = "${SrfList.srf-sub-idos.code.param.code}", required = true) @PathVariable String code) { - ResponseEntity response = this.srfSubIdoItem.findSrfSubIdoBycode(code); - if (response.getStatusCode() == HttpStatus.NOT_FOUND) { - throw new NotFoundException("404", this.env.getProperty("SrfList.srf-sub-idos.code.404")); + /** + * Find a SLO indicator Target requesting by code + * + * @param id + * @return a SrfSloIndicatorTargetDTO with the SLO indicator Target data. + */ + @ApiOperation( + tags = {"Table 1 - Progress towards SRF targets", "Table 3 - Outcome/ Impact Case Reports", + "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, + value = "${SrfList.slo-targets.code.value}", response = SrfSloIndicatorTargetDTO.class) + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/slo-targets/{code:.+}", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity findSrfSloTargetByCode( + @ApiParam(value = "${SrfList.slo-targets.code.param.code}", required = true) @PathVariable String code) { + ResponseEntity response = this.srfSloIndicatorTargetItem.findSrfSloIndicatorTargetbyId(code); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("SrfList.slo-targets.code.404")); + } else { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-targets", "LIST srf-targets, Code: " + code, new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfSloIndicatorTarget", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + } + return response; } - return response; - } - - /** - * Get All the SRF IDO items - * - * @return a List of SrfIdoDTO with all SRF IDO Items. - */ - @ApiOperation(value = "${SrfList.srf-idos.all.value}", response = SrfIdoDTO.class, responseContainer = "List") - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-idos", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public List getAllSrfIdos() { - return this.srfIdoItem.getAllSrfIdos(); - } + /** + * Find a SRF Cross Cutting Issue requesting by Id + * + * @param id + * @return a SrfCrossCuttingIssueDTO with the SRF Cross Cutting Issue data. + */ + @ApiIgnore + @ApiOperation(value = "${SrfList.srf-cross-cutting-issue.code.value}", response = SrfCrossCuttingIssueDTO.class) + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-cross-cutting-issues/{code}", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity findSrfSrfCrossCuttingIssueById( + @ApiParam(value = "${SrfList.srf-cross-cutting-issue.code.param.code}", required = true) @PathVariable Long code) { + ResponseEntity response = this.srfCrossCuttingIssueItem.findSrfCrossCuttingIssuebyId(code); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("SrfList.srf-cross-cutting-issue.code.404")); + } else { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-cross-cutting-issues", "LIST srf-cross-cutting-issues, Code: " + code, new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfCrossCuttingIssue", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + } + return response; + } - /** - * Get All the SRF-SLO items - * - * @return a List of SrfSloDTO with all SRF-SLO Items. - */ - @ApiIgnore - @ApiOperation(value = "${SrfList.srf-slos.all.value}", response = SrfSloDTO.class, responseContainer = "List") - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-slos", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public List getAllSrfSlos() { - return this.srfSloItem.getAllSrfSlos(); - } + /** + * Find a SRF-SubIdo requesting by Id + * + * @param id + * @return a SrfSubIdoDTO with the SRF-SubIdo data. + */ + @ApiOperation( + tags = {"Table 2 - CRP Policies", "Table 3 - Outcome/ Impact Case Reports", + "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, + value = "${SrfList.srf-sub-idos.code.value}", response = SrfSubIdoDTO.class) + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-sub-idos/{code:.+}", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity findSrfSubIdoByCode( + @ApiParam(value = "${SrfList.srf-sub-idos.code.param.code}", required = true) @PathVariable String code) { + ResponseEntity response = this.srfSubIdoItem.findSrfSubIdoBycode(code); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("SrfList.srf-sub-idos.code.404")); + } else { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-sub-idos", "LIST srf-sub-idos, Code: " + code, new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfSubIdo", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + } + return response; + } - /** - * Get All SLO indicator Target items - * - * @return a List of SrfIdoDTO with all SRF IDO Items. - */ + /** + * Get All the SRF IDO items + * + * @return a List of SrfIdoDTO with all SRF IDO Items. + */ + @ApiOperation(value = "${SrfList.srf-idos.all.value}", response = SrfIdoDTO.class, responseContainer = "List") + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-idos", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public List getAllSrfIdos() { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-idos", "LIST srf-idos", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfIdo", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.srfIdoItem.getAllSrfIdos(); + } - @ApiOperation( - tags = {"Table 1 - Progress towards SRF targets", "Table 3 - Outcome/ Impact Case Reports", - "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, - value = "${SrfList.slo-targets.all.value}", response = SrfSloIndicatorTargetDTO.class, responseContainer = "List") - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/slo-targets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAllSrfSloTarget( - @ApiParam(value = "${SrfList.srf-sub-idos.code.param.code}") @RequestParam(required = false) Long year) { - ResponseEntity> response = this.srfSloIndicatorTargetItem.getAllSrfSloIndicatorTargets(year); - if (response.getStatusCode() == HttpStatus.NOT_FOUND) { - throw new NotFoundException("404", this.env.getProperty("SrfList.slo-targets.all.404")); + /** + * Get All the SRF-SLO items + * + * @return a List of SrfSloDTO with all SRF-SLO Items. + */ + @ApiIgnore + @ApiOperation(value = "${SrfList.srf-slos.all.value}", response = SrfSloDTO.class, responseContainer = "List") + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-slos", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public List getAllSrfSlos() { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-slos", "LIST srf-slos", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfSlo", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.srfSloItem.getAllSrfSlos(); } - return response; - } - /** - * Get All the SRF Cross Cutting Issue items - * - * @return a List of SrfCrossCuttingIssueDTO with all SRF Cross Cutting - * Issue Items. - */ - @ApiIgnore - @ApiOperation(value = "${SrfList.srf-cross-cutting-issues.all.value}", response = SrfCrossCuttingIssueDTO.class, - responseContainer = "List") - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-cross-cutting-issues", method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) - public List getAllSrfSrfCrossCuttingIssues() { - return this.srfCrossCuttingIssueItem.getAllSrfCrossCuttingIssues(); - } + /** + * Get All SLO indicator Target items + * + * @return a List of SrfIdoDTO with all SRF IDO Items. + */ + @ApiOperation( + tags = {"Table 1 - Progress towards SRF targets", "Table 3 - Outcome/ Impact Case Reports", + "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, + value = "${SrfList.slo-targets.all.value}", response = SrfSloIndicatorTargetDTO.class, responseContainer = "List") + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/slo-targets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> getAllSrfSloTarget( + @ApiParam(value = "${SrfList.srf-sub-idos.code.param.code}") @RequestParam(required = false) Long year) { + ResponseEntity> response = this.srfSloIndicatorTargetItem.getAllSrfSloIndicatorTargets(year); + if (response.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException("404", this.env.getProperty("SrfList.slo-targets.all.404")); + } else { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List slo-targets", "LIST slo-targets", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfSloIndicatorTarget", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + } + return response; + } - /** - * Get All the SRF-SubIdo items - * - * @return a List of SrfSubIdoDTO with all SRF-SubIdo Items. - */ + /** + * Get All the SRF Cross Cutting Issue items + * + * @return a List of SrfCrossCuttingIssueDTO with all SRF Cross Cutting + * Issue Items. + */ + @ApiIgnore + @ApiOperation(value = "${SrfList.srf-cross-cutting-issues.all.value}", response = SrfCrossCuttingIssueDTO.class, + responseContainer = "List") + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-cross-cutting-issues", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public List getAllSrfSrfCrossCuttingIssues() { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-cross-cutting-issues", "LIST srf-cross-cutting-issues", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfCrossCuttingIssue", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.srfCrossCuttingIssueItem.getAllSrfCrossCuttingIssues(); + } - @ApiOperation( - tags = {"Table 2 - CRP Policies", "Table 3 - Outcome/ Impact Case Reports", - "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, - value = "${SrfList.srf-sub-idos.all.value}", response = SrfSubIdoDTO.class, responseContainer = "List") - @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) - @RequestMapping(value = "/srf-sub-idos", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public List getAllSrfSubIdos() { - return this.srfSubIdoItem.getAllSrfSubIdos(); - } + /** + * Get All the SRF-SubIdo items + * + * @return a List of SrfSubIdoDTO with all SRF-SubIdo Items. + */ + @ApiOperation( + tags = {"Table 2 - CRP Policies", "Table 3 - Outcome/ Impact Case Reports", + "Table 10 - Monitoring, Evaluation, Learning and Impact Assessment (MELIA)"}, + value = "${SrfList.srf-sub-idos.all.value}", response = SrfSubIdoDTO.class, responseContainer = "List") + @RequiresPermissions(Permission.FULL_READ_REST_API_PERMISSION) + @RequestMapping(value = "/srf-sub-idos", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public List getAllSrfSubIdos() { + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("Srf List srf-sub-idos", "LIST srf-sub-idos", new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.SrfSubIdo", "N/A", this.getCurrentUser().getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + return this.srfSubIdoItem.getAllSrfSubIdos(); + } } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/FinancialSumary/FinancialSummaryItem.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/FinancialSumary/FinancialSummaryItem.java index 0fe58d1b23..600bdc0c28 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/FinancialSumary/FinancialSummaryItem.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/FinancialSumary/FinancialSummaryItem.java @@ -37,20 +37,26 @@ import org.cgiar.ccafs.marlo.data.model.ReportSynthesisFinancialSummary; import org.cgiar.ccafs.marlo.data.model.ReportSynthesisFinancialSummaryBudget; import org.cgiar.ccafs.marlo.data.model.User; +import org.cgiar.ccafs.marlo.rest.dto.FinancialSumaryDTO; +import org.cgiar.ccafs.marlo.rest.dto.FinancialSummaryBudgetDTO; import org.cgiar.ccafs.marlo.rest.dto.NewFinancialSummaryBudgetDTO; import org.cgiar.ccafs.marlo.rest.dto.NewFinancialSummaryDTO; import org.cgiar.ccafs.marlo.rest.dto.NewProjectPolicyDTO; import org.cgiar.ccafs.marlo.rest.errors.FieldErrorDTO; import org.cgiar.ccafs.marlo.rest.errors.MARLOFieldValidationException; +import org.cgiar.ccafs.marlo.rest.mappers.FinancialSummaryBudgetMapper; import java.util.ArrayList; import java.util.Comparator; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; import javax.inject.Named; import com.opensymphony.xwork2.inject.Inject; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; @Named public class FinancialSummaryItem { @@ -63,13 +69,15 @@ public class FinancialSummaryItem { private ReportSynthesisFinancialSummaryBudgetManager reportSynthesisFinancialSummaryBudgetManager; private CrpProgramManager crpProgramManager; private PowbExpenditureAreasManager powbExpenditureAreasManager; + private FinancialSummaryBudgetMapper financialSummaryBudgetMapper; @Inject public FinancialSummaryItem(PhaseManager phaseManager, GlobalUnitManager globalUnitManager, LiaisonInstitutionManager liaisonInstitutionManager, ReportSynthesisManager reportSynthesisManager, ReportSynthesisFinancialSummaryManager reportSynthesisFinancialSummaryManager, ReportSynthesisFinancialSummaryBudgetManager reportSynthesisFinancialSummaryBudgetManager, - CrpProgramManager crpProgramManager, PowbExpenditureAreasManager powbExpenditureAreasManager) { + CrpProgramManager crpProgramManager, PowbExpenditureAreasManager powbExpenditureAreasManager, + FinancialSummaryBudgetMapper financialSummaryBudgetMapper) { this.phaseManager = phaseManager; this.globalUnitManager = globalUnitManager; this.liaisonInstitutionManager = liaisonInstitutionManager; @@ -78,6 +86,7 @@ public FinancialSummaryItem(PhaseManager phaseManager, GlobalUnitManager globalU this.crpProgramManager = crpProgramManager; this.reportSynthesisFinancialSummaryBudgetManager = reportSynthesisFinancialSummaryBudgetManager; this.powbExpenditureAreasManager = powbExpenditureAreasManager; + this.financialSummaryBudgetMapper = financialSummaryBudgetMapper; } public Long createFinancialSummary(NewFinancialSummaryDTO financialSummary, String entityAcronym, User user) { @@ -127,7 +136,8 @@ public Long createFinancialSummary(NewFinancialSummaryDTO financialSummary, Stri new ArrayList(); for (NewFinancialSummaryBudgetDTO budgets : financialSummary.getFlagshipSummaryBudgets()) { CrpProgram flagship = crpProgramManager.getCrpProgramBySmoCode("" + budgets.getFlagshipID()); - if (flagship != null && flagship.getProgramType() == 1) { + if (flagship != null && flagship.getProgramType() == 1 + && flagship.getCrp().getAcronym().equals(entityAcronym)) { LiaisonInstitution liaisonInstitutionFlagship = liaisonInstitutionManager.findByAcronymAndCrp(flagship.getAcronym(), globalUnitEntity.getId()); ReportSynthesisFinancialSummaryBudget flagshipSummaryBudget = new ReportSynthesisFinancialSummaryBudget(); @@ -197,8 +207,83 @@ public Long createFinancialSummary(NewFinancialSummaryDTO financialSummary, Stri return id; } - public Long updateFinancialSummary(long idFinancialSummary, NewFinancialSummaryDTO financialSummary, - String entityAcronym, User user) { + public ResponseEntity findFinancialSumaryList(String entityAcronym, int year, String phasestr, + User user) { + FinancialSumaryDTO financialSumary = null; + + List fieldErrors = new ArrayList(); + GlobalUnit globalUnitEntity = this.globalUnitManager.findGlobalUnitByAcronym(entityAcronym); + if (globalUnitEntity == null) { + fieldErrors.add(new FieldErrorDTO("findFinancialSummary", "GlobalUnitEntity", + entityAcronym + " is an invalid CGIAR entity acronym")); + } + Phase phase = + this.phaseManager.findAll().stream().filter(c -> c.getCrp().getAcronym().equalsIgnoreCase(entityAcronym) + && c.getYear() == year && c.getName().equalsIgnoreCase(phasestr)).findFirst().get(); + + if (phase == null) { + fieldErrors.add(new FieldErrorDTO("findFinancialSummary", "phase", + new NewProjectPolicyDTO().getPhase().getYear() + " is an invalid year")); + } + // validate errors + if (fieldErrors.isEmpty()) { + LiaisonInstitution liaisonInstitution = + this.liaisonInstitutionManager.findByAcronymAndCrp(APConstants.CLARISA_ACRONYM_PMU, globalUnitEntity.getId()); + if (liaisonInstitution == null) { + fieldErrors.add(new FieldErrorDTO("findFinancialSummary", "LiaisonInstitution", "invalid liaison institution")); + } else { + ReportSynthesis reportSynthesis = + reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitution.getId()); + if (reportSynthesis == null) { + fieldErrors + .add(new FieldErrorDTO("findFinancialSummary", "ReportSynthesis", "There is not Sysnthesis report")); + } else { + + ReportSynthesisFinancialSummary reportSynthesisFinancialSummary = + reportSynthesisFinancialSummaryManager.getReportSynthesisFinancialSummaryById(reportSynthesis.getId()); + if (reportSynthesisFinancialSummary == null) { + fieldErrors + .add(new FieldErrorDTO("findFinancialSummary", "ReportSynthesis", "There is not Financial Summary")); + } else { + financialSumary = new FinancialSumaryDTO(); + financialSumary.setNarrative(reportSynthesisFinancialSummary.getNarrative()); + financialSumary.setId(reportSynthesisFinancialSummary.getId()); + financialSumary.setYear(phase.getYear()); + List summaryBudgets = new ArrayList(); + for (ReportSynthesisFinancialSummaryBudget budgets : reportSynthesisFinancialSummary + .getReportSynthesisFinancialSummaryBudgets().stream().filter(c -> c.isActive()) + .collect(Collectors.toList())) { + if (budgets.getLiaisonInstitution() != null) { + summaryBudgets.add(Optional.ofNullable(budgets) + .map( + this.financialSummaryBudgetMapper::reportSynthesisFinancialSummaryBudgetToFinancialSummaryBudgetDTO) + .orElse(null)); + } + + if (budgets.getExpenditureArea() != null && budgets.getExpenditureArea().getId() == 1) { + financialSumary.setStrategicCompetitiveResearchGrant(Optional.ofNullable(budgets).map( + this.financialSummaryBudgetMapper::reportSynthesisFinancialSummaryBudgetToFinancialSummaryBudgetAreaDTO) + .orElse(null)); + + } + if (budgets.getExpenditureArea() != null && budgets.getExpenditureArea().getId() == 2) { + financialSumary.setCrpManagementSupportCost(Optional.ofNullable(budgets).map( + this.financialSummaryBudgetMapper::reportSynthesisFinancialSummaryBudgetToFinancialSummaryBudgetAreaDTO) + .orElse(null)); + } + } + + financialSumary.setFlagshipSummaryBudgets(summaryBudgets); + } + } + } + + } + return Optional.ofNullable(financialSumary).map(result -> new ResponseEntity<>(result, HttpStatus.OK)) + .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } + + public Long updateFinancialSummary(NewFinancialSummaryDTO financialSummary, String entityAcronym, User user) { Long id = null; List fieldErrors = new ArrayList(); GlobalUnit globalUnitEntity = this.globalUnitManager.findGlobalUnitByAcronym(entityAcronym); @@ -223,7 +308,162 @@ public Long updateFinancialSummary(long idFinancialSummary, NewFinancialSummaryD if (liaisonInstitution == null) { fieldErrors.add(new FieldErrorDTO("updateExpenditure", "LiaisonInstitution", "invalid liaison institution")); } else { + ReportSynthesis reportSynthesis = + reportSynthesisManager.findSynthesis(phase.getId(), liaisonInstitution.getId()); + if (reportSynthesis == null) { + fieldErrors.add(new FieldErrorDTO("updateExpenditure", "ReportSynthesis", "There is not Sysnthesis report")); + } else { + ReportSynthesisFinancialSummary reportSynthesisFinancialSummary = + reportSynthesisFinancialSummaryManager.getReportSynthesisFinancialSummaryById(reportSynthesis.getId()); + if (reportSynthesisFinancialSummary == null) { + fieldErrors + .add(new FieldErrorDTO("updateExpenditure", "ReportSynthesis", "There is not Financial Summary")); + } else { + // modify financial summary + reportSynthesisFinancialSummary.setModifiedBy(user); + reportSynthesisFinancialSummary.setNarrative(financialSummary.getNarrative()); + reportSynthesisFinancialSummary = reportSynthesisFinancialSummaryManager + .saveReportSynthesisFinancialSummary(reportSynthesisFinancialSummary); + id = reportSynthesisFinancialSummary.getId(); + List summaryBudgetList = + new ArrayList(); + for (NewFinancialSummaryBudgetDTO budgets : financialSummary.getFlagshipSummaryBudgets()) { + CrpProgram flagship = crpProgramManager.getCrpProgramBySmoCode("" + budgets.getFlagshipID()); + if (flagship != null && flagship.getProgramType() == 1 + && flagship.getCrp().getAcronym().equals(entityAcronym)) { + LiaisonInstitution liaisonInstitutionFlagship = + liaisonInstitutionManager.findByAcronymAndCrp(flagship.getAcronym(), globalUnitEntity.getId()); + boolean found = false; + for (ReportSynthesisFinancialSummaryBudget financialSummaryBudget : reportSynthesisFinancialSummary + .getReportSynthesisFinancialSummaryBudgets().stream().filter(c -> c.isActive()) + .collect(Collectors.toList())) { + if (financialSummaryBudget.getLiaisonInstitution() != null && financialSummaryBudget + .getLiaisonInstitution().getId().equals(liaisonInstitutionFlagship.getId())) { + found = true; + ReportSynthesisFinancialSummaryBudget financialSummaryBudgetUpdate = financialSummaryBudget; + financialSummaryBudgetUpdate.setModifiedBy(user); + financialSummaryBudgetUpdate.setW3Actual(budgets.getPlannedBudgetW3Bilateral()); + financialSummaryBudgetUpdate.setW3Planned(budgets.getPlannedBudgetW3Bilateral()); + financialSummaryBudgetUpdate.setW1Actual(budgets.getActualExpenditureW1W2()); + financialSummaryBudgetUpdate.setW1Planned(budgets.getPlannedBudgetW1W2()); + financialSummaryBudgetUpdate.setComments(budgets.getComments()); + summaryBudgetList.add(financialSummaryBudgetUpdate); + } + } + if (!found) { + ReportSynthesisFinancialSummaryBudget flagshipSummaryBudget = + new ReportSynthesisFinancialSummaryBudget(); + flagshipSummaryBudget.setLiaisonInstitution(liaisonInstitutionFlagship); + flagshipSummaryBudget.setReportSynthesisFinancialSummary(reportSynthesisFinancialSummary); + flagshipSummaryBudget.setCreatedBy(user); + flagshipSummaryBudget.setW3Actual(budgets.getPlannedBudgetW3Bilateral()); + flagshipSummaryBudget.setW3Planned(budgets.getPlannedBudgetW3Bilateral()); + flagshipSummaryBudget.setW1Actual(budgets.getActualExpenditureW1W2()); + flagshipSummaryBudget.setW1Planned(budgets.getPlannedBudgetW1W2()); + flagshipSummaryBudget.setComments(budgets.getComments()); + summaryBudgetList.add(flagshipSummaryBudget); + } + } + // update or create new flagship budgets + for (ReportSynthesisFinancialSummaryBudget financialSumaryBudgets : summaryBudgetList) { + reportSynthesisFinancialSummaryBudgetManager + .saveReportSynthesisFinancialSummaryBudget(financialSumaryBudgets); + } + + } + // delete flagship budgets + List financialSumaryBudgetsToRemove = + new ArrayList(); + for (ReportSynthesisFinancialSummaryBudget financialSumaryBudgets : reportSynthesisFinancialSummary + .getReportSynthesisFinancialSummaryBudgets().stream() + .filter(c -> c.getLiaisonInstitution() != null && c.isActive()).collect(Collectors.toList())) { + boolean found = false; + + for (NewFinancialSummaryBudgetDTO budgets : financialSummary.getFlagshipSummaryBudgets()) { + CrpProgram flagship = crpProgramManager.getCrpProgramBySmoCode("" + budgets.getFlagshipID()); + if (flagship.getCrp().getAcronym().equals(entityAcronym)) { + if (financialSumaryBudgets.getLiaisonInstitution() != null && financialSumaryBudgets + .getLiaisonInstitution().getCrpProgram().getId().equals(flagship.getId())) { + found = true; + } + } + } + if (!found) { + financialSumaryBudgetsToRemove.add(financialSumaryBudgets); + } + } + // update or delete other financial budget + if (financialSummary.getStrategicCompetitiveResearchGrant() != null) { + for (ReportSynthesisFinancialSummaryBudget financialSummaryBudget : reportSynthesisFinancialSummary + .getReportSynthesisFinancialSummaryBudgets().stream().filter(c -> c.isActive()) + .collect(Collectors.toList())) { + if (financialSummaryBudget.getExpenditureArea() != null + && financialSummaryBudget.getExpenditureArea().getId() == 1) { + financialSummaryBudget.setModifiedBy(user); + financialSummaryBudget + .setW3Actual(financialSummary.getStrategicCompetitiveResearchGrant().getPlannedBudgetW3Bilateral()); + financialSummaryBudget.setW3Planned( + financialSummary.getStrategicCompetitiveResearchGrant().getPlannedBudgetW3Bilateral()); + financialSummaryBudget + .setW1Actual(financialSummary.getStrategicCompetitiveResearchGrant().getActualExpenditureW1W2()); + financialSummaryBudget + .setW1Planned(financialSummary.getStrategicCompetitiveResearchGrant().getPlannedBudgetW1W2()); + financialSummaryBudget + .setComments(financialSummary.getStrategicCompetitiveResearchGrant().getComments()); + financialSummaryBudget = reportSynthesisFinancialSummaryBudgetManager + .saveReportSynthesisFinancialSummaryBudget(financialSummaryBudget); + } + } + } else { + // check if exists a financial budget + for (ReportSynthesisFinancialSummaryBudget financialSummaryBudget : reportSynthesisFinancialSummary + .getReportSynthesisFinancialSummaryBudgets().stream().filter(c -> c.isActive()) + .collect(Collectors.toList())) { + if (financialSummaryBudget.getExpenditureArea() != null + && financialSummaryBudget.getExpenditureArea().getId() == 1) { + financialSumaryBudgetsToRemove.add(financialSummaryBudget); + } + } + } + + if (financialSummary.getCrpManagementSupportCost() != null) { + for (ReportSynthesisFinancialSummaryBudget financialSummaryBudget : reportSynthesisFinancialSummary + .getReportSynthesisFinancialSummaryBudgets().stream().filter(c -> c.isActive()) + .collect(Collectors.toList())) { + if (financialSummaryBudget.getExpenditureArea() != null + && financialSummaryBudget.getExpenditureArea().getId() == 2) { + financialSummaryBudget.setModifiedBy(user); + financialSummaryBudget + .setW3Actual(financialSummary.getCrpManagementSupportCost().getPlannedBudgetW3Bilateral()); + financialSummaryBudget + .setW3Planned(financialSummary.getCrpManagementSupportCost().getPlannedBudgetW3Bilateral()); + financialSummaryBudget + .setW1Actual(financialSummary.getCrpManagementSupportCost().getActualExpenditureW1W2()); + financialSummaryBudget + .setW1Planned(financialSummary.getCrpManagementSupportCost().getPlannedBudgetW1W2()); + financialSummaryBudget.setComments(financialSummary.getCrpManagementSupportCost().getComments()); + financialSummaryBudget = reportSynthesisFinancialSummaryBudgetManager + .saveReportSynthesisFinancialSummaryBudget(financialSummaryBudget); + } + } + } else { + // check if exists a financial budget + for (ReportSynthesisFinancialSummaryBudget financialSummaryBudget : reportSynthesisFinancialSummary + .getReportSynthesisFinancialSummaryBudgets().stream().filter(c -> c.isActive()) + .collect(Collectors.toList())) { + if (financialSummaryBudget.getExpenditureArea() != null + && financialSummaryBudget.getExpenditureArea().getId() == 2) { + financialSumaryBudgetsToRemove.add(financialSummaryBudget); + } + } + } + for (ReportSynthesisFinancialSummaryBudget removeFLBudget : financialSumaryBudgetsToRemove) { + reportSynthesisFinancialSummaryBudgetManager + .deleteReportSynthesisFinancialSummaryBudget(removeFLBudget.getId()); + } + } + } } } @@ -236,4 +476,5 @@ public Long updateFinancialSummary(long idFinancialSummary, NewFinancialSummaryD return id; } + } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/MilestoneItem.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/MilestoneItem.java index 439c2928ff..7710ba5ae5 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/MilestoneItem.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/MilestoneItem.java @@ -22,6 +22,7 @@ import org.cgiar.ccafs.marlo.data.model.CrpProgram; import org.cgiar.ccafs.marlo.data.model.CrpProgramOutcome; import org.cgiar.ccafs.marlo.data.model.Phase; +import org.cgiar.ccafs.marlo.data.model.User; import org.cgiar.ccafs.marlo.rest.dto.MilestoneDTO; import org.cgiar.ccafs.marlo.rest.mappers.MilestoneMapper; @@ -67,7 +68,7 @@ public MilestoneItem(CrpMilestoneManager crpMilestoneManager, MilestoneMapper mi * @return a OutcomeDTO with the milestone data. */ - public ResponseEntity findMilestoneById(String id, String CGIARentityAcronym, Integer year) { + public ResponseEntity findMilestoneById(String id, String CGIARentityAcronym, Integer year, User user) { CrpMilestone crpMilestone = null; Phase phase = this.phaseManager.findAll().stream() .filter(p -> StringUtils.equalsIgnoreCase(p.getCrp().getAcronym(), CGIARentityAcronym) && p.getYear() == year @@ -96,7 +97,8 @@ public ResponseEntity findMilestoneById(String id, String CGIARent * @param repoYear year of the reporting * @return a OutcomeDTO with the flagship or program data. */ - public List getAllMilestones(String crpProgramCode, String CGIARentityAcronym, Integer repoYear) { + public List getAllMilestones(String crpProgramCode, String CGIARentityAcronym, Integer repoYear, + User user) { List milestonesDTOs = null; List milestoneList = new ArrayList(); CrpProgram crpProgram = this.crpProgramManager.getCrpProgramBySmoCode(crpProgramCode); diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/OutcomeItem.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/OutcomeItem.java index c15eca411b..7314c82018 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/OutcomeItem.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/controller/v2/controllist/items/ImpactPathway/OutcomeItem.java @@ -1,4 +1,4 @@ -/***************************************************************** +/** *************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO is free software: you can redistribute it and/or modify @@ -11,10 +11,12 @@ * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with MARLO. If not, see . - *****************************************************************/ - + **************************************************************** + */ package org.cgiar.ccafs.marlo.rest.controller.v2.controllist.items.ImpactPathway; +import static com.mchange.v2.c3p0.impl.C3P0Defaults.user; +import java.util.Date; import org.cgiar.ccafs.marlo.data.manager.CrpProgramManager; import org.cgiar.ccafs.marlo.data.manager.CrpProgramOutcomeManager; import org.cgiar.ccafs.marlo.data.manager.PhaseManager; @@ -32,93 +34,111 @@ import javax.inject.Named; import org.apache.commons.lang3.StringUtils; +import org.cgiar.ccafs.marlo.data.manager.RestApiAuditlogManager; +import org.cgiar.ccafs.marlo.data.model.RestApiAuditlog; +import org.cgiar.ccafs.marlo.data.model.User; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; /** * @author Hermes Jiménez - CIAT/CCAFS */ - @Named public class OutcomeItem { - private CrpProgramOutcomeManager crpProgramOutcomeManager; - private CrpProgramManager crpProgramManager; - private OutcomeMapper outcomeMapper; - private PhaseManager phaseManager; - - @Inject - public OutcomeItem(CrpProgramOutcomeManager crpProgramOutcomeManager, OutcomeMapper outcomeMapper, - CrpProgramManager crpProgramManager, PhaseManager phaseManager) { - super(); - this.crpProgramOutcomeManager = crpProgramOutcomeManager; - this.outcomeMapper = outcomeMapper; - this.crpProgramManager = crpProgramManager; - this.phaseManager = phaseManager; - } - - /** - * Find a Flagship or program requesting by smo Code and year - * - * @param smo code - * @return a FlagshipProgramDTO with the flagship or program data. - */ - - public ResponseEntity findOutcomeById(String id, String CGIARentityAcronym, Integer year) { - CrpProgramOutcome crpProgramOutcome = null; - Phase phase = this.phaseManager.findAll().stream() - .filter(p -> StringUtils.equalsIgnoreCase(p.getCrp().getAcronym(), CGIARentityAcronym) && p.getYear() == year - && StringUtils.equalsIgnoreCase(p.getName(), "AR")) - .findFirst().orElse(null); - - - if (phase != null) { - crpProgramOutcome = this.crpProgramOutcomeManager.getCrpProgramOutcome(id, phase); - if (!crpProgramOutcome.getCrpProgram().getCrp().getAcronym().equalsIgnoreCase(CGIARentityAcronym)) { - crpProgramOutcome = null; - } - + private CrpProgramOutcomeManager crpProgramOutcomeManager; + private CrpProgramManager crpProgramManager; + private OutcomeMapper outcomeMapper; + private PhaseManager phaseManager; + private RestApiAuditlogManager restApiAuditlogManager; + + @Inject + public OutcomeItem(CrpProgramOutcomeManager crpProgramOutcomeManager, OutcomeMapper outcomeMapper, + CrpProgramManager crpProgramManager, PhaseManager phaseManager, + RestApiAuditlogManager restApiAuditlogManager) { + super(); + this.crpProgramOutcomeManager = crpProgramOutcomeManager; + this.outcomeMapper = outcomeMapper; + this.crpProgramManager = crpProgramManager; + this.phaseManager = phaseManager; + this.restApiAuditlogManager = restApiAuditlogManager; } - return Optional.ofNullable(crpProgramOutcome).map(this.outcomeMapper::crpProgramOutcomeToOutcomeDTO) - .map(result -> new ResponseEntity<>(result, HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); - } - - /** - * Find a Flagship or program requesting by id - * - * @param id - * @return a FlagshipProgramDTO with the flagship or program data. - */ - public List getAllOutcomes(String crpProgramCode, String CGIARentityAcronym, Integer targetYear, - Integer repoYear) { - List outcomeDTOs = null; - CrpProgram crpProgram = this.crpProgramManager.getCrpProgramBySmoCode(crpProgramCode); - List phases = - this.phaseManager.findAll().stream().filter(c -> c.getCrp().getAcronym().equalsIgnoreCase(CGIARentityAcronym) - && c.getYear() == repoYear && c.getName().equalsIgnoreCase("AR")).collect(Collectors.toList()); - - if (crpProgram != null && phases != null && !phases.isEmpty() - && crpProgram.getCrp().equals(phases.get(0).getCrp())) { - - List crpProgramOutcomes = crpProgram.getCrpProgramOutcomes().stream() - .filter(c -> c.isActive() && c.getPhase().equals(phases.get(0))).collect(Collectors.toList()); - if (targetYear != null) { - outcomeDTOs = crpProgramOutcomes.stream().filter(c -> c.getYear().equals(targetYear)) - .map(outcomeEntity -> this.outcomeMapper.crpProgramOutcomeToOutcomeDTO(outcomeEntity)) - .collect(Collectors.toList()); - } else { - outcomeDTOs = crpProgramOutcomes.stream() - .map(outcomeEntity -> this.outcomeMapper.crpProgramOutcomeToOutcomeDTO(outcomeEntity)) - .collect(Collectors.toList()); - } - + /** + * + * @param id + * @param CGIARentityAcronym + * @param year + * @param user + * @return a FlagshipProgramDTO with the flagship or program data. + */ + public ResponseEntity findOutcomeById(String id, String CGIARentityAcronym, Integer year, User user) { + CrpProgramOutcome crpProgramOutcome = null; + Phase phase = this.phaseManager.findAll().stream() + .filter(p -> StringUtils.equalsIgnoreCase(p.getCrp().getAcronym(), CGIARentityAcronym) && p.getYear() == year + && StringUtils.equalsIgnoreCase(p.getName(), "AR")) + .findFirst().orElse(null); + + if (phase != null) { + crpProgramOutcome = this.crpProgramOutcomeManager.getCrpProgramOutcome(id, phase); + if (!crpProgramOutcome.getCrpProgram().getCrp().getAcronym().equalsIgnoreCase(CGIARentityAcronym)) { + crpProgramOutcome = null; + } else { + // Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("findOutcomeById", "Searched CGIAR Entity Acronym " + CGIARentityAcronym + " ID " + id + " Year:" + year + " Phase: " + phase.getId(), new Date(), Long.parseLong(id), "class org.cgiar.ccafs.marlo.data.model.CrpProgramOutcome", + "N/A", user.getId(), null, "", phase.getId()); + restApiAuditlogManager.logApiCall(restApiAuditLog); + } + + } + + return Optional.ofNullable(crpProgramOutcome).map(this.outcomeMapper::crpProgramOutcomeToOutcomeDTO) + .map(result -> new ResponseEntity<>(result, HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } - return outcomeDTOs; - // Optional.ofNullable(outcomeDTOs).map(result -> new ResponseEntity<>(result, HttpStatus.OK)).orElse(new - // ResponseEntity<>(HttpStatus.NOT_FOUND)); - } + /** + * Find a Flagship or program requesting by id + * + * @param crpProgramCode + * @param CGIARentityAcronym + * @param targetYear + * @param repoYear + * @param user + * @return a FlagshipProgramDTO with the flagship or program data. + */ + public List getAllOutcomes(String crpProgramCode, String CGIARentityAcronym, Integer targetYear, + Integer repoYear, User user) { + List outcomeDTOs = null; + CrpProgram crpProgram = this.crpProgramManager.getCrpProgramBySmoCode(crpProgramCode); + List phases + = this.phaseManager.findAll().stream().filter(c -> c.getCrp().getAcronym().equalsIgnoreCase(CGIARentityAcronym) + && c.getYear() == repoYear && c.getName().equalsIgnoreCase("AR")).collect(Collectors.toList()); + + if (crpProgram != null && phases != null && !phases.isEmpty() + && crpProgram.getCrp().equals(phases.get(0).getCrp())) { + + List crpProgramOutcomes = crpProgram.getCrpProgramOutcomes().stream() + .filter(c -> c.isActive() && c.getPhase().equals(phases.get(0))).collect(Collectors.toList()); + if (targetYear != null) { + outcomeDTOs = crpProgramOutcomes.stream().filter(c -> c.getYear().equals(targetYear)) + .map(outcomeEntity -> this.outcomeMapper.crpProgramOutcomeToOutcomeDTO(outcomeEntity)) + .collect(Collectors.toList()); + } else { + outcomeDTOs = crpProgramOutcomes.stream() + .map(outcomeEntity -> this.outcomeMapper.crpProgramOutcomeToOutcomeDTO(outcomeEntity)) + .collect(Collectors.toList()); + } + + } + + //Log Action + RestApiAuditlog restApiAuditLog = new RestApiAuditlog("List Outcomes", "LIST outcomes CGIAR Entity Acronym " + CGIARentityAcronym + " CRP Programe Code " + crpProgramCode + " Year:" + repoYear, new Date(), 0, "class org.cgiar.ccafs.marlo.data.model.CrpProgramOutcome", "N/A", user.getId(), null, "", null); + restApiAuditlogManager.logApiCall(restApiAuditLog); + + return outcomeDTOs; + // Optional.ofNullable(outcomeDTOs).map(result -> new ResponseEntity<>(result, HttpStatus.OK)).orElse(new + // ResponseEntity<>(HttpStatus.NOT_FOUND)); + } } diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSumaryDTO.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSumaryDTO.java new file mode 100644 index 0000000000..282fa86888 --- /dev/null +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSumaryDTO.java @@ -0,0 +1,108 @@ +/***************************************************************** + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). + * MARLO is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * at your option) any later version. + * MARLO is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with MARLO. If not, see . + *****************************************************************/ + +/************** + * @author Diego Perez - CIAT/CCAFS + **************/ + +package org.cgiar.ccafs.marlo.rest.dto; + +import java.util.List; + +import io.swagger.annotations.ApiModelProperty; + +public class FinancialSumaryDTO { + + @ApiModelProperty(notes = "Financial Sumary ID", position = 1) + private Long id; + + @ApiModelProperty(notes = "Financial summary narrative", position = 3) + private String narrative; + + @ApiModelProperty(notes = "Flagship budget List", position = 4) + private List flagshipSummaryBudgets; + + @ApiModelProperty(notes = "Strategic competitive research grant", position = 5) + private FinancialSummaryBudgetAreaDTO strategicCompetitiveResearchGrant; + + + @ApiModelProperty(notes = "CRP Management and Support Cost", position = 6) + private FinancialSummaryBudgetAreaDTO crpManagementSupportCost; + + + @ApiModelProperty(notes = "Reporting year", position = 7) + private int year; + + public FinancialSummaryBudgetAreaDTO getCrpManagementSupportCost() { + return crpManagementSupportCost; + } + + + public List getFlagshipSummaryBudgets() { + return flagshipSummaryBudgets; + } + + + public Long getId() { + return id; + } + + + public String getNarrative() { + return narrative; + } + + + public FinancialSummaryBudgetAreaDTO getStrategicCompetitiveResearchGrant() { + return strategicCompetitiveResearchGrant; + } + + + public int getYear() { + return year; + } + + + public void setCrpManagementSupportCost(FinancialSummaryBudgetAreaDTO crpManagementSupportCost) { + this.crpManagementSupportCost = crpManagementSupportCost; + } + + + public void setFlagshipSummaryBudgets(List flagshipSummaryBudgets) { + this.flagshipSummaryBudgets = flagshipSummaryBudgets; + } + + + public void setId(Long id) { + this.id = id; + } + + + public void setNarrative(String narrative) { + this.narrative = narrative; + } + + + public void setStrategicCompetitiveResearchGrant(FinancialSummaryBudgetAreaDTO strategicCompetitiveResearchGrant) { + this.strategicCompetitiveResearchGrant = strategicCompetitiveResearchGrant; + } + + + public void setYear(int year) { + this.year = year; + } + + +} diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSummaryBudgetAreaDTO.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSummaryBudgetAreaDTO.java new file mode 100644 index 0000000000..a0d62375f0 --- /dev/null +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSummaryBudgetAreaDTO.java @@ -0,0 +1,118 @@ +/***************************************************************** + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). + * MARLO is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * at your option) any later version. + * MARLO is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with MARLO. If not, see . + *****************************************************************/ + +/************** + * @author Diego Perez - CIAT/CCAFS + **************/ + +package org.cgiar.ccafs.marlo.rest.dto; + +import io.swagger.annotations.ApiModelProperty; + +public class FinancialSummaryBudgetAreaDTO { + + + @ApiModelProperty(notes = "Expenditure Area identifier") + private long expenditureAreaID; + + @ApiModelProperty(notes = "Expenditure Area name") + private String expenditureAreaName; + + + @ApiModelProperty(notes = "Planned Budget W1/W2 value") + private double plannedBudgetW1W2; + + + @ApiModelProperty(notes = "Planned Budget W3 and Biltareal value") + private double plannedBudgetW3Bilateral; + + + @ApiModelProperty(notes = "Actual expenditure for W1/W2") + private double actualExpenditureW1W2; + + @ApiModelProperty(notes = "Actual expenditure for W3 and Bilateral") + private double actualExpendituretW3Bilateral; + + @ApiModelProperty(notes = "Commments") + private String comments; + + public double getActualExpendituretW3Bilateral() { + return actualExpendituretW3Bilateral; + } + + public double getActualExpenditureW1W2() { + return actualExpenditureW1W2; + } + + + public String getComments() { + return comments; + } + + + public long getExpenditureAreaID() { + return expenditureAreaID; + } + + + public String getExpenditureAreaName() { + return expenditureAreaName; + } + + + public double getPlannedBudgetW1W2() { + return plannedBudgetW1W2; + } + + + public double getPlannedBudgetW3Bilateral() { + return plannedBudgetW3Bilateral; + } + + + public void setActualExpendituretW3Bilateral(double actualExpendituretW3Bilateral) { + this.actualExpendituretW3Bilateral = actualExpendituretW3Bilateral; + } + + + public void setActualExpenditureW1W2(double actualExpenditureW1W2) { + this.actualExpenditureW1W2 = actualExpenditureW1W2; + } + + + public void setComments(String comments) { + this.comments = comments; + } + + + public void setExpenditureAreaID(long expenditureAreaID) { + this.expenditureAreaID = expenditureAreaID; + } + + + public void setExpenditureAreaName(String expenditureAreaName) { + this.expenditureAreaName = expenditureAreaName; + } + + public void setPlannedBudgetW1W2(double plannedBudgetW1W2) { + this.plannedBudgetW1W2 = plannedBudgetW1W2; + } + + + public void setPlannedBudgetW3Bilateral(double plannedBudgetW3Bilateral) { + this.plannedBudgetW3Bilateral = plannedBudgetW3Bilateral; + } + +} diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSummaryBudgetDTO.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSummaryBudgetDTO.java new file mode 100644 index 0000000000..e6859f200f --- /dev/null +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/FinancialSummaryBudgetDTO.java @@ -0,0 +1,119 @@ +/***************************************************************** + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). + * MARLO is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * at your option) any later version. + * MARLO is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with MARLO. If not, see . + *****************************************************************/ + +/************** + * @author Diego Perez - CIAT/CCAFS + **************/ + +package org.cgiar.ccafs.marlo.rest.dto; + +import io.swagger.annotations.ApiModelProperty; + +public class FinancialSummaryBudgetDTO { + + + @ApiModelProperty(notes = "Flagship program identifier") + private long flagshipID; + + @ApiModelProperty(notes = "Flagship program name") + private String flagshipName; + + + @ApiModelProperty(notes = "Planned Budget W1/W2 value") + private double plannedBudgetW1W2; + + + @ApiModelProperty(notes = "Planned Budget W3 and Biltareal value") + private double plannedBudgetW3Bilateral; + + + @ApiModelProperty(notes = "Actual expenditure for W1/W2") + private double actualExpenditureW1W2; + + @ApiModelProperty(notes = "Actual expenditure for W3 and Bilateral") + private double actualExpendituretW3Bilateral; + + @ApiModelProperty(notes = "Commments") + private String comments; + + public double getActualExpendituretW3Bilateral() { + return actualExpendituretW3Bilateral; + } + + public double getActualExpenditureW1W2() { + return actualExpenditureW1W2; + } + + + public String getComments() { + return comments; + } + + + public long getFlagshipID() { + return flagshipID; + } + + + public String getFlagshipName() { + return flagshipName; + } + + + public double getPlannedBudgetW1W2() { + return plannedBudgetW1W2; + } + + + public double getPlannedBudgetW3Bilateral() { + return plannedBudgetW3Bilateral; + } + + + public void setActualExpendituretW3Bilateral(double actualExpendituretW3Bilateral) { + this.actualExpendituretW3Bilateral = actualExpendituretW3Bilateral; + } + + + public void setActualExpenditureW1W2(double actualExpenditureW1W2) { + this.actualExpenditureW1W2 = actualExpenditureW1W2; + } + + + public void setComments(String comments) { + this.comments = comments; + } + + + public void setFlagshipID(long flagshipID) { + this.flagshipID = flagshipID; + } + + + public void setFlagshipName(String flagshipName) { + this.flagshipName = flagshipName; + } + + + public void setPlannedBudgetW1W2(double plannedBudgetW1W2) { + this.plannedBudgetW1W2 = plannedBudgetW1W2; + } + + + public void setPlannedBudgetW3Bilateral(double plannedBudgetW3Bilateral) { + this.plannedBudgetW3Bilateral = plannedBudgetW3Bilateral; + } + +} diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryBudgetDTO.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryBudgetDTO.java index 4edd389347..1fb7988036 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryBudgetDTO.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryBudgetDTO.java @@ -23,22 +23,22 @@ public class NewFinancialSummaryBudgetDTO { - @ApiModelProperty(notes = "Flagship program identifier") + @ApiModelProperty(notes = "Flagship program SMO identifier", position = 1) private long flagshipID; - @ApiModelProperty(notes = "Planned Budget W1/W2 value") + @ApiModelProperty(notes = "Planned Budget W1/W2 value", position = 2) private double plannedBudgetW1W2; - @ApiModelProperty(notes = "Planned Budget W3 and Biltareal value") + @ApiModelProperty(notes = "Planned Budget W3 and Biltareal value", position = 4) private double plannedBudgetW3Bilateral; - @ApiModelProperty(notes = "Actual expenditure for W1/W2") + @ApiModelProperty(notes = "Actual expenditure for W1/W2", position = 3) private double actualExpenditureW1W2; - @ApiModelProperty(notes = "Actual expenditure for W3 and Bilateral") + @ApiModelProperty(notes = "Actual expenditure for W3 and Bilateral", position = 5) private double actualExpendituretW3Bilateral; - @ApiModelProperty(notes = "Commments") + @ApiModelProperty(notes = "Commments", position = 6) private String comments; diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryDTO.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryDTO.java index 2d72ec3502..b12595502a 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryDTO.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewFinancialSummaryDTO.java @@ -26,21 +26,21 @@ public class NewFinancialSummaryDTO { - @ApiModelProperty(notes = "Financial summary narrative") + @ApiModelProperty(notes = "Financial summary narrative", position = 2) private String narrative; - @ApiModelProperty(notes = "Flagship budget List") + @ApiModelProperty(notes = "Flagship budget List", position = 3) private List flagshipSummaryBudgets; - @ApiModelProperty(notes = "Strategic competitive research grant") + @ApiModelProperty(notes = "Strategic competitive research grant", position = 4) private NewFinancialSummaryBudgetDTO strategicCompetitiveResearchGrant; - @ApiModelProperty(notes = "CRP Management and Support Cost") + @ApiModelProperty(notes = "CRP Management and Support Cost", position = 5) private NewFinancialSummaryBudgetDTO crpManagementSupportCost; - @ApiModelProperty(notes = "Flagship program identifier") + @ApiModelProperty(notes = "Phase identifier", position = 1) private PhaseDTO phase; diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/mappers/FinancialSummaryBudgetMapper.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/mappers/FinancialSummaryBudgetMapper.java new file mode 100644 index 0000000000..34bc9ad4c0 --- /dev/null +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/mappers/FinancialSummaryBudgetMapper.java @@ -0,0 +1,52 @@ +/***************************************************************** + * This file is part of Managing Agricultural Research for Learning & + * Outcomes Platform (MARLO). + * MARLO is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * at your option) any later version. + * MARLO is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with MARLO. If not, see . + *****************************************************************/ + +/************** + * @author Diego Perez - CIAT/CCAFS + **************/ + +package org.cgiar.ccafs.marlo.rest.mappers; + +import org.cgiar.ccafs.marlo.data.model.ReportSynthesisFinancialSummaryBudget; +import org.cgiar.ccafs.marlo.rest.dto.FinancialSummaryBudgetAreaDTO; +import org.cgiar.ccafs.marlo.rest.dto.FinancialSummaryBudgetDTO; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Mappings; + +@Mapper(componentModel = "jsr330", uses = GlobalUnitMapper.class) +public interface FinancialSummaryBudgetMapper { + + @Mappings({@Mapping(source = "expenditureArea.id", target = "expenditureAreaID"), + @Mapping(source = "expenditureArea.expenditureArea", target = "expenditureAreaName"), + @Mapping(source = "w1Planned", target = "plannedBudgetW1W2"), + @Mapping(source = "bilateralPlanned", target = "plannedBudgetW3Bilateral"), + @Mapping(source = "w1Actual", target = "actualExpenditureW1W2"), + @Mapping(source = "bilateralActual", target = "actualExpendituretW3Bilateral")}) + public abstract FinancialSummaryBudgetAreaDTO reportSynthesisFinancialSummaryBudgetToFinancialSummaryBudgetAreaDTO( + ReportSynthesisFinancialSummaryBudget financialSumaryBudget); + + @Mappings({@Mapping(source = "liaisonInstitution.crpProgram.smoCode", target = "flagshipID"), + @Mapping(source = "liaisonInstitution.crpProgram.name", target = "flagshipName"), + @Mapping(source = "w1Planned", target = "plannedBudgetW1W2"), + @Mapping(source = "bilateralPlanned", target = "plannedBudgetW3Bilateral"), + @Mapping(source = "w1Actual", target = "actualExpenditureW1W2"), + @Mapping(source = "bilateralActual", target = "actualExpendituretW3Bilateral")}) + public abstract FinancialSummaryBudgetDTO reportSynthesisFinancialSummaryBudgetToFinancialSummaryBudgetDTO( + ReportSynthesisFinancialSummaryBudget financialSumaryBudget); + + +} diff --git a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/services/deliverables/CGSpaceClientAPI.java b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/services/deliverables/CGSpaceClientAPI.java index 68a690a23b..1b06c2cebc 100644 --- a/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/services/deliverables/CGSpaceClientAPI.java +++ b/marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/services/deliverables/CGSpaceClientAPI.java @@ -203,6 +203,15 @@ public MetadataModel getMetadata(String link) { public String parseLink(String link) { String linkRest = ""; + // the url is encoded? + if (link.contains("%")) { + // decode + try { + link = java.net.URLDecoder.decode(link, java.nio.charset.StandardCharsets.UTF_8.name()); + } catch (java.io.UnsupportedEncodingException e) { + /* not going to happen - value came from JDK's own StandardCharsets */} + } + // if the link contains http://hdl.handle.net/ we remove it from the link if (link.contains(HANDLE_URL)) { this.setId(link.replace(HANDLE_URL, "")); @@ -216,6 +225,8 @@ public String parseLink(String link) { this.setId(link.replace(CGSPACE_URL, "")); } + LOG.debug("The given link is {} and the extracted id is {}", link, this.getId()); + if (this.getId() != null) { String handleUrl = CGSPACE_HANDLE.replace("{0}", this.getId()); RestConnectionUtil connection = new RestConnectionUtil(); diff --git a/marlo-web/src/main/resources/clarisa.properties b/marlo-web/src/main/resources/clarisa.properties index a2d923c8c2..d30d300708 100644 --- a/marlo-web/src/main/resources/clarisa.properties +++ b/marlo-web/src/main/resources/clarisa.properties @@ -713,6 +713,22 @@ Expenditure.Example.PUT.param.CGIAR=Acronym of CGIAR Entity Expenditure.Example.PUT.id.value=Id of Expenditure Example Expenditure.Example.PUT.param.relevantEvaluation=Expenditure Example Model +FinancialSummary.Example.POST.value=Create a financial summary +FinancialSummary.Example.POST.param.CGIAR=Acronym of CGIAR Entity +FinancialSummary.Example.POST.param.financialmodel=New financial summary model + +FinancialSummary.Example.GET.id.404=Financial Summary not found +FinancialSummary.Example.GET.value=Search a CRP financial report +FinancialSummary.Example.GET.param.CGIAR=Acronym of CGIAR Entity +FinancialSummary.Example.GET.year.value=Year to report +FinancialSummary.Example.GET.phase.value=Reporting phase AR + +FinancialSummary.Example.PUT.value=Update a financial summary +FinancialSummary.Example.PUT.param.CGIAR=Acronym of CGIAR Entity +FinancialSummary.Example.PUT.id.value=Id of financial summary +FinancialSummary.Example.PUT.param.financialmodel= Financial summary model + + SubmissionToolsControlLists.action-areas.code.value=Search a Action Area with a code SubmissionToolsControlLists.action-areas.code.404=Action Area not found SubmissionToolsControlLists.action-areas.code.param.code=Code of Action Area diff --git a/marlo-web/src/main/resources/config/marlo-test.properties b/marlo-web/src/main/resources/config/marlo-test.properties index ac9c9aecc8..1e11e7e178 100644 --- a/marlo-web/src/main/resources/config/marlo-test.properties +++ b/marlo-web/src/main/resources/config/marlo-test.properties @@ -6,7 +6,7 @@ mysql.user=XXXXXX mysql.password=XXXXXX -mysql.database=marlo_dev +mysql.database=marlodb mysql.port=3306 @@ -66,7 +66,7 @@ tawkto.api.key=XXXXXX autosave.active=true -autosave.folder=/home/cdgarcia/tempFiles/ +autosave.folder=/home/julianrodriguez/tempFiles/ # ------------------------------------------------ @@ -114,7 +114,10 @@ file.maxSizeAllowed.bytes=3145728 # Base folder where files will be moved -file.uploads.baseFolder=/home/cdgarcia/marloFiles/ +file.uploads.baseFolder=/home/julianrodriguez/marloFiles/ + +# Path to get the base URL of media hosted in the CDN +cdn.url= # ----------------------------------------------- @@ -132,9 +135,9 @@ marlo.debug=false # ------------------------------------------------ -log.folder=/home/cdgarcia/logs +log.folder=/home/julianrodriguez/logs -log.console=false +log.console=true log.file=true @@ -161,4 +164,27 @@ clarisa.wos.link=http://clarisatest.ciat.cgiar.org/api/publicationsWOS?url={1} clarisa.wos.user=dfperez clarisa.wos.password=123 -file.uploads.fundingSourceFolder=fundingSource/ \ No newline at end of file +<<<<<<< HEAD +file.uploads.fundingSourceFolder=fundingSource/ +#------------------------------------------------------ +# Clarisa Public User +#------------------------------------------------------- +clarisa.publicUser=clarisa.public +clarisa.publicPass=2578 +clarisa.mapDatabase.path=/home/julianrodriguez/mapsDatabase/ + +email.auth=true +email.starttls=true +# Mail configuration Backup +email.notificationbackup=MARLOSupport@cgiar.org +email.userbackup=ccafs-pr +email.passwordbackup=tauMaiC8 +email.hostbackup=ciatsmtp.ciat.cgiar.org +email.portbackup=587 +email.authbackup=true +email.starttlsbackup=true + +clarisa.summariesPDF=http://marlodev.ciat.cgiar.org/ +======= +file.uploads.fundingSourceFolder=fundingSource/ +>>>>>>> 04c1f8828cc2b93d766859a4be0c32477d3245b8 diff --git a/marlo-web/src/main/resources/database/migrations/V2_6_0_20200504_0849__AddSectionImpactCovid19.sql b/marlo-web/src/main/resources/database/migrations/V2_6_0_20200504_0849__AddSectionImpactCovid19.sql index 226ffb1c61..c8f6385037 100644 --- a/marlo-web/src/main/resources/database/migrations/V2_6_0_20200504_0849__AddSectionImpactCovid19.sql +++ b/marlo-web/src/main/resources/database/migrations/V2_6_0_20200504_0849__AddSectionImpactCovid19.sql @@ -1,35 +1,29 @@ CREATE TABLE IF NOT EXISTS `project_impacts` ( - `id` BIGINT (20) NOT NULL AUTO_INCREMENT, - `project_id` BIGINT (20) DEFAULT NULL, - `id_phase` BIGINT (20) DEFAULT NULL, - `answer` text, - `is_active` TINYINT (1) NOT NULL DEFAULT '1', - `active_since` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - `created_by` BIGINT (20) DEFAULT NULL, - `modified_by` BIGINT (20) DEFAULT NULL, - `modification_justification` text, - PRIMARY KEY (`id`), - CONSTRAINT `project_impacts_projects` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `project_impacts_phases` FOREIGN KEY (`id_phase`) REFERENCES `phases` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `project_impacts_users1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `project_impacts_users2` FOREIGN KEY (`modified_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE + `id` BIGINT (20) NOT NULL AUTO_INCREMENT, + `project_id` BIGINT (20) DEFAULT NULL, + `id_phase` BIGINT (20) DEFAULT NULL, + `answer` text, + `is_active` TINYINT (1) NOT NULL DEFAULT '1', + `active_since` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `created_by` BIGINT (20) DEFAULT NULL, + `modified_by` BIGINT (20) DEFAULT NULL, + `modification_justification` text, + PRIMARY KEY (`id`), + CONSTRAINT `project_impacts_projects` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `project_impacts_phases` FOREIGN KEY (`id_phase`) REFERENCES `phases` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `project_impacts_users1` FOREIGN KEY (`created_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `project_impacts_users2` FOREIGN KEY (`modified_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ); - ALTER TABLE section_statuses ADD project_impact_id BIGINT(20) DEFAULT NULL; - ALTER TABLE section_statuses ADD CONSTRAINT section_statuses_impacts FOREIGN KEY (project_impact_id) REFERENCES project_impacts(id); - INSERT INTO `parameters` (`global_unit_type_id`, `key`, `description`, `format`, `category`) VALUES ( '1', 'crp_show_section_impact_covid19', 'Show section impact of COVID-19', '1', '2'); - INSERT INTO `custom_parameters` (`parameter_id`, `value`, `created_by`, `is_active`, `active_since`, `modified_by`, `modification_justification`, `global_unit_id`) SELECT (SELECT id FROM `parameters` WHERE `key` = 'crp_show_section_impact_covid19' AND global_unit_type_id = 1), `value`, `created_by`, `is_active`, `active_since`, `modified_by`, `modification_justification`, `global_unit_id` FROM `custom_parameters` WHERE parameter_id = 200; - INSERT INTO `parameters` (`global_unit_type_id`, `key`, `description`, `format`, `category`) VALUES ( '3', 'crp_show_section_impact_covid19', 'Show section impact of COVID-19', '1', '2'); - INSERT INTO `parameters` (`global_unit_type_id`, `key`, `description`, `format`, `category`) VALUES ( '4', 'crp_show_section_impact_covid19', 'Show section impact of COVID-19', '1', '2'); diff --git a/marlo-web/src/main/resources/database/migrations/V2_6_0_20201005_1123__BIReportsNewColumns.sql b/marlo-web/src/main/resources/database/migrations/V2_6_0_20201005_1123__BIReportsNewColumns.sql index 4b4c8082f1..3b7b9fb78a 100644 --- a/marlo-web/src/main/resources/database/migrations/V2_6_0_20201005_1123__BIReportsNewColumns.sql +++ b/marlo-web/src/main/resources/database/migrations/V2_6_0_20201005_1123__BIReportsNewColumns.sql @@ -1,7 +1,10 @@ ALTER TABLE bi_reports ADD COLUMN report_title VARCHAR(15) AFTER report_name; +<<<<<<< HEAD +======= +>>>>>>> 32e660484cde88d5ad492ad580c8c607564da1c4 ALTER TABLE bi_reports ADD COLUMN report_description VARCHAR(140) AFTER report_title; \ No newline at end of file diff --git a/marlo-web/src/main/resources/database/migrations/V2_6_0_20201231_1000__AddRestAPIAuditLogTable.sql b/marlo-web/src/main/resources/database/migrations/V2_6_0_20201231_1000__AddRestAPIAuditLogTable.sql new file mode 100644 index 0000000000..4489b8aae0 --- /dev/null +++ b/marlo-web/src/main/resources/database/migrations/V2_6_0_20201231_1000__AddRestAPIAuditLogTable.sql @@ -0,0 +1,21 @@ +CREATE TABLE +IF NOT EXISTS `rest_api_auditlog` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `action` varchar(128) NOT NULL, + `detail` text NOT NULL, + `created_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `entity_id` bigint NOT NULL, + `entity_name` varchar(512) NOT NULL, + `entity_json` text NOT NULL, + `user_id` bigint NOT NULL, + `main` bigint DEFAULT NULL, + `modification_justification` text, + `phase` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `fk_rest_api_auditlog_user_idx` (`user_id`), + CONSTRAINT `fk_rest_api_auditlog_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) +) +ENGINE=InnoDB +DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci +; + diff --git a/marlo-web/src/main/resources/database/migrations/V2_6_0_20220323_0915__NewIATIInstitutionTypes.sql b/marlo-web/src/main/resources/database/migrations/V2_6_0_20220323_0915__NewIATIInstitutionTypes.sql new file mode 100644 index 0000000000..cd67f37e7f --- /dev/null +++ b/marlo-web/src/main/resources/database/migrations/V2_6_0_20220323_0915__NewIATIInstitutionTypes.sql @@ -0,0 +1,6 @@ +alter table institution_types add column is_legacy tinyint(1) DEFAULT '0' after description; + +update institution_types set is_legacy = '1'; + +insert into institution_types (name) values ('Subnational Government'), ('Regional NGO'), +('Academic, Training and Research'), ('Public Private Partnership'), ('Multilateral'); \ No newline at end of file diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/macros/projectsListTemplate.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/macros/projectsListTemplate.ftl index 0ebdf93ce3..edf16579d6 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/macros/projectsListTemplate.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/macros/projectsListTemplate.ftl @@ -4,17 +4,30 @@ + [#if !centerGlobalUnit] + [#else] + + [/#if] + [#if !reportingActive && !centerGlobalUnit] [/#if] + [#if !centerGlobalUnit] + [#else] + + [/#if] - - + + [#if centerGlobalUnit] + + [/#if] + + [#if !reportingActive && !centerGlobalUnit] [/#if] + [#if centerGlobalUnit] + + [/#if] + [#if !centerGlobalUnit] + [/#if] [#if isPlanning] @@ -50,9 +69,10 @@ [#-- ID --] [#-- Project Title --] + [#-- Center Staf --] + [#if centerGlobalUnit] + + [/#if] [#-- Flagship / Regions / Programs --] - + [#if centerGlobalUnit] + + [/#if] [#-- Summary PDF download --] + [#if !centerGlobalUnit] + [/#if] [#-- Delete Project--]
General InformationGeneral Information[@s.text name="projectsList.projectBudget"] [@s.param]${(crpSession?upper_case)!}[/@s.param] [/@s.text] ${currentCycleYear}ActionsActions
[@s.text name="projectsList.projectids" /] [@s.text name="projectsList.projectTitles" /][@s.text name="projectsList.projectLeader" /][@s.text name="projectsList.projectLeaderPerson" /] + [@s.text name="projectsList.projectLeader" /][@s.text name="projectsList.projectLeaderPerson" /][@s.text name="projectsList.centerStaff" /] [#if centerGlobalUnit] [@s.text name="projectsList.projectPrograms" /] @@ -26,13 +39,19 @@ [/#if] [/#if] [@s.text name="projectsList.W1W2projectBudget" /] [@s.text name="projectsList.W3projectBudget" /] [@s.text name="projectsList.BILATERALprojectBudget" /][@s.text name="projectsList.projectActionStatus" /][@s.text name="projectsList.centerMapping" /][@s.text name="projectsList.download" /][@s.text name="projectsList.delete" /][@s.text name="planning.projects.completion" /] P${project.id} - [#if centerGlobalUnit && isCrpProject ] + [#if centerGlobalUnit] ${(project.projectInfo.phase.crp.acronym)!} [/#if] + @@ -80,18 +100,34 @@ [#else] [#assign pLeader = (project.getLeader(action.getActualPhase()))! ] [#assign pLeaderPerson = (project.getLeaderPersonDB(action.getActualPhase()))! ] - [/#if] + [/#if] [#if pLeader?has_content]${(pLeader.institution.acronym)!pLeader.institution.name}[#else][@s.text name="projectsList.title.none" /][/#if] + [#if centerGlobalUnit] + [#if pLeaderPerson?has_content] ${(pLeaderPerson.user.composedCompleteName)!}[#else][@s.text name="projectsList.title.none" /][/#if] + [#else] [#if pLeaderPerson?has_content] ${(pLeaderPerson.user.composedName)!}[#else][@s.text name="projectsList.title.none" /][/#if] + [/#if] + + +
+ [#assign centerStaffList = (project.getLeadersCenter(project.projectInfo.phase,actualPhase.crp.institution.id))! ] + [#list (centerStaffList)![] as centerstaff] + ${(centerstaff.user.composedCompleteName)!} + [/#list] +
[#assign tagsNumber = 0 /] [#if project.projectInfo.administrative] - [#local li = (project.projectInfo.liaisonInstitution)!{} ] + [#local li = (project.projectInfo.liaisonInstitution)!{}] [#if ((li.crpProgram??)!false) && (li.crpProgram.crp.id == actualPhase.crp.id )] ${(li.crpProgram.acronym)!(li.crpProgram.name)} @@ -146,8 +182,11 @@ [#-- Project Action Status --] [#assign currentCycleYear= currentCycleYear /] - [#assign submission = action.isProjectSubmitted(project.id) /] - + [#if centerGlobalUnit] + [#assign submission = action.isSubmit(project.id,(currentCycleYear-1),"Reporting") /] + [#else] + [#assign submission = action.isProjectSubmitted(project.id) /] + [/#if] [#-- CRP Project --] [#if isCrpProject] [#if !project.projectInfo.isProjectEditLeader()] @@ -157,8 +196,7 @@ [#if !reportingActive]

Ready for PL

[/#if] [#else] Submitted - [/#if] - + [/#if] [#-- Status --] [#if reportingActive]

${(project.projectInfo.statusName)!}

@@ -167,8 +205,24 @@ [/#if]
+ [#if isCrpProject] + [#assign centerMappingComplete = action.isCenterMappingComplete(project.id,project.projectInfo.phase) /] + [#else] + [#assign centerMappingComplete = action.isCompleteCenterProject(project.id) /] + [/#if] + [#if centerMappingComplete!] + + [#else] + + + + [/#if] + [#if action.getActualPhase().crp.id != 29] @@ -176,6 +230,7 @@ [/#if] [#if canEdit && isProjectNew && action.deletePermission(project.id) && action.getActualPhase().editable && project.projectInfo.phase.id=action.getActualPhase().id] diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/annualReport2018/AR2018_outcomeMilestones.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/annualReport2018/AR2018_outcomeMilestones.ftl index 69a74b1dc7..95e7f548f0 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/annualReport2018/AR2018_outcomeMilestones.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/annualReport2018/AR2018_outcomeMilestones.ftl @@ -545,29 +545,26 @@ [#-- Links to evidence --] -
[@customForm.textArea name="${customName}.evidenceLink" value="${(annualReportElement.evidenceLink)!}" i18nkey="${customLabel}.milestoneEvidenceLink" help="${customLabel}.milestoneEvidenceLink.help" helpIcon=false display=true required=false editable=editable /] [#-- ${annualReportElement.id} ${customName} --] - [#if action.isSelectedPhaseAR2021()] -
- - [#if editable] - -
- [/#if] -
- [#-- Element item Template --] -
- [@customForm.multiInput name="${customName}.links" element={} index=-1 template=true class="links" placeholder="global.webSiteLink.placeholder" /] -
+
+ + [#if editable] + +
[/#if] +
+ [#-- Element item Template --] +
+ [@customForm.multiInput name="${customName}.links" element={} index=-1 template=true class="links" placeholder="global.webSiteLink.placeholder" /] +
diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/buttons-projects.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/buttons-projects.ftl index 625ac651d4..c3b154ba6d 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/buttons-projects.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/buttons-projects.ftl @@ -1,64 +1,64 @@ -[#ftl] - -[#-- Project identifiers --] -[#if (project.id?has_content)!false] - [#assign auditObject = (project)!{} ] - [#assign auditObjectID = auditObject['id'] ] - [#assign auditObjectName = "projectID" ] - - - - -[/#if] - -[#-- Policy identifiers --] -[#if (policy.id?has_content)!false] - [#assign auditObject = (policy)!{} ] - [#assign auditObjectID = auditObject['id'] ] - [#assign auditObjectName = "policyID" ] - - -[/#if] - - -[#-- General identifiers --] - - - - - - - -[#assign recordsList = (action.getListLog(auditObject))!{} /] - -
-
- [#-- History Log --] - [#if recordsList?has_content] - [#import "/WEB-INF/global/macros/logHistory.ftl" as logHistory /] - [@logHistory.logList list=recordsList itemName=auditObjectName itemId=auditObjectID /] - [@s.text name="form.buttons.history" /] - [/#if] - [#if (editable || action.canModifiedProjectStatus()) && !(transaction??)] - [#-- Discard Button --] - [@s.submit type="button" cssStyle="display:none" name="cancel" cssClass="button-cancel"] [@s.text name="form.buttons.discard" /] [/@s.submit] - [#-- Save Button --] - [@s.submit type="button" name="save" cssClass="button-save"] [@s.text name="form.buttons.save" /] [/@s.submit] - [#-- Replicate to the next upkeep --] - [#include "/WEB-INF/global/pages/replicateButton.ftl" /] - [#elseif canEdit || action.canModifiedProjectStatus() ] - [#-- Edit Button --] - [@s.text name="form.buttons.edit" /] - [/#if] -
-
- -[#-- Last update message --] -[#if recordsList?has_content] -[#assign lastRecord = recordsList[0] /] -
- - Last edit was made on ${(lastRecord.createdDate)?datetime} ${(timeZone)!} by ${lastRecord.user.composedCompleteName} - -[/#if] - +[#ftl] + +[#-- Project identifiers --] +[#if (project.id?has_content)!false] + [#assign auditObject = (project)!{} ] + [#assign auditObjectID = auditObject['id'] ] + [#assign auditObjectName = "projectID" ] + + + + +[/#if] + +[#-- Policy identifiers --] +[#if (policy.id?has_content)!false] + [#assign auditObject = (policy)!{} ] + [#assign auditObjectID = auditObject['id'] ] + [#assign auditObjectName = "policyID" ] + + +[/#if] + + +[#-- General identifiers --] + + + + + + + +[#assign recordsList = (action.getListLog(auditObject))!{} /] + +
+
+ [#-- History Log --] + [#if recordsList?has_content] + [#import "/WEB-INF/global/macros/logHistory.ftl" as logHistory /] + [@logHistory.logList list=recordsList itemName=auditObjectName itemId=auditObjectID /] + [@s.text name="form.buttons.history" /] + [/#if] + [#if (editable || action.canModifiedProjectStatus()) && !(transaction??)] + [#-- Discard Button --] + [@s.submit type="button" cssStyle="display:none" name="cancel" cssClass="button-cancel"] [@s.text name="form.buttons.discard" /] [/@s.submit] + [#-- Save Button --] + [@s.submit type="button" name="save" cssClass="button-save"] [@s.text name="form.buttons.save" /] [/@s.submit] + [#-- Replicate to the next upkeep --] + [#include "/WEB-INF/global/pages/replicateButton.ftl" /] + [#elseif (canEdit || action.canModifiedProjectStatus() && isGlobalUnitProject )] + [#-- Edit Button --] + [@s.text name="form.buttons.edit" /] + [/#if] +
+
+ +[#-- Last update message --] +[#if recordsList?has_content] +[#assign lastRecord = recordsList[0] /] +
+ + Last edit was made on ${(lastRecord.createdDate)?datetime} ${(timeZone)!} by ${lastRecord.user.composedCompleteName} + +[/#if] + diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/menu-projects.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/menu-projects.ftl index 358ff1617f..1e9c45048a 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/menu-projects.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/menu-projects.ftl @@ -90,7 +90,15 @@
    [#list menu.items as item] [#if (item.showCheck)!true] - [#assign submitStatus = (action.getProjectSectionStatus(item.action, projectID))!false /] + [#if centerGlobalUnit!] + [#if isCrpProject] + [#assign submitStatus = (action.getProjectCenterSectionStatus(item.action, projectID,project.projectInfo.phase))!false /] + [#else] + [#assign submitStatus = (action.getProjectSectionStatus(item.action, projectID))!false /] + [/#if] + [#else] + [#assign submitStatus = (action.getProjectSectionStatus(item.action, projectID))!false /] + [/#if] [/#if] [#assign hasDraft = (action.getAutoSaveFilePath(project.class.simpleName, item.action, project.id))!false /] [#if (item.show)!true ] diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectBudgetByPartners.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectBudgetByPartners.ftl index b040061f49..7c51adab1e 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectBudgetByPartners.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectBudgetByPartners.ftl @@ -10,6 +10,7 @@ [#assign customCSS = ["${baseUrlMedia}/css/projects/projectBudgetByPartners.css"] /] [#assign currentSection = "projects" /] [#assign currentStage = "budgetByPartners" /] +[#assign isCrpProject = (action.isProjectCrpOrPlatform(project.id))!false ] [#assign breadCrumb = [ {"label":"projectsList", "nameSpace":"/projects", "action":"${(crpSession)!}/projectsList"}, @@ -430,12 +431,24 @@ [/#if]

    - [#if !isTemplate] - + [#if !isTemplate] + [#if centerGlobalUnit] + [#if !isCrpProject] + + [/#if] + [#else] + + [/#if] [/#if]

    ${(element.fundingSource.fundingSourceInfo.title)!}

    [#if !isTemplate] -
    + [#if centerGlobalUnit] + [#if !isCrpProject] + + [/#if] + [#else] + + [/#if] [/#if] diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectCenterPrograms.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectCenterPrograms.ftl index fce45ec05c..7e0f80a27c 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectCenterPrograms.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectCenterPrograms.ftl @@ -55,7 +55,7 @@
    [#-- CENTER Research program --]
    - [@customForm.select name="project.projectInfo.liaisonInstitutionCenter.id" listName="liaisonInstitutions" paramText="${currentCrp.acronym}" keyFieldName="id" displayFieldName="composedName" i18nkey="CIAT Program" className="liaisonInstitutionSelect" help="project.researchProgram.help" required=true editable=editable /] + [@customForm.select name="project.projectInfo.liaisonInstitutionCenter.id" listName="liaisonInstitutions" paramText="${currentCrp.acronym}" keyFieldName="id" displayFieldName="composedName" i18nkey="CIAT Program" className="liaisonInstitutionSelect" help="project.researchProgram.help" required=true editable=(editable && canMapPrograms) /]
    @@ -64,7 +64,7 @@

    ${crpSession} Program(s)

    [#list (programFlagships)![] as element] - [@customForm.checkmark id="program-${element.id}" name="project.flagshipValue" label="${element.centerComposedName}" value="${element.id}" editable=editable checked=(flagshipIds?seq_contains(element.id))!false cssClass="fpInput getCenterOutcomes" cssClassLabel="font-normal" /] + [@customForm.checkmark id="program-${element.id}" name="project.flagshipValue" label="${element.centerComposedName}" value="${element.id}" editable=(editable && canMapPrograms) checked=(flagshipIds?seq_contains(element.id))!false cssClass="fpInput getCenterOutcomes" cssClassLabel="font-normal" /]
    [/#list]
    @@ -72,7 +72,7 @@

    Regional Office(s)

    [#list (regionFlagships)![] as element] - [@customForm.checkmark id="region-${element.id}" name="project.regionsValue" label="${element.name}" value="${element.id}" editable=editable checked=((regionsIds?seq_contains(element.id))!false) cssClass="rpInput" cssClassLabel="font-normal" /] + [@customForm.checkmark id="region-${element.id}" name="project.regionsValue" label="${element.name}" value="${element.id}" editable=(editable && canMapPrograms) checked=((regionsIds?seq_contains(element.id))!false) cssClass="rpInput" cssClassLabel="font-normal" /]
    [/#list]
    diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectInnovation.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectInnovation.ftl index 2e01525729..019fe0959d 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectInnovation.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectInnovation.ftl @@ -4,8 +4,8 @@ [#-- TODO: Remove unused pageLibs--] [#assign pageLibs = ["select2","font-awesome", "flag-icon-css"] /] [#assign customJS = [ - "${baseUrlMedia}/js/projects/projectInnovations.js?20220107A", - "${baseUrlCdn}/global/js/autoSave.js", + "${baseUrlMedia}/js/projects/projectInnovations.js?20220303A", + [#-- "${baseUrlCdn}/global/js/autoSave.js", --] "${baseUrlCdn}/global/js/fieldsValidation.js" ] /] [#assign customCSS = [ @@ -246,7 +246,7 @@ [#-- Or Deliverable ID (optional) --]
    - [@customForm.elementsListComponent name="innovation.deliverables" elementType="deliverable" elementList=innovation.deliverables label="projectInnovations.deliverableId" listName="deliverableList" required=false keyFieldName="id" displayFieldName="tagTitle"/] + [@customForm.elementsListComponentInnovation name="innovation.deliverables" elementType="deliverable" elementList=innovation.deliverables label="projectInnovations.deliverableId" listName="deliverableList" required=false keyFieldName="id" displayFieldName="tagTitle"/]

diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectPolicies.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectPolicies.ftl index 1d53f64ee1..12d6eaa055 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectPolicies.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectPolicies.ftl @@ -177,4 +177,4 @@
-[/#macro] +[/#macro] \ No newline at end of file diff --git a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectsList.ftl b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectsList.ftl index 9fc50f0a26..5f14096967 100644 --- a/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectsList.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/crp/views/projects/projectsList.ftl @@ -1,7 +1,7 @@ [#ftl] [#assign title = "MARLO Projects" /] [#assign currentSectionString = "${actionName?replace('/','-')}-phase-${(actualPhase.id)!}" /] -[#assign pageLibs = ["datatables.net", "datatables.net-bs","font-awesome"] /] +[#assign pageLibs = ["datatables.net", "datatables.net-bs","font-awesome","malihu-custom-scrollbar-plugin"] /] [#assign customJS = [ "https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js", "//cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js", @@ -59,20 +59,31 @@
[#-- Projects List (My Projects) --] -

[@s.text name="projectsList.yourProjects"/]

- [@projectList.projectsList projects=myProjects canValidate=true canEdit=true namespace="/projects" defaultAction="${(crpSession)!}/description" /] -
- [#-- Projects List (Other Projects) --] -

[@s.text name="projectsList.otherProjects" /]
[@s.text name="projectsList.otherProjects.help" /]

- [@projectList.projectsList projects=allProjects canValidate=true namespace="/projects" defaultAction="${(crpSession)!}/description"/] -
- [#if !reportingActive] -
- [#-- Archived Projects List (My Projects) --] -

[@s.text name="projectsList.archivedProjects"/]

- [@projectList.projectsListArchived projects=(closedProjects)! canValidate=false canEdit=false namespace="/projects" defaultAction="${(crpSession)!}/description" /] -
- [/#if] + [#if !centerGlobalUnit] +

[@s.text name="projectsList.yourProjects"/]

+ [@projectList.projectsList projects=myProjects canValidate=true canEdit=true namespace="/projects" defaultAction="${(crpSession)!}/description" /] +
+ [#-- Projects List (Other Projects) --] +

[@s.text name="projectsList.otherProjects" /]
[@s.text name="projectsList.otherProjects.help" /]

+ [@projectList.projectsList projects=allProjects canValidate=true namespace="/projects" defaultAction="${(crpSession)!}/description"/] + [/#if] + [#if centerGlobalUnit] +

[@s.text name="projectsList.yourProjects"/]

+ [@projectList.projectsList projects=allCenterProjects canValidate=true canEdit=true namespace="/projects" defaultAction="${(crpSession)!}/description" /] +
+ [#-- Projects List (Other Projects) --] +

[@s.text name="projectsList.otherProjects" /]
[@s.text name="projectsList.otherProjects.help" /]

+ [@projectList.projectsList projects=allNotCenterProjects canValidate=true namespace="/projects" defaultAction="${(crpSession)!}/description"/] + [/#if] +
+ [#if !reportingActive] +
+ [#-- Archived Projects List (My Projects) --] +

[@s.text name="projectsList.archivedProjects"/]

+ [@projectList.projectsListArchived projects=(closedProjects)! canValidate=false canEdit=false namespace="/projects" defaultAction="${(crpSession)!}/description" /] +
+ [/#if] + [#-- Section Buttons --] diff --git a/marlo-web/src/main/webapp/WEB-INF/global/macros/forms.ftl b/marlo-web/src/main/webapp/WEB-INF/global/macros/forms.ftl index 5fd14ecc51..376e44398c 100644 --- a/marlo-web/src/main/webapp/WEB-INF/global/macros/forms.ftl +++ b/marlo-web/src/main/webapp/WEB-INF/global/macros/forms.ftl @@ -767,12 +767,13 @@ [/#macro] -[#macro listElementMacro element name type id="" index=-1 keyFieldName="id" displayFieldName="composedName" indexLevel=1 template=false hasPrimary=false isEditable=true onlyElementIDs=false] +[#macro listElementMacro element name type id="" index=-1 keyFieldName="id" displayFieldName="composedName" indexLevel=1 template=false hasPrimary=false isEditable=true onlyElementIDs=false deliverableURL=""] [#local customName = "${template?string('_TEMPLATE_', '')}${name}[${index}]"] [#local composedID = "${type}" /] [#if id?has_content] [#local composedID = "${type}-${id}" /] [/#if] + [#local url][@s.url namespace="/projects" action="${(crpSession)!}/deliverable"][@s.param name='deliverableID']${(element.deliverable.id)!}[/@s.param][#include "/WEB-INF/global/pages/urlGlobalParams.ftl" /][/@s.url][/#local] [#if hasPrimary] [#attempt] [#if template] @@ -802,7 +803,7 @@ [#-- Title --] - ${(element[type][displayFieldName])!'{elementNameUndefined}'} + [#if deliverableURL == ""]${(element[type][displayFieldName])!'{elementNameUndefined}'}[#else](D${(element[type][keyFieldName])!}) ${(element[type].getDeliverableInfo().getDeliverableType().getName())!} - ${(element[type].getDeliverableInfo().getTitle())!} - ${deliverableURL}[/#if] @@ -814,7 +815,7 @@ [#-- Remove button --] [#if isEditable]
[/#if] [#-- Title --] - ${(element[type][displayFieldName])!'{elementNameUndefined}'} + [#if deliverableURL == ""]${(element[type][displayFieldName])!'{elementNameUndefined}'}[#else](D${(element[type][keyFieldName])!}) ${(element[type].getDeliverableInfo().getDeliverableType().getName())!} - ${(element[type].getDeliverableInfo().getTitle())!} - ${deliverableURL}[/#if] [/#if] [/#macro] @@ -872,4 +873,52 @@ [/#if] +[/#macro] + +[#macro elementsListComponentInnovation name elementType id="" elementList=[] label="" paramText="" help="" helpIcon=true listName="" keyFieldName="" displayFieldName="" maxLimit=0 indexLevel=1 required=true hasPrimary=false forceEditable=false onlyElementIDs=false i18nkey=""] + [#attempt] + [#local list = ((listName?eval)?sort_by((displayFieldName?split("."))))![] /] + [#recover] + [#local list = [] /] + [/#attempt] + + [#local composedID = "${elementType}" /] + [#if id?has_content] + [#local composedID = "${elementType}-${id}" /] + [/#if] + +
+
+ +
+
+ +
    + [#if elementList?has_content] + [#if hasPrimary][/#if] + [#if editable || forceEditable] + [#list elementList as item] + [#assign deliverableURL = (item.deliverable.getDisseminationUrl(actualPhase))!'not defined'] + [@listElementMacro name=name element=item type=elementType id=id index=item_index keyFieldName=keyFieldName displayFieldName=displayFieldName indexLevel=indexLevel hasPrimary=hasPrimary isEditable=(editable || forceEditable) deliverableURL=deliverableURL/] + [/#list] + [/#if] +
+ + [#else] + [#if !(elementList?has_content)]

No entries added yet.

[/#if] + [/#if] +
+ [#-- Element item Template --] +
    + [@listElementMacro name="${name}" element={} type=elementType id=id index=-1 indexLevel=indexLevel template=true hasPrimary=hasPrimary onlyElementIDs=onlyElementIDs isEditable=(editable || forceEditable) /] +
+
[/#macro] \ No newline at end of file diff --git a/marlo-web/src/main/webapp/WEB-INF/swagger/dist/index.html b/marlo-web/src/main/webapp/WEB-INF/swagger/dist/index.html index 7799f95a0f..64692e5291 100644 --- a/marlo-web/src/main/webapp/WEB-INF/swagger/dist/index.html +++ b/marlo-web/src/main/webapp/WEB-INF/swagger/dist/index.html @@ -84,6 +84,16 @@ + + diff --git a/marlo-web/src/main/webapp/WEB-INF/swagger/dist/partners.html b/marlo-web/src/main/webapp/WEB-INF/swagger/dist/partners.html index 9e1071e3b3..143d59e6b9 100644 --- a/marlo-web/src/main/webapp/WEB-INF/swagger/dist/partners.html +++ b/marlo-web/src/main/webapp/WEB-INF/swagger/dist/partners.html @@ -78,7 +78,7 @@