Commit c4b0ca36 authored by François-Xavier Lebastard's avatar François-Xavier Lebastard
Browse files

UNOTOPLYS-163 feat(liste ecrans) : création du web service pour récupérer les...

UNOTOPLYS-163 feat(liste ecrans) : création du web service pour récupérer les écrans et branchement sur le front
parent 499515db
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -18,6 +18,7 @@ import org.hibernate.annotations.Type;
@Table(name = "screen")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Screen implements Serializable {
private static final long serialVersionUID = 1L;
@Id
......@@ -69,6 +70,12 @@ public class Screen implements Serializable {
@JsonIgnoreProperties(value = { "screens", "variables", "workspace" }, allowSetters = true)
private Form form;
/**
* La position de l'écran dans le back-office.
*/
@Column(name = "index")
private Integer index;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return id;
......@@ -193,6 +200,14 @@ public class Screen implements Serializable {
this.form = form;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
......
......@@ -65,8 +65,6 @@ public class FilArianeController {
public String getUserHome() {
if (PermissionService.currentUserHasAuthority(AuthoritiesConstants.AUTHORITY_VIEW_WORKSPACE)) {
return Path.LIST_WORKSPACES;
} else if (PermissionService.currentUserHasAuthority(AuthoritiesConstants.AUTHORITY_VIEW_FORMS)) {
return Path.LIST_FORMS;
} else if (PermissionService.currentUserHasAuthority(AuthoritiesConstants.AUTHORITY_VIEW_FORM)) {
return Path.LIST_FORMS;
}
......
package com.unantes.orientactive.repository;
import com.unantes.orientactive.domain.Screen;
import java.util.List;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.validation.constraints.NotNull;
import java.util.Optional;
/**
* Repository des écrans.
*/
@SuppressWarnings("unused")
@Repository
public interface ScreenRepository extends JpaRepository<Screen, Long> {
/**
* Récupération d'un écran par sa référence.
*
......@@ -30,7 +29,10 @@ public interface ScreenRepository extends JpaRepository<Screen, Long> {
* @param formId L'identifiant du formulaire.
* @return Le premier écran du formulaire s'il existe.
*/
@Query(value = "select * from screen join form on form.id = screen.form_id where screen.previous_id is null and form.id = :formId", nativeQuery = true)
@Query(
value = "select * from screen join form on form.id = screen.form_id where screen.previous_id is null and form.id = :formId",
nativeQuery = true
)
Optional<Screen> findFirstScreenOfForm(final @Param("formId") Long formId);
/**
......@@ -40,7 +42,10 @@ public interface ScreenRepository extends JpaRepository<Screen, Long> {
* @param sessionId L'identifiant de la session de l'utilisateur.
* @return L'écran précédent s'il existe.
*/
@Query(value = "select * from screen where id = (select previous.screen_id from answer current join answer previous on current.previous_id = previous.id where current.screen_id = :currentScreenId and current.session_id = :sessionId)", nativeQuery = true)
@Query(
value = "select * from screen where id = (select previous.screen_id from answer current join answer previous on current.previous_id = previous.id where current.screen_id = :currentScreenId and current.session_id = :sessionId)",
nativeQuery = true
)
Optional<Screen> findPreviousScreen(final @Param("currentScreenId") Long currentScreenId, final @Param("sessionId") String sessionId);
/**
......@@ -50,7 +55,10 @@ public interface ScreenRepository extends JpaRepository<Screen, Long> {
* @param sessionId L'identifiant de la session de l'utilisateur.
* @return L'écran suivant s'il existe.
*/
@Query(value = "select * from screen where id = (select next.screen_id from answer current join answer next on next.previous_id = current.id where current.screen_id = :currentScreenId and current.session_id = :sessionId)", nativeQuery = true)
@Query(
value = "select * from screen where id = (select next.screen_id from answer current join answer next on next.previous_id = current.id where current.screen_id = :currentScreenId and current.session_id = :sessionId)",
nativeQuery = true
)
Optional<Screen> findNextScreen(final @Param("currentScreenId") Long currentScreenId, final @Param("sessionId") String sessionId);
/**
......@@ -62,6 +70,21 @@ public interface ScreenRepository extends JpaRepository<Screen, Long> {
* @param screenId L'identifiant de l'écran.
* @return Le nombre d'écran potentiellement restant.
*/
@Query(value = "WITH RECURSIVE previous AS (SELECT id, previous_id FROM screen WHERE id = :screenId UNION SELECT s.id, s.previous_id FROM screen s INNER JOIN previous p ON p.previous_id = s.id) SELECT (select count(*) from screen where form_id = :formId) - count(pr.*) FROM previous pr", nativeQuery = true)
@Query(
value = "WITH RECURSIVE previous AS (SELECT id, previous_id FROM screen WHERE id = :screenId UNION SELECT s.id, s.previous_id FROM screen s INNER JOIN previous p ON p.previous_id = s.id) SELECT (select count(*) from screen where form_id = :formId) - count(pr.*) FROM previous pr",
nativeQuery = true
)
int countScreenLeft(final @Param("formId") Long formId, final @Param("screenId") Long screenId);
/**
* Retourne les écrans d'un formulaire selon les permissions d'un utilisateur
* @param idUser identifiant d'utilisateur
* @param idForm identifiant de formulaire
* @return
*/
@Query(
value = "select screen.* from form f join scope_form sf on sf.id_form = f.id join scope s on s.id = sf.id_scope join screen on f.id = screen.form_id join jhi_user u on u.id = s.id_user where u.id = :idUser and f.id = :idForm",
nativeQuery = true
)
List<Screen> findWithPermission(@Param("idUser") Long idUser, @Param("idForm") Long idForm);
}
......@@ -19,8 +19,6 @@ public final class AuthoritiesConstants {
public static final SimpleGrantedAuthority AUTHORITY_VIEW_WORKSPACE = new SimpleGrantedAuthority(VIEW_WORKSPACE);
public static final String EDIT_WORKSPACE = "EDIT_WORKSPACE";
public static final SimpleGrantedAuthority AUTHORITY_EDIT_WORKSPACE = new SimpleGrantedAuthority(EDIT_WORKSPACE);
public static final String VIEW_FORMS = "VIEW_FORMS";
public static final SimpleGrantedAuthority AUTHORITY_VIEW_FORMS = new SimpleGrantedAuthority(VIEW_FORMS);
public static final String VIEW_FORM = "VIEW_FORM";
public static final SimpleGrantedAuthority AUTHORITY_VIEW_FORM = new SimpleGrantedAuthority(VIEW_FORM);
public static final String EDIT_FORM = "EDIT_FORM";
......
......@@ -9,23 +9,23 @@ import com.unantes.orientactive.security.permissions.Role;
import com.unantes.orientactive.service.dto.AdminUserDTO;
import com.unantes.orientactive.service.dto.FormDTO;
import com.unantes.orientactive.service.mapper.FormMapper;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Service Implementation for managing {@link Form}.
*/
@Service
@Transactional
public class FormService extends PermissionService<FormDTO> {
private final Logger log = LoggerFactory.getLogger(FormService.class);
private final FormRepository formRepository;
......@@ -175,7 +175,7 @@ public class FormService extends PermissionService<FormDTO> {
formRepository.removePermission(user.getId(), element.getId());
}
@PreAuthorize("hasAuthority('VIEW_FORMS')")
@PreAuthorize("hasAuthority('VIEW_FORM')")
@Override
protected List<FormDTO> findWithPermission(User user, Long idParentElement) {
return formRepository
......@@ -185,7 +185,7 @@ public class FormService extends PermissionService<FormDTO> {
.collect(Collectors.toList());
}
@PreAuthorize("hasAuthority('VIEW_FORMS')")
@PreAuthorize("hasAuthority('VIEW_FORM')")
@Override
public List<FormDTO> findAllByParent(Long idParentElement) {
return formRepository
......@@ -195,7 +195,7 @@ public class FormService extends PermissionService<FormDTO> {
.collect(Collectors.toCollection(LinkedList::new));
}
@PreAuthorize("hasAuthority('VIEW_FORMS')")
@PreAuthorize("hasAuthority('VIEW_FORM')")
@Override
protected boolean hasWildcard(User user) {
return formRepository.hasWildcard(user.getId(), Role.CONTRIBUTEUR.getId());
......@@ -206,9 +206,13 @@ public class FormService extends PermissionService<FormDTO> {
return userService.findAllWithPermissionOnForm(Role.CONTRIBUTEUR.getId(), element.getId());
}
@PreAuthorize("hasAuthority('VIEW_FORMS')")
@Override
protected boolean existPermission(User user, FormDTO element) {
return formRepository.existPermission(user.getId(), element.getId());
return existPermission(user, element.getId());
}
@PreAuthorize("hasAuthority('VIEW_FORM')")
protected boolean existPermission(User user, Long formId) {
return formRepository.existPermission(user.getId(), formId);
}
}
package com.unantes.orientactive.service;
import com.unantes.orientactive.domain.Screen;
import com.unantes.orientactive.domain.User;
import com.unantes.orientactive.repository.ScreenRepository;
import com.unantes.orientactive.service.dto.ScreenDTO;
import com.unantes.orientactive.service.dto.ScreenPanelDTO;
import com.unantes.orientactive.service.mapper.ScreenMapper;
import com.unantes.orientactive.service.mapper.ScreenPanelMapper;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
/**
......@@ -24,15 +25,27 @@ import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ScreenService {
private final Logger log = LoggerFactory.getLogger(ScreenService.class);
private final ScreenRepository screenRepository;
private final ScreenMapper screenMapper;
public ScreenService(ScreenRepository screenRepository, ScreenMapper screenMapper) {
private final ScreenPanelMapper screenPanelMapper;
private final FormService formService;
public ScreenService(
ScreenRepository screenRepository,
ScreenMapper screenMapper,
ScreenPanelMapper screenPanelMapper,
FormService formService
) {
this.screenRepository = screenRepository;
this.screenMapper = screenMapper;
this.screenPanelMapper = screenPanelMapper;
this.formService = formService;
}
/**
......@@ -180,4 +193,22 @@ public class ScreenService {
);
return screenRepository.countScreenLeft(formId, screenId);
}
/**
* Retourne les écrans du formulaire.
*
* @param formId
* @param user
* @return
*/
@Transactional(readOnly = true)
public List<ScreenPanelDTO> findScreenByFormId(Long formId, User user) {
if (!formService.existPermission(user, formId)) {
throw new AccessDeniedException("Action non autorisée");
}
final List<Screen> screens = screenRepository.findWithPermission(user.getId(), formId);
List<ScreenPanelDTO> screenPanelDTOS = screenPanelMapper.toDto(screens);
Collections.sort(screenPanelDTOS);
return screenPanelDTOS;
}
}
package com.unantes.orientactive.service.dto;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* DTO pour le panel des écrans : pour éviter de charger des données inutiles.
*/
public class ScreenPanelDTO implements Serializable, Comparable {
private String title;
private Integer index;
private Long id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScreenPanelDTO that = (ScreenPanelDTO) o;
return new EqualsBuilder().append(id, that.id).append(index, that.index).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37).append(id).append(index).toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this).append("title", title).append("index", index).append("id", id).toString();
}
@Override
public int compareTo(Object that) {
if (this.equals(that)) {
return 0;
}
return this.index.compareTo(((ScreenPanelDTO) that).getIndex());
}
}
package com.unantes.orientactive.service.mapper;
import com.unantes.orientactive.domain.Screen;
import com.unantes.orientactive.service.dto.ScreenPanelDTO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
/**
* Mapper for the entity {@link Screen} and its DTO {@link ScreenPanelDTO}.
*/
@Mapper(componentModel = "spring")
public interface ScreenPanelMapper extends EntityMapper<ScreenPanelDTO, Screen> {
@Mapping(source = "name", target = "title")
ScreenPanelDTO toDto(Screen screen);
}
package com.unantes.orientactive.web.rest;
import com.unantes.orientactive.domain.User;
import com.unantes.orientactive.service.ScreenService;
import com.unantes.orientactive.service.UserService;
import com.unantes.orientactive.service.dto.ScreenDTO;
import com.unantes.orientactive.service.dto.ScreenPanelDTO;
import com.unantes.orientactive.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
......@@ -13,6 +17,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
......@@ -31,6 +36,7 @@ import tech.jhipster.web.util.ResponseUtil;
@RestController
@RequestMapping("/api")
public class ScreenResource {
private final Logger log = LoggerFactory.getLogger(ScreenResource.class);
private static final String ENTITY_NAME = "screen";
......@@ -40,8 +46,11 @@ public class ScreenResource {
private final ScreenService screenService;
public ScreenResource(ScreenService screenService) {
private final UserService userService;
public ScreenResource(ScreenService screenService, UserService userService) {
this.screenService = screenService;
this.userService = userService;
}
/**
......@@ -64,6 +73,13 @@ public class ScreenResource {
.body(result);
}
@GetMapping("/forms/{formId}/screens")
public List<ScreenPanelDTO> getScreenByFormId(@PathVariable Long formId, Principal principal) {
final Optional<User> userOptional = userService.getUserWithAuthoritiesByLogin(principal.getName());
final User user = userOptional.orElseThrow(() -> new UsernameNotFoundException(principal.getName()));
return screenService.findScreenByFormId(formId, user);
}
/**
* {@code PUT /screens} : Updates an existing screen.
*
......
package com.unantes.orientactive.web.rest.errors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Exception lancée si un appel est fait à l'API avec un identifiant de form non existant.
*/
public class FormNotFoundException extends RuntimeException {
private static final Logger LOGGER = LoggerFactory.getLogger(FormNotFoundException.class);
private Long idForm;
public FormNotFoundException(String message, Long idForm) {
super(message);
this.idForm = idForm;
LOGGER.error(message);
LOGGER.error("Form non trouvé : {}", idForm);
}
}
......@@ -3,7 +3,6 @@ insert into jhi_authority (name) values ('VIEW_ORGANIZATION');
insert into jhi_authority (name) values ('EDIT_ORGANIZATION');
insert into jhi_authority (name) values ('VIEW_WORKSPACE');
insert into jhi_authority (name) values ('EDIT_WORKSPACE');
insert into jhi_authority (name) values ('VIEW_FORMS');
insert into jhi_authority (name) values ('VIEW_FORM');
insert into jhi_authority (name) values ('EDIT_FORM');
insert into jhi_authority (name) values ('VIEW_RESULT');
......@@ -15,7 +15,6 @@ insert into role_jhi_authority (id_role, id_jhi_authority) values (2, 'EDIT_WORK
insert into role_jhi_authority (id_role, id_jhi_authority) values (3, 'VIEW_WORKSPACE');
insert into role_jhi_authority (id_role, id_jhi_authority) values (3, 'EDIT_WORKSPACE');
insert into role_jhi_authority (id_role, id_jhi_authority) values (3, 'VIEW_FORMS');
insert into role_jhi_authority (id_role, id_jhi_authority) values (3, 'VIEW_FORM');
insert into role_jhi_authority (id_role, id_jhi_authority) values (3, 'EDIT_FORM');
......
......@@ -34,6 +34,7 @@
<include file="config/liquibase/changelog/20210322164500_authorities.sql" relativeToChangelogFile="false"/>
<include file="config/liquibase/changelog/20210322171800_role_authorities.sql" relativeToChangelogFile="false"/>
<include file="config/liquibase/changelog/20210323110900_add_authorities_admin.sql" relativeToChangelogFile="false"/>
<include file="config/liquibase/changelog/20210414161316_update_entity_Screen.xml" relativeToChangelogFile="false"/>
<!-- jhipster-needle-liquibase-add-constraints-changelog - JHipster will add liquibase constraints changelogs here -->
<!-- jhipster-needle-liquibase-add-incremental-changelog - JHipster will add incremental liquibase changelogs here -->
</databaseChangeLog>
......@@ -9,21 +9,9 @@ import Icon from '@/components/icon/icon.vue';
},
})
export default class Panel extends Vue {
private panelScreensTmp = [
{
index: 1,
title: 'Écran 1',
},
{
index: 2,
title: 'Écran 2 avec un intitulé d’écran beaucoup trop long, beaucoup trop long pour être confortablement inséré ici',
},
{
index: 3,
title: 'Écran 3',
current: true,
},
];
public get screenList(): boolean {
return this.$store.getters.screenList;
}
public get idWorkspace(): string {
return this.$store.getters.idWorkspace;
......
......@@ -15,7 +15,7 @@
</div>
<ol class="p-2 text-sm select-none">
<li
v-for="panelScreen in panelScreensTmp"
v-for="panelScreen in screenList"
:key="panelScreen.index"
:class="[
'flex items-center p-1 leading-tight transition rounded-md cursor-pointer group hover:absolute focus:ring ',
......
......@@ -18,6 +18,19 @@ export default class ScreenService {
});
}
public findByFormId(id: number): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.get(`api/forms/${id}/screens`)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public retrieve(): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
......
import { Module } from 'vuex';
import FormService from '@/entities/form/form.service';
import ScreenService from '@/entities/screen/screen.service';
const formService = new FormService();
const screenService = new ScreenService();
export const formStore: Module<any, any> = {
state: {
idForm: 0,
form: null,
screenList: [],
screenList: null,
},
getters: {
idForm: state => state.idForm,
form: state => state.form,
screenList: state => state.screenList,
},
actions: {},
actions: {
loadScreens({ commit }, idForm) {
screenService.findByFormId(idForm).then(res => {
commit('setScreenList', res);
});
},
},
mutations: {
setIdForm(state, idForm) {
state.idForm = idForm;
......
......@@ -20,7 +20,8 @@ export default class FormEdit extends Vue {
beforeRouteEnter(to, from, next) {
next(vm => {
vm.$store.commit('setIdWorkspace', to.params.idWorkspace);
vm.$store.commit('setIdForm', to.params.idForm); // dispatch screenList sur une nouvelle action du store form
vm.$store.commit('setIdForm', to.params.idForm);
vm.$store.dispatch('loadScreens', to.params.idForm);