diff --git a/.jhipster/Asset.json b/.jhipster/Asset.json index 62a805e7..2fe0d88c 100644 --- a/.jhipster/Asset.json +++ b/.jhipster/Asset.json @@ -49,7 +49,7 @@ "otherEntityField": "admissionDocumentDate" } ], - "changelogDate": "20190430150327", + "changelogDate": "20190430152139", "entityTableName": "asset", "dto": "mapstruct", "pagination": "infinite-scroll", diff --git a/.jhipster/Customer.json b/.jhipster/Customer.json index d27cac6f..ee92a803 100644 --- a/.jhipster/Customer.json +++ b/.jhipster/Customer.json @@ -142,7 +142,7 @@ "relationshipName": "sepamandate" } ], - "changelogDate": "20190430150324", + "changelogDate": "20190430152136", "entityTableName": "customer", "dto": "mapstruct", "pagination": "infinite-scroll", diff --git a/.jhipster/Membership.json b/.jhipster/Membership.json index 6c9f4b7b..ff3f80e8 100644 --- a/.jhipster/Membership.json +++ b/.jhipster/Membership.json @@ -54,7 +54,7 @@ "otherEntityField": "prefix" } ], - "changelogDate": "20190430150325", + "changelogDate": "20190430152137", "entityTableName": "membership", "dto": "mapstruct", "pagination": "infinite-scroll", diff --git a/.jhipster/SepaMandate.json b/.jhipster/SepaMandate.json index c6733f0f..5ef7a2f8 100644 --- a/.jhipster/SepaMandate.json +++ b/.jhipster/SepaMandate.json @@ -72,7 +72,7 @@ "otherEntityField": "prefix" } ], - "changelogDate": "20190430150328", + "changelogDate": "20190430152140", "entityTableName": "sepa_mandate", "dto": "mapstruct", "pagination": "infinite-scroll", diff --git a/.jhipster/Share.json b/.jhipster/Share.json index d8f3083d..0d92e505 100644 --- a/.jhipster/Share.json +++ b/.jhipster/Share.json @@ -49,7 +49,7 @@ "otherEntityField": "admissionDocumentDate" } ], - "changelogDate": "20190430150326", + "changelogDate": "20190430152138", "entityTableName": "share", "dto": "mapstruct", "pagination": "infinite-scroll", diff --git a/.jhipster/UserRoleAssignment.json b/.jhipster/UserRoleAssignment.json new file mode 100644 index 00000000..92062630 --- /dev/null +++ b/.jhipster/UserRoleAssignment.json @@ -0,0 +1,46 @@ +{ + "name": "UserRoleAssignment", + "fields": [ + { + "fieldName": "entityTypeId", + "fieldType": "String" + }, + { + "fieldName": "entityObjectId", + "fieldType": "Long" + }, + { + "fieldName": "userId", + "fieldType": "Long", + "fieldValidateRules": [ + "required" + ] + }, + { + "fieldName": "assignedRole", + "fieldType": "UserRole", + "fieldValues": "HOSTMASTER,ADMIN,SUPPORTER,CONTRACTUAL_CONTACT,FINANCIAL_CONTACT,TECHNICAL_CONTACT,CUSTOMER_USER", + "fieldValidateRules": [ + "required" + ] + } + ], + "relationships": [ + { + "relationshipType": "many-to-one", + "otherEntityName": "user", + "otherEntityRelationshipName": "required", + "relationshipName": "user", + "otherEntityField": "login" + } + ], + "changelogDate": "20190430152204", + "entityTableName": "user_role_assignment", + "dto": "no", + "pagination": "infinite-scroll", + "service": "serviceClass", + "jpaMetamodelFiltering": true, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/src/main/java/org/hostsharing/hsadminng/domain/UserRoleAssignment.java b/src/main/java/org/hostsharing/hsadminng/domain/UserRoleAssignment.java new file mode 100644 index 00000000..44803a00 --- /dev/null +++ b/src/main/java/org/hostsharing/hsadminng/domain/UserRoleAssignment.java @@ -0,0 +1,152 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.domain; + +import org.hostsharing.hsadminng.domain.enumeration.UserRole; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import java.io.Serializable; +import java.util.Objects; + +import javax.persistence.*; +import javax.validation.constraints.*; + +/** + * A UserRoleAssignment. + */ +@Entity +@Table(name = "user_role_assignment") +public class UserRoleAssignment implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + private Long id; + + @Column(name = "entity_type_id") + private String entityTypeId; + + @Column(name = "entity_object_id") + private Long entityObjectId; + + @NotNull + @Column(name = "user_id", nullable = false) + private Long userId; + + @NotNull + @Enumerated(EnumType.STRING) + @Column(name = "assigned_role", nullable = false) + private UserRole assignedRole; + + @ManyToOne + @JsonIgnoreProperties("requireds") + private User user; + + // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getEntityTypeId() { + return entityTypeId; + } + + public UserRoleAssignment entityTypeId(String entityTypeId) { + this.entityTypeId = entityTypeId; + return this; + } + + public void setEntityTypeId(String entityTypeId) { + this.entityTypeId = entityTypeId; + } + + public Long getEntityObjectId() { + return entityObjectId; + } + + public UserRoleAssignment entityObjectId(Long entityObjectId) { + this.entityObjectId = entityObjectId; + return this; + } + + public void setEntityObjectId(Long entityObjectId) { + this.entityObjectId = entityObjectId; + } + + public Long getUserId() { + return userId; + } + + public UserRoleAssignment userId(Long userId) { + this.userId = userId; + return this; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public UserRole getAssignedRole() { + return assignedRole; + } + + public UserRoleAssignment assignedRole(UserRole assignedRole) { + this.assignedRole = assignedRole; + return this; + } + + public void setAssignedRole(UserRole assignedRole) { + this.assignedRole = assignedRole; + } + + public User getUser() { + return user; + } + + public UserRoleAssignment user(User user) { + this.user = user; + return this; + } + + public void setUser(User user) { + this.user = user; + } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + UserRoleAssignment userRoleAssignment = (UserRoleAssignment) o; + if (userRoleAssignment.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), userRoleAssignment.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "UserRoleAssignment{" + + "id=" + getId() + + ", entityTypeId='" + getEntityTypeId() + "'" + + ", entityObjectId=" + getEntityObjectId() + + ", userId=" + getUserId() + + ", assignedRole='" + getAssignedRole() + "'" + + "}"; + } +} diff --git a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/UserRole.java b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/UserRole.java new file mode 100644 index 00000000..86bfa199 --- /dev/null +++ b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/UserRole.java @@ -0,0 +1,15 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.domain.enumeration; + +/** + * The UserRole enumeration. + */ +public enum UserRole { + HOSTMASTER, + ADMIN, + SUPPORTER, + CONTRACTUAL_CONTACT, + FINANCIAL_CONTACT, + TECHNICAL_CONTACT, + CUSTOMER_USER +} diff --git a/src/main/java/org/hostsharing/hsadminng/repository/UserRoleAssignmentRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/UserRoleAssignmentRepository.java new file mode 100644 index 00000000..167f37a0 --- /dev/null +++ b/src/main/java/org/hostsharing/hsadminng/repository/UserRoleAssignmentRepository.java @@ -0,0 +1,22 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.repository; + +import org.hostsharing.hsadminng.domain.UserRoleAssignment; + +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * Spring Data repository for the UserRoleAssignment entity. + */ +@SuppressWarnings("unused") +@Repository +public interface UserRoleAssignmentRepository + extends JpaRepository, JpaSpecificationExecutor { + + @Query("select user_role_assignment from UserRoleAssignment user_role_assignment where user_role_assignment.user.login = ?#{principal.username}") + List findByUserIsCurrentUser(); + +} diff --git a/src/main/java/org/hostsharing/hsadminng/service/UserRoleAssignmentQueryService.java b/src/main/java/org/hostsharing/hsadminng/service/UserRoleAssignmentQueryService.java new file mode 100644 index 00000000..bdf4ec4a --- /dev/null +++ b/src/main/java/org/hostsharing/hsadminng/service/UserRoleAssignmentQueryService.java @@ -0,0 +1,115 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.service; + +import org.hostsharing.hsadminng.domain.*; +import org.hostsharing.hsadminng.domain.UserRoleAssignment; +import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; +import org.hostsharing.hsadminng.service.dto.UserRoleAssignmentCriteria; + +import io.github.jhipster.service.QueryService; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import javax.persistence.criteria.JoinType; + +/** + * Service for executing complex queries for UserRoleAssignment entities in the database. + * The main input is a {@link UserRoleAssignmentCriteria} which gets converted to {@link Specification}, + * in a way that all the filters must apply. + * It returns a {@link List} of {@link UserRoleAssignment} or a {@link Page} of {@link UserRoleAssignment} which fulfills the + * criteria. + */ +@Service +@Transactional(readOnly = true) +public class UserRoleAssignmentQueryService extends QueryService { + + private final Logger log = LoggerFactory.getLogger(UserRoleAssignmentQueryService.class); + + private final UserRoleAssignmentRepository userRoleAssignmentRepository; + + public UserRoleAssignmentQueryService(UserRoleAssignmentRepository userRoleAssignmentRepository) { + this.userRoleAssignmentRepository = userRoleAssignmentRepository; + } + + /** + * Return a {@link List} of {@link UserRoleAssignment} which matches the criteria from the database + * + * @param criteria The object which holds all the filters, which the entities should match. + * @return the matching entities. + */ + @Transactional(readOnly = true) + public List findByCriteria(UserRoleAssignmentCriteria criteria) { + log.debug("find by criteria : {}", criteria); + final Specification specification = createSpecification(criteria); + return userRoleAssignmentRepository.findAll(specification); + } + + /** + * Return a {@link Page} of {@link UserRoleAssignment} which matches the criteria from the database + * + * @param criteria The object which holds all the filters, which the entities should match. + * @param page The page, which should be returned. + * @return the matching entities. + */ + @Transactional(readOnly = true) + public Page findByCriteria(UserRoleAssignmentCriteria criteria, Pageable page) { + log.debug("find by criteria : {}, page: {}", criteria, page); + final Specification specification = createSpecification(criteria); + return userRoleAssignmentRepository.findAll(specification, page); + } + + /** + * Return the number of matching entities in the database + * + * @param criteria The object which holds all the filters, which the entities should match. + * @return the number of matching entities. + */ + @Transactional(readOnly = true) + public long countByCriteria(UserRoleAssignmentCriteria criteria) { + log.debug("count by criteria : {}", criteria); + final Specification specification = createSpecification(criteria); + return userRoleAssignmentRepository.count(specification); + } + + /** + * Function to convert UserRoleAssignmentCriteria to a {@link Specification} + */ + private Specification createSpecification(UserRoleAssignmentCriteria criteria) { + Specification specification = Specification.where(null); + if (criteria != null) { + if (criteria.getId() != null) { + specification = specification.and(buildSpecification(criteria.getId(), UserRoleAssignment_.id)); + } + if (criteria.getEntityTypeId() != null) { + specification = specification + .and(buildStringSpecification(criteria.getEntityTypeId(), UserRoleAssignment_.entityTypeId)); + } + if (criteria.getEntityObjectId() != null) { + specification = specification + .and(buildRangeSpecification(criteria.getEntityObjectId(), UserRoleAssignment_.entityObjectId)); + } + if (criteria.getUserId() != null) { + specification = specification.and(buildRangeSpecification(criteria.getUserId(), UserRoleAssignment_.userId)); + } + if (criteria.getAssignedRole() != null) { + specification = specification + .and(buildSpecification(criteria.getAssignedRole(), UserRoleAssignment_.assignedRole)); + } + if (criteria.getUserId() != null) { + specification = specification.and( + buildSpecification( + criteria.getUserId(), + root -> root.join(UserRoleAssignment_.user, JoinType.LEFT).get(User_.id))); + } + } + return specification; + } +} diff --git a/src/main/java/org/hostsharing/hsadminng/service/UserRoleAssignmentService.java b/src/main/java/org/hostsharing/hsadminng/service/UserRoleAssignmentService.java new file mode 100644 index 00000000..cb43d61b --- /dev/null +++ b/src/main/java/org/hostsharing/hsadminng/service/UserRoleAssignmentService.java @@ -0,0 +1,75 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.service; + +import org.hostsharing.hsadminng.domain.UserRoleAssignment; +import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +/** + * Service Implementation for managing UserRoleAssignment. + */ +@Service +@Transactional +public class UserRoleAssignmentService { + + private final Logger log = LoggerFactory.getLogger(UserRoleAssignmentService.class); + + private final UserRoleAssignmentRepository userRoleAssignmentRepository; + + public UserRoleAssignmentService(UserRoleAssignmentRepository userRoleAssignmentRepository) { + this.userRoleAssignmentRepository = userRoleAssignmentRepository; + } + + /** + * Save a userRoleAssignment. + * + * @param userRoleAssignment the entity to save + * @return the persisted entity + */ + public UserRoleAssignment save(UserRoleAssignment userRoleAssignment) { + log.debug("Request to save UserRoleAssignment : {}", userRoleAssignment); + return userRoleAssignmentRepository.save(userRoleAssignment); + } + + /** + * Get all the userRoleAssignments. + * + * @param pageable the pagination information + * @return the list of entities + */ + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + log.debug("Request to get all UserRoleAssignments"); + return userRoleAssignmentRepository.findAll(pageable); + } + + /** + * Get one userRoleAssignment by id. + * + * @param id the id of the entity + * @return the entity + */ + @Transactional(readOnly = true) + public Optional findOne(Long id) { + log.debug("Request to get UserRoleAssignment : {}", id); + return userRoleAssignmentRepository.findById(id); + } + + /** + * Delete the userRoleAssignment by id. + * + * @param id the id of the entity + */ + public void delete(Long id) { + log.debug("Request to delete UserRoleAssignment : {}", id); + userRoleAssignmentRepository.deleteById(id); + } +} diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/UserRoleAssignmentCriteria.java b/src/main/java/org/hostsharing/hsadminng/service/dto/UserRoleAssignmentCriteria.java new file mode 100644 index 00000000..f42af7b9 --- /dev/null +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/UserRoleAssignmentCriteria.java @@ -0,0 +1,131 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.service.dto; + +import org.hostsharing.hsadminng.domain.enumeration.UserRole; + +import io.github.jhipster.service.filter.Filter; +import io.github.jhipster.service.filter.LongFilter; +import io.github.jhipster.service.filter.StringFilter; + +import java.io.Serializable; +import java.util.Objects; + +/** + * Criteria class for the UserRoleAssignment entity. This class is used in UserRoleAssignmentResource to + * receive all the possible filtering options from the Http GET request parameters. + * For example the following could be a valid requests: + * /user-role-assignments?id.greaterThan=5&attr1.contains=something&attr2.specified=false + * As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use + * fix type specific filters. + */ +public class UserRoleAssignmentCriteria implements Serializable { + + /** + * Class for filtering UserRole + */ + public static class UserRoleFilter extends Filter { + } + + private static final long serialVersionUID = 1L; + + private LongFilter id; + + private StringFilter entityTypeId; + + private LongFilter entityObjectId; + + private LongFilter userId; + + private UserRoleFilter assignedRole; + + private LongFilter userId; + + public LongFilter getId() { + return id; + } + + public void setId(LongFilter id) { + this.id = id; + } + + public StringFilter getEntityTypeId() { + return entityTypeId; + } + + public void setEntityTypeId(StringFilter entityTypeId) { + this.entityTypeId = entityTypeId; + } + + public LongFilter getEntityObjectId() { + return entityObjectId; + } + + public void setEntityObjectId(LongFilter entityObjectId) { + this.entityObjectId = entityObjectId; + } + + public LongFilter getUserId() { + return userId; + } + + public void setUserId(LongFilter userId) { + this.userId = userId; + } + + public UserRoleFilter getAssignedRole() { + return assignedRole; + } + + public void setAssignedRole(UserRoleFilter assignedRole) { + this.assignedRole = assignedRole; + } + + public LongFilter getUserId() { + return userId; + } + + public void setUserId(LongFilter userId) { + this.userId = userId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final UserRoleAssignmentCriteria that = (UserRoleAssignmentCriteria) o; + return Objects.equals(id, that.id) && + Objects.equals(entityTypeId, that.entityTypeId) && + Objects.equals(entityObjectId, that.entityObjectId) && + Objects.equals(userId, that.userId) && + Objects.equals(assignedRole, that.assignedRole) && + Objects.equals(userId, that.userId); + } + + @Override + public int hashCode() { + return Objects.hash( + id, + entityTypeId, + entityObjectId, + userId, + assignedRole, + userId); + } + + @Override + public String toString() { + return "UserRoleAssignmentCriteria{" + + (id != null ? "id=" + id + ", " : "") + + (entityTypeId != null ? "entityTypeId=" + entityTypeId + ", " : "") + + (entityObjectId != null ? "entityObjectId=" + entityObjectId + ", " : "") + + (userId != null ? "userId=" + userId + ", " : "") + + (assignedRole != null ? "assignedRole=" + assignedRole + ", " : "") + + (userId != null ? "userId=" + userId + ", " : "") + + "}"; + } + +} diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/UserRoleAssignmentResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/UserRoleAssignmentResource.java new file mode 100644 index 00000000..8417f65c --- /dev/null +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/UserRoleAssignmentResource.java @@ -0,0 +1,148 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.web.rest; + +import org.hostsharing.hsadminng.domain.UserRoleAssignment; +import org.hostsharing.hsadminng.service.UserRoleAssignmentQueryService; +import org.hostsharing.hsadminng.service.UserRoleAssignmentService; +import org.hostsharing.hsadminng.service.dto.UserRoleAssignmentCriteria; +import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; +import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; +import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; + +import io.github.jhipster.web.util.ResponseUtil; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Optional; + +import javax.validation.Valid; + +/** + * REST controller for managing UserRoleAssignment. + */ +@RestController +@RequestMapping("/api") +public class UserRoleAssignmentResource { + + private final Logger log = LoggerFactory.getLogger(UserRoleAssignmentResource.class); + + private static final String ENTITY_NAME = "userRoleAssignment"; + + private final UserRoleAssignmentService userRoleAssignmentService; + + private final UserRoleAssignmentQueryService userRoleAssignmentQueryService; + + public UserRoleAssignmentResource( + UserRoleAssignmentService userRoleAssignmentService, + UserRoleAssignmentQueryService userRoleAssignmentQueryService) { + this.userRoleAssignmentService = userRoleAssignmentService; + this.userRoleAssignmentQueryService = userRoleAssignmentQueryService; + } + + /** + * POST /user-role-assignments : Create a new userRoleAssignment. + * + * @param userRoleAssignment the userRoleAssignment to create + * @return the ResponseEntity with status 201 (Created) and with body the new userRoleAssignment, or with status 400 (Bad + * Request) if the userRoleAssignment has already an ID + * @throws URISyntaxException if the Location URI syntax is incorrect + */ + @PostMapping("/user-role-assignments") + public ResponseEntity createUserRoleAssignment( + @Valid @RequestBody UserRoleAssignment userRoleAssignment) throws URISyntaxException { + log.debug("REST request to save UserRoleAssignment : {}", userRoleAssignment); + if (userRoleAssignment.getId() != null) { + throw new BadRequestAlertException("A new userRoleAssignment cannot already have an ID", ENTITY_NAME, "idexists"); + } + UserRoleAssignment result = userRoleAssignmentService.save(userRoleAssignment); + return ResponseEntity.created(new URI("/api/user-role-assignments/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * PUT /user-role-assignments : Updates an existing userRoleAssignment. + * + * @param userRoleAssignment the userRoleAssignment to update + * @return the ResponseEntity with status 200 (OK) and with body the updated userRoleAssignment, + * or with status 400 (Bad Request) if the userRoleAssignment is not valid, + * or with status 500 (Internal Server Error) if the userRoleAssignment couldn't be updated + * @throws URISyntaxException if the Location URI syntax is incorrect + */ + @PutMapping("/user-role-assignments") + public ResponseEntity updateUserRoleAssignment( + @Valid @RequestBody UserRoleAssignment userRoleAssignment) throws URISyntaxException { + log.debug("REST request to update UserRoleAssignment : {}", userRoleAssignment); + if (userRoleAssignment.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + UserRoleAssignment result = userRoleAssignmentService.save(userRoleAssignment); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, userRoleAssignment.getId().toString())) + .body(result); + } + + /** + * GET /user-role-assignments : get all the userRoleAssignments. + * + * @param pageable the pagination information + * @param criteria the criterias which the requested entities should match + * @return the ResponseEntity with status 200 (OK) and the list of userRoleAssignments in body + */ + @GetMapping("/user-role-assignments") + public ResponseEntity> getAllUserRoleAssignments( + UserRoleAssignmentCriteria criteria, + Pageable pageable) { + log.debug("REST request to get UserRoleAssignments by criteria: {}", criteria); + Page page = userRoleAssignmentQueryService.findByCriteria(criteria, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/user-role-assignments"); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * GET /user-role-assignments/count : count all the userRoleAssignments. + * + * @param criteria the criterias which the requested entities should match + * @return the ResponseEntity with status 200 (OK) and the count in body + */ + @GetMapping("/user-role-assignments/count") + public ResponseEntity countUserRoleAssignments(UserRoleAssignmentCriteria criteria) { + log.debug("REST request to count UserRoleAssignments by criteria: {}", criteria); + return ResponseEntity.ok().body(userRoleAssignmentQueryService.countByCriteria(criteria)); + } + + /** + * GET /user-role-assignments/:id : get the "id" userRoleAssignment. + * + * @param id the id of the userRoleAssignment to retrieve + * @return the ResponseEntity with status 200 (OK) and with body the userRoleAssignment, or with status 404 (Not Found) + */ + @GetMapping("/user-role-assignments/{id}") + public ResponseEntity getUserRoleAssignment(@PathVariable Long id) { + log.debug("REST request to get UserRoleAssignment : {}", id); + Optional userRoleAssignment = userRoleAssignmentService.findOne(id); + return ResponseUtil.wrapOrNotFound(userRoleAssignment); + } + + /** + * DELETE /user-role-assignments/:id : delete the "id" userRoleAssignment. + * + * @param id the id of the userRoleAssignment to delete + * @return the ResponseEntity with status 200 (OK) + */ + @DeleteMapping("/user-role-assignments/{id}") + public ResponseEntity deleteUserRoleAssignment(@PathVariable Long id) { + log.debug("REST request to delete UserRoleAssignment : {}", id); + userRoleAssignmentService.delete(id); + return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); + } +} diff --git a/src/main/jdl/accessrights.jdl b/src/main/jdl/accessrights.jdl new file mode 100644 index 00000000..cabbb540 --- /dev/null +++ b/src/main/jdl/accessrights.jdl @@ -0,0 +1,24 @@ +filter all +paginate all with infinite-scroll + +enum UserRole { + HOSTMASTER, + ADMIN, + SUPPORTER, + CONTRACTUAL_CONTACT, + FINANCIAL_CONTACT, + TECHNICAL_CONTACT, + CUSTOMER_USER +} + +entity UserRoleAssignment { + entityTypeId String, + entityObjectId Long, + userId Long required, + assignedRole UserRole required +} + + +relationship ManyToOne { + UserRoleAssignment{user(login)} to User{required}, +} diff --git a/src/main/resources/config/liquibase/changelog/20190430150324_added_entity_Customer.xml b/src/main/resources/config/liquibase/changelog/20190430152136_added_entity_Customer.xml similarity index 98% rename from src/main/resources/config/liquibase/changelog/20190430150324_added_entity_Customer.xml rename to src/main/resources/config/liquibase/changelog/20190430152136_added_entity_Customer.xml index 59940c72..e12bbf7e 100644 --- a/src/main/resources/config/liquibase/changelog/20190430150324_added_entity_Customer.xml +++ b/src/main/resources/config/liquibase/changelog/20190430152136_added_entity_Customer.xml @@ -14,7 +14,7 @@ - + diff --git a/src/main/resources/config/liquibase/changelog/20190430150325_added_entity_Membership.xml b/src/main/resources/config/liquibase/changelog/20190430152137_added_entity_Membership.xml similarity index 97% rename from src/main/resources/config/liquibase/changelog/20190430150325_added_entity_Membership.xml rename to src/main/resources/config/liquibase/changelog/20190430152137_added_entity_Membership.xml index 5c2f7916..3230c5d8 100644 --- a/src/main/resources/config/liquibase/changelog/20190430150325_added_entity_Membership.xml +++ b/src/main/resources/config/liquibase/changelog/20190430152137_added_entity_Membership.xml @@ -14,7 +14,7 @@ - + diff --git a/src/main/resources/config/liquibase/changelog/20190430150325_added_entity_constraints_Membership.xml b/src/main/resources/config/liquibase/changelog/20190430152137_added_entity_constraints_Membership.xml similarity index 93% rename from src/main/resources/config/liquibase/changelog/20190430150325_added_entity_constraints_Membership.xml rename to src/main/resources/config/liquibase/changelog/20190430152137_added_entity_constraints_Membership.xml index b641312b..b298dc4f 100644 --- a/src/main/resources/config/liquibase/changelog/20190430150325_added_entity_constraints_Membership.xml +++ b/src/main/resources/config/liquibase/changelog/20190430152137_added_entity_constraints_Membership.xml @@ -6,7 +6,7 @@ - + - + diff --git a/src/main/resources/config/liquibase/changelog/20190430150326_added_entity_constraints_Share.xml b/src/main/resources/config/liquibase/changelog/20190430152138_added_entity_constraints_Share.xml similarity index 92% rename from src/main/resources/config/liquibase/changelog/20190430150326_added_entity_constraints_Share.xml rename to src/main/resources/config/liquibase/changelog/20190430152138_added_entity_constraints_Share.xml index 06766919..625dc8b7 100644 --- a/src/main/resources/config/liquibase/changelog/20190430150326_added_entity_constraints_Share.xml +++ b/src/main/resources/config/liquibase/changelog/20190430152138_added_entity_constraints_Share.xml @@ -6,7 +6,7 @@ - + - + diff --git a/src/main/resources/config/liquibase/changelog/20190430150327_added_entity_constraints_Asset.xml b/src/main/resources/config/liquibase/changelog/20190430152139_added_entity_constraints_Asset.xml similarity index 92% rename from src/main/resources/config/liquibase/changelog/20190430150327_added_entity_constraints_Asset.xml rename to src/main/resources/config/liquibase/changelog/20190430152139_added_entity_constraints_Asset.xml index b91dfb17..79006896 100644 --- a/src/main/resources/config/liquibase/changelog/20190430150327_added_entity_constraints_Asset.xml +++ b/src/main/resources/config/liquibase/changelog/20190430152139_added_entity_constraints_Asset.xml @@ -6,7 +6,7 @@ - + - + diff --git a/src/main/resources/config/liquibase/changelog/20190430150328_added_entity_constraints_SepaMandate.xml b/src/main/resources/config/liquibase/changelog/20190430152140_added_entity_constraints_SepaMandate.xml similarity index 93% rename from src/main/resources/config/liquibase/changelog/20190430150328_added_entity_constraints_SepaMandate.xml rename to src/main/resources/config/liquibase/changelog/20190430152140_added_entity_constraints_SepaMandate.xml index a19a8626..958ab70e 100644 --- a/src/main/resources/config/liquibase/changelog/20190430150328_added_entity_constraints_SepaMandate.xml +++ b/src/main/resources/config/liquibase/changelog/20190430152140_added_entity_constraints_SepaMandate.xml @@ -6,7 +6,7 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190430152204_added_entity_constraints_UserRoleAssignment.xml b/src/main/resources/config/liquibase/changelog/20190430152204_added_entity_constraints_UserRoleAssignment.xml new file mode 100644 index 00000000..6fbd98d5 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190430152204_added_entity_constraints_UserRoleAssignment.xml @@ -0,0 +1,18 @@ + + + + + + + + + diff --git a/src/main/resources/config/liquibase/master.xml b/src/main/resources/config/liquibase/master.xml index e2a5d338..75469c85 100644 --- a/src/main/resources/config/liquibase/master.xml +++ b/src/main/resources/config/liquibase/master.xml @@ -5,16 +5,18 @@ xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd"> - - - - - + + + + + + - - - - + + + + + diff --git a/src/main/webapp/app/entities/entity.module.ts b/src/main/webapp/app/entities/entity.module.ts index 00686b57..bdcacf35 100644 --- a/src/main/webapp/app/entities/entity.module.ts +++ b/src/main/webapp/app/entities/entity.module.ts @@ -23,6 +23,10 @@ import { RouterModule } from '@angular/router'; { path: 'sepa-mandate', loadChildren: './sepa-mandate/sepa-mandate.module#HsadminNgSepaMandateModule' + }, + { + path: 'user-role-assignment', + loadChildren: './user-role-assignment/user-role-assignment.module#HsadminNgUserRoleAssignmentModule' } /* jhipster-needle-add-entity-route - JHipster will add entity modules routes here */ ]) diff --git a/src/main/webapp/app/entities/user-role-assignment/index.ts b/src/main/webapp/app/entities/user-role-assignment/index.ts new file mode 100644 index 00000000..c09ebecf --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/index.ts @@ -0,0 +1,6 @@ +export * from './user-role-assignment.service'; +export * from './user-role-assignment-update.component'; +export * from './user-role-assignment-delete-dialog.component'; +export * from './user-role-assignment-detail.component'; +export * from './user-role-assignment.component'; +export * from './user-role-assignment.route'; diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.html b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.html new file mode 100644 index 00000000..abf0a02e --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.ts b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.ts new file mode 100644 index 00000000..886df8fc --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.ts @@ -0,0 +1,72 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; + +import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; +import { JhiEventManager } from 'ng-jhipster'; + +import { IUserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; +import { UserRoleAssignmentService } from './user-role-assignment.service'; + +@Component({ + selector: 'jhi-user-role-assignment-delete-dialog', + templateUrl: './user-role-assignment-delete-dialog.component.html' +}) +export class UserRoleAssignmentDeleteDialogComponent { + userRoleAssignment: IUserRoleAssignment; + + constructor( + protected userRoleAssignmentService: UserRoleAssignmentService, + public activeModal: NgbActiveModal, + protected eventManager: JhiEventManager + ) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.userRoleAssignmentService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'userRoleAssignmentListModification', + content: 'Deleted an userRoleAssignment' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-user-role-assignment-delete-popup', + template: '' +}) +export class UserRoleAssignmentDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ userRoleAssignment }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(UserRoleAssignmentDeleteDialogComponent as Component, { + size: 'lg', + backdrop: 'static' + }); + this.ngbModalRef.componentInstance.userRoleAssignment = userRoleAssignment; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/user-role-assignment', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/user-role-assignment', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-detail.component.html b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-detail.component.html new file mode 100644 index 00000000..151047a0 --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-detail.component.html @@ -0,0 +1,43 @@ +
+
+
+

User Role Assignment {{userRoleAssignment.id}}

+
+ +
+
Entity Type Id
+
+ {{userRoleAssignment.entityTypeId}} +
+
Entity Object Id
+
+ {{userRoleAssignment.entityObjectId}} +
+
User Id
+
+ {{userRoleAssignment.userId}} +
+
Assigned Role
+
+ {{userRoleAssignment.assignedRole}} +
+
User
+
+ {{userRoleAssignment.user?.login}} +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-detail.component.ts b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-detail.component.ts new file mode 100644 index 00000000..7882a634 --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { IUserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; + +@Component({ + selector: 'jhi-user-role-assignment-detail', + templateUrl: './user-role-assignment-detail.component.html' +}) +export class UserRoleAssignmentDetailComponent implements OnInit { + userRoleAssignment: IUserRoleAssignment; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ userRoleAssignment }) => { + this.userRoleAssignment = userRoleAssignment; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-update.component.html b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-update.component.html new file mode 100644 index 00000000..1162073e --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-update.component.html @@ -0,0 +1,74 @@ +
+
+
+

Create or edit a User Role Assignment

+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + This field is required. + + + This field should be a number. + +
+
+
+ + +
+ + This field is required. + +
+
+ +
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-update.component.ts b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-update.component.ts new file mode 100644 index 00000000..acd6dd35 --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment-update.component.ts @@ -0,0 +1,75 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiAlertService } from 'ng-jhipster'; +import { IUserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; +import { UserRoleAssignmentService } from './user-role-assignment.service'; +import { IUser, UserService } from 'app/core'; + +@Component({ + selector: 'jhi-user-role-assignment-update', + templateUrl: './user-role-assignment-update.component.html' +}) +export class UserRoleAssignmentUpdateComponent implements OnInit { + userRoleAssignment: IUserRoleAssignment; + isSaving: boolean; + + users: IUser[]; + + constructor( + protected jhiAlertService: JhiAlertService, + protected userRoleAssignmentService: UserRoleAssignmentService, + protected userService: UserService, + protected activatedRoute: ActivatedRoute + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ userRoleAssignment }) => { + this.userRoleAssignment = userRoleAssignment; + }); + this.userService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: IUser[]) => (this.users = res), (res: HttpErrorResponse) => this.onError(res.message)); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + if (this.userRoleAssignment.id !== undefined) { + this.subscribeToSaveResponse(this.userRoleAssignmentService.update(this.userRoleAssignment)); + } else { + this.subscribeToSaveResponse(this.userRoleAssignmentService.create(this.userRoleAssignment)); + } + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackUserById(index: number, item: IUser) { + return item.id; + } +} diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.component.html b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.component.html new file mode 100644 index 00000000..0dc00584 --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.component.html @@ -0,0 +1,64 @@ +
+

+ User Role Assignments + +

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + +
ID Entity Type Id Entity Object Id User Id Assigned Role User
{{userRoleAssignment.id}}{{userRoleAssignment.entityTypeId}}{{userRoleAssignment.entityObjectId}}{{userRoleAssignment.userId}}{{userRoleAssignment.assignedRole}} + {{userRoleAssignment.user?.login}} + +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.component.ts b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.component.ts new file mode 100644 index 00000000..822109d8 --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.component.ts @@ -0,0 +1,108 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiParseLinks, JhiAlertService } from 'ng-jhipster'; + +import { IUserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; +import { AccountService } from 'app/core'; + +import { ITEMS_PER_PAGE } from 'app/shared'; +import { UserRoleAssignmentService } from './user-role-assignment.service'; + +@Component({ + selector: 'jhi-user-role-assignment', + templateUrl: './user-role-assignment.component.html' +}) +export class UserRoleAssignmentComponent implements OnInit, OnDestroy { + userRoleAssignments: IUserRoleAssignment[]; + currentAccount: any; + eventSubscriber: Subscription; + itemsPerPage: number; + links: any; + page: any; + predicate: any; + reverse: any; + totalItems: number; + + constructor( + protected userRoleAssignmentService: UserRoleAssignmentService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected parseLinks: JhiParseLinks, + protected accountService: AccountService + ) { + this.userRoleAssignments = []; + this.itemsPerPage = ITEMS_PER_PAGE; + this.page = 0; + this.links = { + last: 0 + }; + this.predicate = 'id'; + this.reverse = true; + } + + loadAll() { + this.userRoleAssignmentService + .query({ + page: this.page, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe( + (res: HttpResponse) => this.paginateUserRoleAssignments(res.body, res.headers), + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + reset() { + this.page = 0; + this.userRoleAssignments = []; + this.loadAll(); + } + + loadPage(page) { + this.page = page; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInUserRoleAssignments(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IUserRoleAssignment) { + return item.id; + } + + registerChangeInUserRoleAssignments() { + this.eventSubscriber = this.eventManager.subscribe('userRoleAssignmentListModification', response => this.reset()); + } + + sort() { + const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')]; + if (this.predicate !== 'id') { + result.push('id'); + } + return result; + } + + protected paginateUserRoleAssignments(data: IUserRoleAssignment[], headers: HttpHeaders) { + this.links = this.parseLinks.parse(headers.get('link')); + this.totalItems = parseInt(headers.get('X-Total-Count'), 10); + for (let i = 0; i < data.length; i++) { + this.userRoleAssignments.push(data[i]); + } + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.module.ts b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.module.ts new file mode 100644 index 00000000..f90bd034 --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.module.ts @@ -0,0 +1,45 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; +import { JhiLanguageService } from 'ng-jhipster'; +import { JhiLanguageHelper } from 'app/core'; + +import { HsadminNgSharedModule } from 'app/shared'; +import { + UserRoleAssignmentComponent, + UserRoleAssignmentDetailComponent, + UserRoleAssignmentUpdateComponent, + UserRoleAssignmentDeletePopupComponent, + UserRoleAssignmentDeleteDialogComponent, + userRoleAssignmentRoute, + userRoleAssignmentPopupRoute +} from './'; + +const ENTITY_STATES = [...userRoleAssignmentRoute, ...userRoleAssignmentPopupRoute]; + +@NgModule({ + imports: [HsadminNgSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + UserRoleAssignmentComponent, + UserRoleAssignmentDetailComponent, + UserRoleAssignmentUpdateComponent, + UserRoleAssignmentDeleteDialogComponent, + UserRoleAssignmentDeletePopupComponent + ], + entryComponents: [ + UserRoleAssignmentComponent, + UserRoleAssignmentUpdateComponent, + UserRoleAssignmentDeleteDialogComponent, + UserRoleAssignmentDeletePopupComponent + ], + providers: [{ provide: JhiLanguageService, useClass: JhiLanguageService }], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class HsadminNgUserRoleAssignmentModule { + constructor(private languageService: JhiLanguageService, private languageHelper: JhiLanguageHelper) { + this.languageHelper.language.subscribe((languageKey: string) => { + if (languageKey !== undefined) { + this.languageService.changeLanguage(languageKey); + } + }); + } +} diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.route.ts b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.route.ts new file mode 100644 index 00000000..7271326a --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { UserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; +import { UserRoleAssignmentService } from './user-role-assignment.service'; +import { UserRoleAssignmentComponent } from './user-role-assignment.component'; +import { UserRoleAssignmentDetailComponent } from './user-role-assignment-detail.component'; +import { UserRoleAssignmentUpdateComponent } from './user-role-assignment-update.component'; +import { UserRoleAssignmentDeletePopupComponent } from './user-role-assignment-delete-dialog.component'; +import { IUserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; + +@Injectable({ providedIn: 'root' }) +export class UserRoleAssignmentResolve implements Resolve { + constructor(private service: UserRoleAssignmentService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((userRoleAssignment: HttpResponse) => userRoleAssignment.body) + ); + } + return of(new UserRoleAssignment()); + } +} + +export const userRoleAssignmentRoute: Routes = [ + { + path: '', + component: UserRoleAssignmentComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'hsadminNgApp.userRoleAssignment.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: UserRoleAssignmentDetailComponent, + resolve: { + userRoleAssignment: UserRoleAssignmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'hsadminNgApp.userRoleAssignment.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: UserRoleAssignmentUpdateComponent, + resolve: { + userRoleAssignment: UserRoleAssignmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'hsadminNgApp.userRoleAssignment.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: UserRoleAssignmentUpdateComponent, + resolve: { + userRoleAssignment: UserRoleAssignmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'hsadminNgApp.userRoleAssignment.home.title' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const userRoleAssignmentPopupRoute: Routes = [ + { + path: ':id/delete', + component: UserRoleAssignmentDeletePopupComponent, + resolve: { + userRoleAssignment: UserRoleAssignmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'hsadminNgApp.userRoleAssignment.home.title' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.service.ts b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.service.ts new file mode 100644 index 00000000..ea268039 --- /dev/null +++ b/src/main/webapp/app/entities/user-role-assignment/user-role-assignment.service.ts @@ -0,0 +1,38 @@ +import { Injectable } from '@angular/core'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; + +import { SERVER_API_URL } from 'app/app.constants'; +import { createRequestOption } from 'app/shared'; +import { IUserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class UserRoleAssignmentService { + public resourceUrl = SERVER_API_URL + 'api/user-role-assignments'; + + constructor(protected http: HttpClient) {} + + create(userRoleAssignment: IUserRoleAssignment): Observable { + return this.http.post(this.resourceUrl, userRoleAssignment, { observe: 'response' }); + } + + update(userRoleAssignment: IUserRoleAssignment): Observable { + return this.http.put(this.resourceUrl, userRoleAssignment, { observe: 'response' }); + } + + find(id: number): Observable { + return this.http.get(`${this.resourceUrl}/${id}`, { observe: 'response' }); + } + + query(req?: any): Observable { + const options = createRequestOption(req); + return this.http.get(this.resourceUrl, { params: options, observe: 'response' }); + } + + delete(id: number): Observable> { + return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); + } +} diff --git a/src/main/webapp/app/layouts/navbar/navbar.component.html b/src/main/webapp/app/layouts/navbar/navbar.component.html index 9ec42f90..cf34be25 100644 --- a/src/main/webapp/app/layouts/navbar/navbar.component.html +++ b/src/main/webapp/app/layouts/navbar/navbar.component.html @@ -57,6 +57,12 @@ Sepa Mandate +
  • + + + User Role Assignment + +
  • diff --git a/src/main/webapp/app/shared/model/user-role-assignment.model.ts b/src/main/webapp/app/shared/model/user-role-assignment.model.ts new file mode 100644 index 00000000..3f44f34f --- /dev/null +++ b/src/main/webapp/app/shared/model/user-role-assignment.model.ts @@ -0,0 +1,31 @@ +import { IUser } from 'app/core/user/user.model'; + +export const enum UserRole { + HOSTMASTER = 'HOSTMASTER', + ADMIN = 'ADMIN', + SUPPORTER = 'SUPPORTER', + CONTRACTUAL_CONTACT = 'CONTRACTUAL_CONTACT', + FINANCIAL_CONTACT = 'FINANCIAL_CONTACT', + TECHNICAL_CONTACT = 'TECHNICAL_CONTACT', + CUSTOMER_USER = 'CUSTOMER_USER' +} + +export interface IUserRoleAssignment { + id?: number; + entityTypeId?: string; + entityObjectId?: number; + userId?: number; + assignedRole?: UserRole; + user?: IUser; +} + +export class UserRoleAssignment implements IUserRoleAssignment { + constructor( + public id?: number, + public entityTypeId?: string, + public entityObjectId?: number, + public userId?: number, + public assignedRole?: UserRole, + public user?: IUser + ) {} +} diff --git a/src/main/webapp/i18n/de/global.json b/src/main/webapp/i18n/de/global.json index c7a71134..fabdfc34 100644 --- a/src/main/webapp/i18n/de/global.json +++ b/src/main/webapp/i18n/de/global.json @@ -12,6 +12,7 @@ "share": "Share", "asset": "Asset", "sepaMandate": "Sepa Mandate", + "userRoleAssignment": "User Role Assignment", "jhipster-needle-menu-add-entry": "JHipster will add additional entities here (do not translate!)" }, "account": { diff --git a/src/main/webapp/i18n/de/userRole.json b/src/main/webapp/i18n/de/userRole.json new file mode 100644 index 00000000..610dc2a4 --- /dev/null +++ b/src/main/webapp/i18n/de/userRole.json @@ -0,0 +1,14 @@ +{ + "hsadminNgApp": { + "UserRole": { + "null": "", + "HOSTMASTER": "HOSTMASTER", + "ADMIN": "ADMIN", + "SUPPORTER": "SUPPORTER", + "CONTRACTUAL_CONTACT": "CONTRACTUAL_CONTACT", + "FINANCIAL_CONTACT": "FINANCIAL_CONTACT", + "TECHNICAL_CONTACT": "TECHNICAL_CONTACT", + "CUSTOMER_USER": "CUSTOMER_USER" + } + } +} diff --git a/src/main/webapp/i18n/de/userRoleAssignment.json b/src/main/webapp/i18n/de/userRoleAssignment.json new file mode 100644 index 00000000..654e22a8 --- /dev/null +++ b/src/main/webapp/i18n/de/userRoleAssignment.json @@ -0,0 +1,25 @@ +{ + "hsadminNgApp": { + "userRoleAssignment": { + "home": { + "title": "User Role Assignments", + "createLabel": "User Role Assignment erstellen", + "createOrEditLabel": "User Role Assignment erstellen oder bearbeiten" + }, + "created": "User Role Assignment erstellt mit ID {{ param }}", + "updated": "User Role Assignment aktualisiert mit ID {{ param }}", + "deleted": "User Role Assignment gelöscht mit ID {{ param }}", + "delete": { + "question": "Soll User Role Assignment {{ id }} wirklich dauerhaft gelöscht werden?" + }, + "detail": { + "title": "User Role Assignment" + }, + "entityTypeId": "Entity Type Id", + "entityObjectId": "Entity Object Id", + "userId": "User Id", + "assignedRole": "Assigned Role", + "user": "User" + } + } +} diff --git a/src/main/webapp/i18n/en/global.json b/src/main/webapp/i18n/en/global.json index 53b8ae7c..72ca26ef 100644 --- a/src/main/webapp/i18n/en/global.json +++ b/src/main/webapp/i18n/en/global.json @@ -12,6 +12,7 @@ "share": "Share", "asset": "Asset", "sepaMandate": "Sepa Mandate", + "userRoleAssignment": "User Role Assignment", "jhipster-needle-menu-add-entry": "JHipster will add additional entities here (do not translate!)" }, "account": { diff --git a/src/main/webapp/i18n/en/userRole.json b/src/main/webapp/i18n/en/userRole.json new file mode 100644 index 00000000..610dc2a4 --- /dev/null +++ b/src/main/webapp/i18n/en/userRole.json @@ -0,0 +1,14 @@ +{ + "hsadminNgApp": { + "UserRole": { + "null": "", + "HOSTMASTER": "HOSTMASTER", + "ADMIN": "ADMIN", + "SUPPORTER": "SUPPORTER", + "CONTRACTUAL_CONTACT": "CONTRACTUAL_CONTACT", + "FINANCIAL_CONTACT": "FINANCIAL_CONTACT", + "TECHNICAL_CONTACT": "TECHNICAL_CONTACT", + "CUSTOMER_USER": "CUSTOMER_USER" + } + } +} diff --git a/src/main/webapp/i18n/en/userRoleAssignment.json b/src/main/webapp/i18n/en/userRoleAssignment.json new file mode 100644 index 00000000..b8b643ca --- /dev/null +++ b/src/main/webapp/i18n/en/userRoleAssignment.json @@ -0,0 +1,25 @@ +{ + "hsadminNgApp": { + "userRoleAssignment": { + "home": { + "title": "User Role Assignments", + "createLabel": "Create a new User Role Assignment", + "createOrEditLabel": "Create or edit a User Role Assignment" + }, + "created": "A new User Role Assignment is created with identifier {{ param }}", + "updated": "A User Role Assignment is updated with identifier {{ param }}", + "deleted": "A User Role Assignment is deleted with identifier {{ param }}", + "delete": { + "question": "Are you sure you want to delete User Role Assignment {{ id }}?" + }, + "detail": { + "title": "User Role Assignment" + }, + "entityTypeId": "Entity Type Id", + "entityObjectId": "Entity Object Id", + "userId": "User Id", + "assignedRole": "Assigned Role", + "user": "User" + } + } +} diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/UserRoleAssignmentResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/UserRoleAssignmentResourceIntTest.java new file mode 100644 index 00000000..a3c20ed7 --- /dev/null +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/UserRoleAssignmentResourceIntTest.java @@ -0,0 +1,594 @@ +// Licensed under Apache-2.0 +package org.hostsharing.hsadminng.web.rest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import org.hostsharing.hsadminng.HsadminNgApp; +import org.hostsharing.hsadminng.domain.User; +import org.hostsharing.hsadminng.domain.UserRoleAssignment; +import org.hostsharing.hsadminng.domain.enumeration.UserRole; +import org.hostsharing.hsadminng.repository.UserRoleAssignmentRepository; +import org.hostsharing.hsadminng.service.UserRoleAssignmentQueryService; +import org.hostsharing.hsadminng.service.UserRoleAssignmentService; +import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Validator; + +import java.util.List; + +import javax.persistence.EntityManager; + +/** + * Test class for the UserRoleAssignmentResource REST controller. + * + * @see UserRoleAssignmentResource + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = HsadminNgApp.class) +public class UserRoleAssignmentResourceIntTest { + + private static final String DEFAULT_ENTITY_TYPE_ID = "AAAAAAAAAA"; + private static final String UPDATED_ENTITY_TYPE_ID = "BBBBBBBBBB"; + + private static final Long DEFAULT_ENTITY_OBJECT_ID = 1L; + private static final Long UPDATED_ENTITY_OBJECT_ID = 2L; + + private static final Long DEFAULT_USER_ID = 1L; + private static final Long UPDATED_USER_ID = 2L; + + private static final UserRole DEFAULT_ASSIGNED_ROLE = UserRole.HOSTMASTER; + private static final UserRole UPDATED_ASSIGNED_ROLE = UserRole.ADMIN; + + @Autowired + private UserRoleAssignmentRepository userRoleAssignmentRepository; + + @Autowired + private UserRoleAssignmentService userRoleAssignmentService; + + @Autowired + private UserRoleAssignmentQueryService userRoleAssignmentQueryService; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restUserRoleAssignmentMockMvc; + + private UserRoleAssignment userRoleAssignment; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + final UserRoleAssignmentResource userRoleAssignmentResource = new UserRoleAssignmentResource( + userRoleAssignmentService, + userRoleAssignmentQueryService); + this.restUserRoleAssignmentMockMvc = MockMvcBuilders.standaloneSetup(userRoleAssignmentResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator) + .build(); + } + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static UserRoleAssignment createEntity(EntityManager em) { + UserRoleAssignment userRoleAssignment = new UserRoleAssignment() + .entityTypeId(DEFAULT_ENTITY_TYPE_ID) + .entityObjectId(DEFAULT_ENTITY_OBJECT_ID) + .userId(DEFAULT_USER_ID) + .assignedRole(DEFAULT_ASSIGNED_ROLE); + return userRoleAssignment; + } + + @Before + public void initTest() { + userRoleAssignment = createEntity(em); + } + + @Test + @Transactional + public void createUserRoleAssignment() throws Exception { + int databaseSizeBeforeCreate = userRoleAssignmentRepository.findAll().size(); + + // Create the UserRoleAssignment + restUserRoleAssignmentMockMvc.perform( + post("/api/user-role-assignments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userRoleAssignment))) + .andExpect(status().isCreated()); + + // Validate the UserRoleAssignment in the database + List userRoleAssignmentList = userRoleAssignmentRepository.findAll(); + assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeCreate + 1); + UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1); + assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(DEFAULT_ENTITY_TYPE_ID); + assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(DEFAULT_ENTITY_OBJECT_ID); + assertThat(testUserRoleAssignment.getUserId()).isEqualTo(DEFAULT_USER_ID); + assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(DEFAULT_ASSIGNED_ROLE); + } + + @Test + @Transactional + public void createUserRoleAssignmentWithExistingId() throws Exception { + int databaseSizeBeforeCreate = userRoleAssignmentRepository.findAll().size(); + + // Create the UserRoleAssignment with an existing ID + userRoleAssignment.setId(1L); + + // An entity with an existing ID cannot be created, so this API call must fail + restUserRoleAssignmentMockMvc.perform( + post("/api/user-role-assignments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userRoleAssignment))) + .andExpect(status().isBadRequest()); + + // Validate the UserRoleAssignment in the database + List userRoleAssignmentList = userRoleAssignmentRepository.findAll(); + assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeCreate); + } + + @Test + @Transactional + public void checkUserIdIsRequired() throws Exception { + int databaseSizeBeforeTest = userRoleAssignmentRepository.findAll().size(); + // set the field null + userRoleAssignment.setUserId(null); + + // Create the UserRoleAssignment, which fails. + + restUserRoleAssignmentMockMvc.perform( + post("/api/user-role-assignments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userRoleAssignment))) + .andExpect(status().isBadRequest()); + + List userRoleAssignmentList = userRoleAssignmentRepository.findAll(); + assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void checkAssignedRoleIsRequired() throws Exception { + int databaseSizeBeforeTest = userRoleAssignmentRepository.findAll().size(); + // set the field null + userRoleAssignment.setAssignedRole(null); + + // Create the UserRoleAssignment, which fails. + + restUserRoleAssignmentMockMvc.perform( + post("/api/user-role-assignments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userRoleAssignment))) + .andExpect(status().isBadRequest()); + + List userRoleAssignmentList = userRoleAssignmentRepository.findAll(); + assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void getAllUserRoleAssignments() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList + restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue()))) + .andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID.toString()))) + .andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue()))) + .andExpect(jsonPath("$.[*].userId").value(hasItem(DEFAULT_USER_ID.intValue()))) + .andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.toString()))); + } + + @Test + @Transactional + public void getUserRoleAssignment() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get the userRoleAssignment + restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/{id}", userRoleAssignment.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(userRoleAssignment.getId().intValue())) + .andExpect(jsonPath("$.entityTypeId").value(DEFAULT_ENTITY_TYPE_ID.toString())) + .andExpect(jsonPath("$.entityObjectId").value(DEFAULT_ENTITY_OBJECT_ID.intValue())) + .andExpect(jsonPath("$.userId").value(DEFAULT_USER_ID.intValue())) + .andExpect(jsonPath("$.assignedRole").value(DEFAULT_ASSIGNED_ROLE.toString())); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityTypeIdIsEqualToSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityTypeId equals to DEFAULT_ENTITY_TYPE_ID + defaultUserRoleAssignmentShouldBeFound("entityTypeId.equals=" + DEFAULT_ENTITY_TYPE_ID); + + // Get all the userRoleAssignmentList where entityTypeId equals to UPDATED_ENTITY_TYPE_ID + defaultUserRoleAssignmentShouldNotBeFound("entityTypeId.equals=" + UPDATED_ENTITY_TYPE_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityTypeIdIsInShouldWork() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityTypeId in DEFAULT_ENTITY_TYPE_ID or UPDATED_ENTITY_TYPE_ID + defaultUserRoleAssignmentShouldBeFound("entityTypeId.in=" + DEFAULT_ENTITY_TYPE_ID + "," + UPDATED_ENTITY_TYPE_ID); + + // Get all the userRoleAssignmentList where entityTypeId equals to UPDATED_ENTITY_TYPE_ID + defaultUserRoleAssignmentShouldNotBeFound("entityTypeId.in=" + UPDATED_ENTITY_TYPE_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityTypeIdIsNullOrNotNull() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityTypeId is not null + defaultUserRoleAssignmentShouldBeFound("entityTypeId.specified=true"); + + // Get all the userRoleAssignmentList where entityTypeId is null + defaultUserRoleAssignmentShouldNotBeFound("entityTypeId.specified=false"); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityObjectIdIsEqualToSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityObjectId equals to DEFAULT_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldBeFound("entityObjectId.equals=" + DEFAULT_ENTITY_OBJECT_ID); + + // Get all the userRoleAssignmentList where entityObjectId equals to UPDATED_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.equals=" + UPDATED_ENTITY_OBJECT_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityObjectIdIsInShouldWork() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityObjectId in DEFAULT_ENTITY_OBJECT_ID or UPDATED_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldBeFound( + "entityObjectId.in=" + DEFAULT_ENTITY_OBJECT_ID + "," + UPDATED_ENTITY_OBJECT_ID); + + // Get all the userRoleAssignmentList where entityObjectId equals to UPDATED_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.in=" + UPDATED_ENTITY_OBJECT_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityObjectIdIsNullOrNotNull() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityObjectId is not null + defaultUserRoleAssignmentShouldBeFound("entityObjectId.specified=true"); + + // Get all the userRoleAssignmentList where entityObjectId is null + defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.specified=false"); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityObjectIdIsGreaterThanOrEqualToSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityObjectId greater than or equals to DEFAULT_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldBeFound("entityObjectId.greaterOrEqualThan=" + DEFAULT_ENTITY_OBJECT_ID); + + // Get all the userRoleAssignmentList where entityObjectId greater than or equals to UPDATED_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.greaterOrEqualThan=" + UPDATED_ENTITY_OBJECT_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByEntityObjectIdIsLessThanSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where entityObjectId less than or equals to DEFAULT_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldNotBeFound("entityObjectId.lessThan=" + DEFAULT_ENTITY_OBJECT_ID); + + // Get all the userRoleAssignmentList where entityObjectId less than or equals to UPDATED_ENTITY_OBJECT_ID + defaultUserRoleAssignmentShouldBeFound("entityObjectId.lessThan=" + UPDATED_ENTITY_OBJECT_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByUserIdIsEqualToSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where userId equals to DEFAULT_USER_ID + defaultUserRoleAssignmentShouldBeFound("userId.equals=" + DEFAULT_USER_ID); + + // Get all the userRoleAssignmentList where userId equals to UPDATED_USER_ID + defaultUserRoleAssignmentShouldNotBeFound("userId.equals=" + UPDATED_USER_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByUserIdIsInShouldWork() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where userId in DEFAULT_USER_ID or UPDATED_USER_ID + defaultUserRoleAssignmentShouldBeFound("userId.in=" + DEFAULT_USER_ID + "," + UPDATED_USER_ID); + + // Get all the userRoleAssignmentList where userId equals to UPDATED_USER_ID + defaultUserRoleAssignmentShouldNotBeFound("userId.in=" + UPDATED_USER_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByUserIdIsNullOrNotNull() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where userId is not null + defaultUserRoleAssignmentShouldBeFound("userId.specified=true"); + + // Get all the userRoleAssignmentList where userId is null + defaultUserRoleAssignmentShouldNotBeFound("userId.specified=false"); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByUserIdIsGreaterThanOrEqualToSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where userId greater than or equals to DEFAULT_USER_ID + defaultUserRoleAssignmentShouldBeFound("userId.greaterOrEqualThan=" + DEFAULT_USER_ID); + + // Get all the userRoleAssignmentList where userId greater than or equals to UPDATED_USER_ID + defaultUserRoleAssignmentShouldNotBeFound("userId.greaterOrEqualThan=" + UPDATED_USER_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByUserIdIsLessThanSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where userId less than or equals to DEFAULT_USER_ID + defaultUserRoleAssignmentShouldNotBeFound("userId.lessThan=" + DEFAULT_USER_ID); + + // Get all the userRoleAssignmentList where userId less than or equals to UPDATED_USER_ID + defaultUserRoleAssignmentShouldBeFound("userId.lessThan=" + UPDATED_USER_ID); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByAssignedRoleIsEqualToSomething() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where assignedRole equals to DEFAULT_ASSIGNED_ROLE + defaultUserRoleAssignmentShouldBeFound("assignedRole.equals=" + DEFAULT_ASSIGNED_ROLE); + + // Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE + defaultUserRoleAssignmentShouldNotBeFound("assignedRole.equals=" + UPDATED_ASSIGNED_ROLE); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByAssignedRoleIsInShouldWork() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where assignedRole in DEFAULT_ASSIGNED_ROLE or UPDATED_ASSIGNED_ROLE + defaultUserRoleAssignmentShouldBeFound("assignedRole.in=" + DEFAULT_ASSIGNED_ROLE + "," + UPDATED_ASSIGNED_ROLE); + + // Get all the userRoleAssignmentList where assignedRole equals to UPDATED_ASSIGNED_ROLE + defaultUserRoleAssignmentShouldNotBeFound("assignedRole.in=" + UPDATED_ASSIGNED_ROLE); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByAssignedRoleIsNullOrNotNull() throws Exception { + // Initialize the database + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + + // Get all the userRoleAssignmentList where assignedRole is not null + defaultUserRoleAssignmentShouldBeFound("assignedRole.specified=true"); + + // Get all the userRoleAssignmentList where assignedRole is null + defaultUserRoleAssignmentShouldNotBeFound("assignedRole.specified=false"); + } + + @Test + @Transactional + public void getAllUserRoleAssignmentsByUserIsEqualToSomething() throws Exception { + // Initialize the database + User user = UserResourceIntTest.createEntity(em); + em.persist(user); + em.flush(); + userRoleAssignment.setUser(user); + userRoleAssignmentRepository.saveAndFlush(userRoleAssignment); + Long userId = user.getId(); + + // Get all the userRoleAssignmentList where user equals to userId + defaultUserRoleAssignmentShouldBeFound("userId.equals=" + userId); + + // Get all the userRoleAssignmentList where user equals to userId + 1 + defaultUserRoleAssignmentShouldNotBeFound("userId.equals=" + (userId + 1)); + } + + /** + * Executes the search, and checks that the default entity is returned + */ + private void defaultUserRoleAssignmentShouldBeFound(String filter) throws Exception { + restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments?sort=id,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(userRoleAssignment.getId().intValue()))) + .andExpect(jsonPath("$.[*].entityTypeId").value(hasItem(DEFAULT_ENTITY_TYPE_ID))) + .andExpect(jsonPath("$.[*].entityObjectId").value(hasItem(DEFAULT_ENTITY_OBJECT_ID.intValue()))) + .andExpect(jsonPath("$.[*].userId").value(hasItem(DEFAULT_USER_ID.intValue()))) + .andExpect(jsonPath("$.[*].assignedRole").value(hasItem(DEFAULT_ASSIGNED_ROLE.toString()))); + + // Check, that the count call also returns 1 + restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/count?sort=id,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("1")); + } + + /** + * Executes the search, and checks that the default entity is not returned + */ + private void defaultUserRoleAssignmentShouldNotBeFound(String filter) throws Exception { + restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments?sort=id,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").isEmpty()); + + // Check, that the count call also returns 0 + restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/count?sort=id,desc&" + filter)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("0")); + } + + @Test + @Transactional + public void getNonExistingUserRoleAssignment() throws Exception { + // Get the userRoleAssignment + restUserRoleAssignmentMockMvc.perform(get("/api/user-role-assignments/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateUserRoleAssignment() throws Exception { + // Initialize the database + userRoleAssignmentService.save(userRoleAssignment); + + int databaseSizeBeforeUpdate = userRoleAssignmentRepository.findAll().size(); + + // Update the userRoleAssignment + UserRoleAssignment updatedUserRoleAssignment = userRoleAssignmentRepository.findById(userRoleAssignment.getId()).get(); + // Disconnect from session so that the updates on updatedUserRoleAssignment are not directly saved in db + em.detach(updatedUserRoleAssignment); + updatedUserRoleAssignment + .entityTypeId(UPDATED_ENTITY_TYPE_ID) + .entityObjectId(UPDATED_ENTITY_OBJECT_ID) + .userId(UPDATED_USER_ID) + .assignedRole(UPDATED_ASSIGNED_ROLE); + + restUserRoleAssignmentMockMvc.perform( + put("/api/user-role-assignments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(updatedUserRoleAssignment))) + .andExpect(status().isOk()); + + // Validate the UserRoleAssignment in the database + List userRoleAssignmentList = userRoleAssignmentRepository.findAll(); + assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeUpdate); + UserRoleAssignment testUserRoleAssignment = userRoleAssignmentList.get(userRoleAssignmentList.size() - 1); + assertThat(testUserRoleAssignment.getEntityTypeId()).isEqualTo(UPDATED_ENTITY_TYPE_ID); + assertThat(testUserRoleAssignment.getEntityObjectId()).isEqualTo(UPDATED_ENTITY_OBJECT_ID); + assertThat(testUserRoleAssignment.getUserId()).isEqualTo(UPDATED_USER_ID); + assertThat(testUserRoleAssignment.getAssignedRole()).isEqualTo(UPDATED_ASSIGNED_ROLE); + } + + @Test + @Transactional + public void updateNonExistingUserRoleAssignment() throws Exception { + int databaseSizeBeforeUpdate = userRoleAssignmentRepository.findAll().size(); + + // Create the UserRoleAssignment + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restUserRoleAssignmentMockMvc.perform( + put("/api/user-role-assignments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userRoleAssignment))) + .andExpect(status().isBadRequest()); + + // Validate the UserRoleAssignment in the database + List userRoleAssignmentList = userRoleAssignmentRepository.findAll(); + assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeUpdate); + } + + @Test + @Transactional + public void deleteUserRoleAssignment() throws Exception { + // Initialize the database + userRoleAssignmentService.save(userRoleAssignment); + + int databaseSizeBeforeDelete = userRoleAssignmentRepository.findAll().size(); + + // Delete the userRoleAssignment + restUserRoleAssignmentMockMvc.perform( + delete("/api/user-role-assignments/{id}", userRoleAssignment.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()); + + // Validate the database is empty + List userRoleAssignmentList = userRoleAssignmentRepository.findAll(); + assertThat(userRoleAssignmentList).hasSize(databaseSizeBeforeDelete - 1); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(UserRoleAssignment.class); + UserRoleAssignment userRoleAssignment1 = new UserRoleAssignment(); + userRoleAssignment1.setId(1L); + UserRoleAssignment userRoleAssignment2 = new UserRoleAssignment(); + userRoleAssignment2.setId(userRoleAssignment1.getId()); + assertThat(userRoleAssignment1).isEqualTo(userRoleAssignment2); + userRoleAssignment2.setId(2L); + assertThat(userRoleAssignment1).isNotEqualTo(userRoleAssignment2); + userRoleAssignment1.setId(null); + assertThat(userRoleAssignment1).isNotEqualTo(userRoleAssignment2); + } +} diff --git a/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.spec.ts new file mode 100644 index 00000000..359e218c --- /dev/null +++ b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { HsadminNgTestModule } from '../../../test.module'; +import { UserRoleAssignmentDeleteDialogComponent } from 'app/entities/user-role-assignment/user-role-assignment-delete-dialog.component'; +import { UserRoleAssignmentService } from 'app/entities/user-role-assignment/user-role-assignment.service'; + +describe('Component Tests', () => { + describe('UserRoleAssignment Management Delete Component', () => { + let comp: UserRoleAssignmentDeleteDialogComponent; + let fixture: ComponentFixture; + let service: UserRoleAssignmentService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HsadminNgTestModule], + declarations: [UserRoleAssignmentDeleteDialogComponent] + }) + .overrideTemplate(UserRoleAssignmentDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(UserRoleAssignmentDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(UserRoleAssignmentService); + mockEventManager = fixture.debugElement.injector.get(JhiEventManager); + mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); + }); + + describe('confirmDelete', () => { + it('Should call delete service on confirmDelete', inject( + [], + fakeAsync(() => { + // GIVEN + spyOn(service, 'delete').and.returnValue(of({})); + + // WHEN + comp.confirmDelete(123); + tick(); + + // THEN + expect(service.delete).toHaveBeenCalledWith(123); + expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); + expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); + }) + )); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-detail.component.spec.ts b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-detail.component.spec.ts new file mode 100644 index 00000000..d2f85209 --- /dev/null +++ b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { HsadminNgTestModule } from '../../../test.module'; +import { UserRoleAssignmentDetailComponent } from 'app/entities/user-role-assignment/user-role-assignment-detail.component'; +import { UserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; + +describe('Component Tests', () => { + describe('UserRoleAssignment Management Detail Component', () => { + let comp: UserRoleAssignmentDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ userRoleAssignment: new UserRoleAssignment(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HsadminNgTestModule], + declarations: [UserRoleAssignmentDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(UserRoleAssignmentDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(UserRoleAssignmentDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.userRoleAssignment).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-update.component.spec.ts b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-update.component.spec.ts new file mode 100644 index 00000000..0ca89214 --- /dev/null +++ b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment-update.component.spec.ts @@ -0,0 +1,60 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { Observable, of } from 'rxjs'; + +import { HsadminNgTestModule } from '../../../test.module'; +import { UserRoleAssignmentUpdateComponent } from 'app/entities/user-role-assignment/user-role-assignment-update.component'; +import { UserRoleAssignmentService } from 'app/entities/user-role-assignment/user-role-assignment.service'; +import { UserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; + +describe('Component Tests', () => { + describe('UserRoleAssignment Management Update Component', () => { + let comp: UserRoleAssignmentUpdateComponent; + let fixture: ComponentFixture; + let service: UserRoleAssignmentService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HsadminNgTestModule], + declarations: [UserRoleAssignmentUpdateComponent] + }) + .overrideTemplate(UserRoleAssignmentUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(UserRoleAssignmentUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(UserRoleAssignmentService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new UserRoleAssignment(123); + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.userRoleAssignment = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new UserRoleAssignment(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.userRoleAssignment = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment.component.spec.ts b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment.component.spec.ts new file mode 100644 index 00000000..82e6923c --- /dev/null +++ b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment.component.spec.ts @@ -0,0 +1,128 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Data } from '@angular/router'; + +import { HsadminNgTestModule } from '../../../test.module'; +import { UserRoleAssignmentComponent } from 'app/entities/user-role-assignment/user-role-assignment.component'; +import { UserRoleAssignmentService } from 'app/entities/user-role-assignment/user-role-assignment.service'; +import { UserRoleAssignment } from 'app/shared/model/user-role-assignment.model'; + +describe('Component Tests', () => { + describe('UserRoleAssignment Management Component', () => { + let comp: UserRoleAssignmentComponent; + let fixture: ComponentFixture; + let service: UserRoleAssignmentService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HsadminNgTestModule], + declarations: [UserRoleAssignmentComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => + fn({ + pagingParams: { + predicate: 'id', + reverse: false, + page: 0 + } + }) + } + } + } + ] + }) + .overrideTemplate(UserRoleAssignmentComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(UserRoleAssignmentComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(UserRoleAssignmentService); + }); + + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new UserRoleAssignment(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.userRoleAssignments[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should load a page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new UserRoleAssignment(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.userRoleAssignments[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should re-initialize the page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new UserRoleAssignment(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + comp.reset(); + + // THEN + expect(comp.page).toEqual(0); + expect(service.query).toHaveBeenCalledTimes(2); + expect(comp.userRoleAssignments[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + it('should calculate the sort attribute for an id', () => { + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['id,asc']); + }); + + it('should calculate the sort attribute for a non-id attribute', () => { + // GIVEN + comp.predicate = 'name'; + + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['name,asc', 'id']); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment.service.spec.ts b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment.service.spec.ts new file mode 100644 index 00000000..9a138113 --- /dev/null +++ b/src/test/javascript/spec/app/entities/user-role-assignment/user-role-assignment.service.spec.ts @@ -0,0 +1,110 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { UserRoleAssignmentService } from 'app/entities/user-role-assignment/user-role-assignment.service'; +import { IUserRoleAssignment, UserRoleAssignment, UserRole } from 'app/shared/model/user-role-assignment.model'; + +describe('Service Tests', () => { + describe('UserRoleAssignment Service', () => { + let injector: TestBed; + let service: UserRoleAssignmentService; + let httpMock: HttpTestingController; + let elemDefault: IUserRoleAssignment; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + injector = getTestBed(); + service = injector.get(UserRoleAssignmentService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new UserRoleAssignment(0, 'AAAAAAA', 0, 0, UserRole.HOSTMASTER); + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe(resp => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a UserRoleAssignment', async () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new UserRoleAssignment(null)) + .pipe(take(1)) + .subscribe(resp => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a UserRoleAssignment', async () => { + const returnedFromService = Object.assign( + { + entityTypeId: 'BBBBBB', + entityObjectId: 1, + userId: 1, + assignedRole: 'BBBBBB' + }, + elemDefault + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe(resp => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of UserRoleAssignment', async () => { + const returnedFromService = Object.assign( + { + entityTypeId: 'BBBBBB', + entityObjectId: 1, + userId: 1, + assignedRole: 'BBBBBB' + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .query(expected) + .pipe( + take(1), + map(resp => resp.body) + ) + .subscribe(body => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + + it('should delete a UserRoleAssignment', async () => { + const rxPromise = service.delete(123).subscribe(resp => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); + }); +});