This commit is contained in:
2024-11-05 10:11:11 +01:00
parent 59bd5f6b78
commit c2bf40c1a4
80 changed files with 7291 additions and 1 deletions
+50
View File
@@ -0,0 +1,50 @@
{
"annotations": {
"changelogDate": "20241105091001"
},
"applications": "*",
"fields": [
{
"fieldName": "chargeDate",
"fieldType": "LocalDate",
"fieldValidateRules": ["required"]
},
{
"fieldName": "type",
"fieldType": "ChargeType",
"fieldValidateRules": ["required"],
"fieldValues": "CHARGE,PAYMENT"
},
{
"fieldName": "amount",
"fieldType": "BigDecimal",
"fieldValidateRules": ["required"]
}
],
"name": "Charge",
"relationships": [
{
"otherEntityField": "id",
"otherEntityName": "event",
"relationshipName": "event",
"relationshipSide": "left",
"relationshipType": "many-to-one"
},
{
"otherEntityField": "id",
"otherEntityName": "registration",
"relationshipName": "registration",
"relationshipSide": "left",
"relationshipType": "many-to-one"
},
{
"otherEntityField": "login",
"otherEntityName": "user",
"relationshipName": "user",
"relationshipSide": "left",
"relationshipType": "many-to-one",
"relationshipWithBuiltInEntity": true
}
],
"searchEngine": "no"
}
+42
View File
@@ -0,0 +1,42 @@
{
"annotations": {
"changelogDate": "20241105091002"
},
"applications": "*",
"fields": [
{
"fieldName": "name",
"fieldType": "String",
"fieldValidateRules": ["required"]
},
{
"fieldName": "date",
"fieldType": "LocalDate",
"fieldValidateRules": ["required"]
},
{
"fieldName": "playersLimit",
"fieldType": "Integer"
},
{
"fieldName": "cost",
"fieldType": "BigDecimal"
},
{
"fieldName": "comment",
"fieldType": "TextBlob"
}
],
"name": "Event",
"relationships": [
{
"otherEntityName": "registration",
"otherEntityRelationshipName": "event",
"relationshipName": "registrations",
"relationshipSide": "left",
"relationshipType": "one-to-many"
}
],
"searchEngine": "no",
"service": "serviceClass"
}
+46
View File
@@ -0,0 +1,46 @@
{
"annotations": {
"changelogDate": "20241105091003"
},
"applications": "*",
"fields": [
{
"fieldName": "dateTime",
"fieldType": "ZonedDateTime",
"fieldValidateRules": ["required"]
},
{
"fieldName": "active",
"fieldType": "Boolean",
"fieldValidateRules": ["required"]
},
{
"fieldName": "playerName",
"fieldType": "String"
},
{
"fieldName": "comment",
"fieldType": "TextBlob"
}
],
"name": "Registration",
"relationships": [
{
"otherEntityField": "login",
"otherEntityName": "user",
"relationshipName": "user",
"relationshipSide": "left",
"relationshipType": "many-to-one",
"relationshipWithBuiltInEntity": true
},
{
"otherEntityField": "name",
"otherEntityName": "event",
"otherEntityRelationshipName": "registrations",
"relationshipName": "event",
"relationshipSide": "right",
"relationshipType": "many-to-one"
}
],
"searchEngine": "no"
}
+2 -1
View File
@@ -15,9 +15,10 @@
"enableHibernateCache": null,
"enableSwaggerCodegen": false,
"enableTranslation": false,
"entities": [],
"entities": ["Charge", "Event", "Registration"],
"feignClient": null,
"jhipsterVersion": "8.7.2",
"lastLiquibaseTimestamp": 1730797803000,
"messageBroker": false,
"microfrontend": null,
"microfrontends": [],
+55
View File
@@ -0,0 +1,55 @@
entity Event {
name String required,
date LocalDate required,
playersLimit Integer,
cost BigDecimal,
comment TextBlob
}
entity Registration {
dateTime ZonedDateTime required,
active Boolean required,
playerName String,
comment TextBlob
}
entity Charge {
chargeDate LocalDate required,
type ChargeType required,
amount BigDecimal required,
// User will be linked through a relationship, no need for an attribute here
}
enum ChargeType {
CHARGE,
PAYMENT
}
// Change the relationship to reflect composition
relationship OneToMany {
Event{registrations} to Registration{event(name)}
}
// Declare User as a built-in entity
relationship ManyToOne {
Registration{user(login)} to User with builtInEntity
}
relationship ManyToOne {
Charge{event(id)} to Event
}
relationship ManyToOne {
Charge{registration(id)} to Registration
}
relationship ManyToOne {
Charge{user(login)} to User with builtInEntity
}
service Event with serviceClass
// No pagination as per your request
// Excluding DTOs as per your request
// noDto *
@@ -0,0 +1,173 @@
package com.sasiedzi.event.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.sasiedzi.event.domain.enumeration.ChargeType;
import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
* A Charge.
*/
@Entity
@Table(name = "charge")
@SuppressWarnings("common-java:DuplicatedBlocks")
public class Charge implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@NotNull
@Column(name = "charge_date", nullable = false)
private LocalDate chargeDate;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "type", nullable = false)
private ChargeType type;
@NotNull
@Column(name = "amount", precision = 21, scale = 2, nullable = false)
private BigDecimal amount;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = { "registrations" }, allowSetters = true)
private Event event;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = { "user", "event" }, allowSetters = true)
private Registration registration;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return this.id;
}
public Charge id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getChargeDate() {
return this.chargeDate;
}
public Charge chargeDate(LocalDate chargeDate) {
this.setChargeDate(chargeDate);
return this;
}
public void setChargeDate(LocalDate chargeDate) {
this.chargeDate = chargeDate;
}
public ChargeType getType() {
return this.type;
}
public Charge type(ChargeType type) {
this.setType(type);
return this;
}
public void setType(ChargeType type) {
this.type = type;
}
public BigDecimal getAmount() {
return this.amount;
}
public Charge amount(BigDecimal amount) {
this.setAmount(amount);
return this;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Event getEvent() {
return this.event;
}
public void setEvent(Event event) {
this.event = event;
}
public Charge event(Event event) {
this.setEvent(event);
return this;
}
public Registration getRegistration() {
return this.registration;
}
public void setRegistration(Registration registration) {
this.registration = registration;
}
public Charge registration(Registration registration) {
this.setRegistration(registration);
return this;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public Charge user(User user) {
this.setUser(user);
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Charge)) {
return false;
}
return getId() != null && getId().equals(((Charge) o).getId());
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "Charge{" +
"id=" + getId() +
", chargeDate='" + getChargeDate() + "'" +
", type='" + getType() + "'" +
", amount=" + getAmount() +
"}";
}
}
@@ -0,0 +1,192 @@
package com.sasiedzi.event.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
/**
* A Event.
*/
@Entity
@Table(name = "event")
@SuppressWarnings("common-java:DuplicatedBlocks")
public class Event implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@NotNull
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Column(name = "date", nullable = false)
private LocalDate date;
@Column(name = "players_limit")
private Integer playersLimit;
@Column(name = "cost", precision = 21, scale = 2)
private BigDecimal cost;
@Lob
@Column(name = "comment")
private String comment;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "event")
@JsonIgnoreProperties(value = { "user", "event" }, allowSetters = true)
private Set<Registration> registrations = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return this.id;
}
public Event id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public Event name(String name) {
this.setName(name);
return this;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDate() {
return this.date;
}
public Event date(LocalDate date) {
this.setDate(date);
return this;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Integer getPlayersLimit() {
return this.playersLimit;
}
public Event playersLimit(Integer playersLimit) {
this.setPlayersLimit(playersLimit);
return this;
}
public void setPlayersLimit(Integer playersLimit) {
this.playersLimit = playersLimit;
}
public BigDecimal getCost() {
return this.cost;
}
public Event cost(BigDecimal cost) {
this.setCost(cost);
return this;
}
public void setCost(BigDecimal cost) {
this.cost = cost;
}
public String getComment() {
return this.comment;
}
public Event comment(String comment) {
this.setComment(comment);
return this;
}
public void setComment(String comment) {
this.comment = comment;
}
public Set<Registration> getRegistrations() {
return this.registrations;
}
public void setRegistrations(Set<Registration> registrations) {
if (this.registrations != null) {
this.registrations.forEach(i -> i.setEvent(null));
}
if (registrations != null) {
registrations.forEach(i -> i.setEvent(this));
}
this.registrations = registrations;
}
public Event registrations(Set<Registration> registrations) {
this.setRegistrations(registrations);
return this;
}
public Event addRegistrations(Registration registration) {
this.registrations.add(registration);
registration.setEvent(this);
return this;
}
public Event removeRegistrations(Registration registration) {
this.registrations.remove(registration);
registration.setEvent(null);
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Event)) {
return false;
}
return getId() != null && getId().equals(((Event) o).getId());
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "Event{" +
"id=" + getId() +
", name='" + getName() + "'" +
", date='" + getDate() + "'" +
", playersLimit=" + getPlayersLimit() +
", cost=" + getCost() +
", comment='" + getComment() + "'" +
"}";
}
}
@@ -0,0 +1,170 @@
package com.sasiedzi.event.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.time.ZonedDateTime;
/**
* A Registration.
*/
@Entity
@Table(name = "registration")
@SuppressWarnings("common-java:DuplicatedBlocks")
public class Registration implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@NotNull
@Column(name = "date_time", nullable = false)
private ZonedDateTime dateTime;
@NotNull
@Column(name = "active", nullable = false)
private Boolean active;
@Column(name = "player_name")
private String playerName;
@Lob
@Column(name = "comment")
private String comment;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = { "registrations" }, allowSetters = true)
private Event event;
// jhipster-needle-entity-add-field - JHipster will add fields here
public Long getId() {
return this.id;
}
public Registration id(Long id) {
this.setId(id);
return this;
}
public void setId(Long id) {
this.id = id;
}
public ZonedDateTime getDateTime() {
return this.dateTime;
}
public Registration dateTime(ZonedDateTime dateTime) {
this.setDateTime(dateTime);
return this;
}
public void setDateTime(ZonedDateTime dateTime) {
this.dateTime = dateTime;
}
public Boolean getActive() {
return this.active;
}
public Registration active(Boolean active) {
this.setActive(active);
return this;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getPlayerName() {
return this.playerName;
}
public Registration playerName(String playerName) {
this.setPlayerName(playerName);
return this;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getComment() {
return this.comment;
}
public Registration comment(String comment) {
this.setComment(comment);
return this;
}
public void setComment(String comment) {
this.comment = comment;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public Registration user(User user) {
this.setUser(user);
return this;
}
public Event getEvent() {
return this.event;
}
public void setEvent(Event event) {
this.event = event;
}
public Registration event(Event event) {
this.setEvent(event);
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Registration)) {
return false;
}
return getId() != null && getId().equals(((Registration) o).getId());
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "Registration{" +
"id=" + getId() +
", dateTime='" + getDateTime() + "'" +
", active='" + getActive() + "'" +
", playerName='" + getPlayerName() + "'" +
", comment='" + getComment() + "'" +
"}";
}
}
@@ -0,0 +1,9 @@
package com.sasiedzi.event.domain.enumeration;
/**
* The ChargeType enumeration.
*/
public enum ChargeType {
CHARGE,
PAYMENT,
}
@@ -0,0 +1,4 @@
/**
* This package file was generated by JHipster
*/
package com.sasiedzi.event.domain.enumeration;
@@ -0,0 +1,40 @@
package com.sasiedzi.event.repository;
import com.sasiedzi.event.domain.Charge;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the Charge entity.
*/
@Repository
public interface ChargeRepository extends JpaRepository<Charge, Long> {
@Query("select charge from Charge charge where charge.user.login = ?#{authentication.name}")
List<Charge> findByUserIsCurrentUser();
default Optional<Charge> findOneWithEagerRelationships(Long id) {
return this.findOneWithToOneRelationships(id);
}
default List<Charge> findAllWithEagerRelationships() {
return this.findAllWithToOneRelationships();
}
default Page<Charge> findAllWithEagerRelationships(Pageable pageable) {
return this.findAllWithToOneRelationships(pageable);
}
@Query(value = "select charge from Charge charge left join fetch charge.user", countQuery = "select count(charge) from Charge charge")
Page<Charge> findAllWithToOneRelationships(Pageable pageable);
@Query("select charge from Charge charge left join fetch charge.user")
List<Charge> findAllWithToOneRelationships();
@Query("select charge from Charge charge left join fetch charge.user where charge.id =:id")
Optional<Charge> findOneWithToOneRelationships(@Param("id") Long id);
}
@@ -0,0 +1,12 @@
package com.sasiedzi.event.repository;
import com.sasiedzi.event.domain.Event;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the Event entity.
*/
@SuppressWarnings("unused")
@Repository
public interface EventRepository extends JpaRepository<Event, Long> {}
@@ -0,0 +1,45 @@
package com.sasiedzi.event.repository;
import com.sasiedzi.event.domain.Registration;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the Registration entity.
*/
@Repository
public interface RegistrationRepository extends JpaRepository<Registration, Long> {
@Query("select registration from Registration registration where registration.user.login = ?#{authentication.name}")
List<Registration> findByUserIsCurrentUser();
default Optional<Registration> findOneWithEagerRelationships(Long id) {
return this.findOneWithToOneRelationships(id);
}
default List<Registration> findAllWithEagerRelationships() {
return this.findAllWithToOneRelationships();
}
default Page<Registration> findAllWithEagerRelationships(Pageable pageable) {
return this.findAllWithToOneRelationships(pageable);
}
@Query(
value = "select registration from Registration registration left join fetch registration.user left join fetch registration.event",
countQuery = "select count(registration) from Registration registration"
)
Page<Registration> findAllWithToOneRelationships(Pageable pageable);
@Query("select registration from Registration registration left join fetch registration.user left join fetch registration.event")
List<Registration> findAllWithToOneRelationships();
@Query(
"select registration from Registration registration left join fetch registration.user left join fetch registration.event where registration.id =:id"
)
Optional<Registration> findOneWithToOneRelationships(@Param("id") Long id);
}
@@ -0,0 +1,114 @@
package com.sasiedzi.event.service;
import com.sasiedzi.event.domain.Event;
import com.sasiedzi.event.repository.EventRepository;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service Implementation for managing {@link com.sasiedzi.event.domain.Event}.
*/
@Service
@Transactional
public class EventService {
private static final Logger LOG = LoggerFactory.getLogger(EventService.class);
private final EventRepository eventRepository;
public EventService(EventRepository eventRepository) {
this.eventRepository = eventRepository;
}
/**
* Save a event.
*
* @param event the entity to save.
* @return the persisted entity.
*/
public Event save(Event event) {
LOG.debug("Request to save Event : {}", event);
return eventRepository.save(event);
}
/**
* Update a event.
*
* @param event the entity to save.
* @return the persisted entity.
*/
public Event update(Event event) {
LOG.debug("Request to update Event : {}", event);
return eventRepository.save(event);
}
/**
* Partially update a event.
*
* @param event the entity to update partially.
* @return the persisted entity.
*/
public Optional<Event> partialUpdate(Event event) {
LOG.debug("Request to partially update Event : {}", event);
return eventRepository
.findById(event.getId())
.map(existingEvent -> {
if (event.getName() != null) {
existingEvent.setName(event.getName());
}
if (event.getDate() != null) {
existingEvent.setDate(event.getDate());
}
if (event.getPlayersLimit() != null) {
existingEvent.setPlayersLimit(event.getPlayersLimit());
}
if (event.getCost() != null) {
existingEvent.setCost(event.getCost());
}
if (event.getComment() != null) {
existingEvent.setComment(event.getComment());
}
return existingEvent;
})
.map(eventRepository::save);
}
/**
* Get all the events.
*
* @return the list of entities.
*/
@Transactional(readOnly = true)
public List<Event> findAll() {
LOG.debug("Request to get all Events");
return eventRepository.findAll();
}
/**
* Get one event by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Transactional(readOnly = true)
public Optional<Event> findOne(Long id) {
LOG.debug("Request to get Event : {}", id);
return eventRepository.findById(id);
}
/**
* Delete the event by id.
*
* @param id the id of the entity.
*/
public void delete(Long id) {
LOG.debug("Request to delete Event : {}", id);
eventRepository.deleteById(id);
}
}
@@ -0,0 +1,189 @@
package com.sasiedzi.event.web.rest;
import com.sasiedzi.event.domain.Charge;
import com.sasiedzi.event.repository.ChargeRepository;
import com.sasiedzi.event.web.rest.errors.BadRequestAlertException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link com.sasiedzi.event.domain.Charge}.
*/
@RestController
@RequestMapping("/api/charges")
@Transactional
public class ChargeResource {
private static final Logger LOG = LoggerFactory.getLogger(ChargeResource.class);
private static final String ENTITY_NAME = "charge";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final ChargeRepository chargeRepository;
public ChargeResource(ChargeRepository chargeRepository) {
this.chargeRepository = chargeRepository;
}
/**
* {@code POST /charges} : Create a new charge.
*
* @param charge the charge to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new charge, or with status {@code 400 (Bad Request)} if the charge has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("")
public ResponseEntity<Charge> createCharge(@Valid @RequestBody Charge charge) throws URISyntaxException {
LOG.debug("REST request to save Charge : {}", charge);
if (charge.getId() != null) {
throw new BadRequestAlertException("A new charge cannot already have an ID", ENTITY_NAME, "idexists");
}
charge = chargeRepository.save(charge);
return ResponseEntity.created(new URI("/api/charges/" + charge.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, charge.getId().toString()))
.body(charge);
}
/**
* {@code PUT /charges/:id} : Updates an existing charge.
*
* @param id the id of the charge to save.
* @param charge the charge to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated charge,
* or with status {@code 400 (Bad Request)} if the charge is not valid,
* or with status {@code 500 (Internal Server Error)} if the charge couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/{id}")
public ResponseEntity<Charge> updateCharge(
@PathVariable(value = "id", required = false) final Long id,
@Valid @RequestBody Charge charge
) throws URISyntaxException {
LOG.debug("REST request to update Charge : {}, {}", id, charge);
if (charge.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, charge.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!chargeRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
charge = chargeRepository.save(charge);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, charge.getId().toString()))
.body(charge);
}
/**
* {@code PATCH /charges/:id} : Partial updates given fields of an existing charge, field will ignore if it is null
*
* @param id the id of the charge to save.
* @param charge the charge to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated charge,
* or with status {@code 400 (Bad Request)} if the charge is not valid,
* or with status {@code 404 (Not Found)} if the charge is not found,
* or with status {@code 500 (Internal Server Error)} if the charge couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity<Charge> partialUpdateCharge(
@PathVariable(value = "id", required = false) final Long id,
@NotNull @RequestBody Charge charge
) throws URISyntaxException {
LOG.debug("REST request to partial update Charge partially : {}, {}", id, charge);
if (charge.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, charge.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!chargeRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
Optional<Charge> result = chargeRepository
.findById(charge.getId())
.map(existingCharge -> {
if (charge.getChargeDate() != null) {
existingCharge.setChargeDate(charge.getChargeDate());
}
if (charge.getType() != null) {
existingCharge.setType(charge.getType());
}
if (charge.getAmount() != null) {
existingCharge.setAmount(charge.getAmount());
}
return existingCharge;
})
.map(chargeRepository::save);
return ResponseUtil.wrapOrNotFound(
result,
HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, charge.getId().toString())
);
}
/**
* {@code GET /charges} : get all the charges.
*
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of charges in body.
*/
@GetMapping("")
public List<Charge> getAllCharges(@RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload) {
LOG.debug("REST request to get all Charges");
if (eagerload) {
return chargeRepository.findAllWithEagerRelationships();
} else {
return chargeRepository.findAll();
}
}
/**
* {@code GET /charges/:id} : get the "id" charge.
*
* @param id the id of the charge to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the charge, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/{id}")
public ResponseEntity<Charge> getCharge(@PathVariable("id") Long id) {
LOG.debug("REST request to get Charge : {}", id);
Optional<Charge> charge = chargeRepository.findOneWithEagerRelationships(id);
return ResponseUtil.wrapOrNotFound(charge);
}
/**
* {@code DELETE /charges/:id} : delete the "id" charge.
*
* @param id the id of the charge to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCharge(@PathVariable("id") Long id) {
LOG.debug("REST request to delete Charge : {}", id);
chargeRepository.deleteById(id);
return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
.build();
}
}
@@ -0,0 +1,169 @@
package com.sasiedzi.event.web.rest;
import com.sasiedzi.event.domain.Event;
import com.sasiedzi.event.repository.EventRepository;
import com.sasiedzi.event.service.EventService;
import com.sasiedzi.event.web.rest.errors.BadRequestAlertException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link com.sasiedzi.event.domain.Event}.
*/
@RestController
@RequestMapping("/api/events")
public class EventResource {
private static final Logger LOG = LoggerFactory.getLogger(EventResource.class);
private static final String ENTITY_NAME = "event";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final EventService eventService;
private final EventRepository eventRepository;
public EventResource(EventService eventService, EventRepository eventRepository) {
this.eventService = eventService;
this.eventRepository = eventRepository;
}
/**
* {@code POST /events} : Create a new event.
*
* @param event the event to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new event, or with status {@code 400 (Bad Request)} if the event has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("")
public ResponseEntity<Event> createEvent(@Valid @RequestBody Event event) throws URISyntaxException {
LOG.debug("REST request to save Event : {}", event);
if (event.getId() != null) {
throw new BadRequestAlertException("A new event cannot already have an ID", ENTITY_NAME, "idexists");
}
event = eventService.save(event);
return ResponseEntity.created(new URI("/api/events/" + event.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, event.getId().toString()))
.body(event);
}
/**
* {@code PUT /events/:id} : Updates an existing event.
*
* @param id the id of the event to save.
* @param event the event to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated event,
* or with status {@code 400 (Bad Request)} if the event is not valid,
* or with status {@code 500 (Internal Server Error)} if the event couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/{id}")
public ResponseEntity<Event> updateEvent(@PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody Event event)
throws URISyntaxException {
LOG.debug("REST request to update Event : {}, {}", id, event);
if (event.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, event.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!eventRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
event = eventService.update(event);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, event.getId().toString()))
.body(event);
}
/**
* {@code PATCH /events/:id} : Partial updates given fields of an existing event, field will ignore if it is null
*
* @param id the id of the event to save.
* @param event the event to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated event,
* or with status {@code 400 (Bad Request)} if the event is not valid,
* or with status {@code 404 (Not Found)} if the event is not found,
* or with status {@code 500 (Internal Server Error)} if the event couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity<Event> partialUpdateEvent(
@PathVariable(value = "id", required = false) final Long id,
@NotNull @RequestBody Event event
) throws URISyntaxException {
LOG.debug("REST request to partial update Event partially : {}, {}", id, event);
if (event.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, event.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!eventRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
Optional<Event> result = eventService.partialUpdate(event);
return ResponseUtil.wrapOrNotFound(
result,
HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, event.getId().toString())
);
}
/**
* {@code GET /events} : get all the events.
*
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of events in body.
*/
@GetMapping("")
public List<Event> getAllEvents() {
LOG.debug("REST request to get all Events");
return eventService.findAll();
}
/**
* {@code GET /events/:id} : get the "id" event.
*
* @param id the id of the event to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the event, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/{id}")
public ResponseEntity<Event> getEvent(@PathVariable("id") Long id) {
LOG.debug("REST request to get Event : {}", id);
Optional<Event> event = eventService.findOne(id);
return ResponseUtil.wrapOrNotFound(event);
}
/**
* {@code DELETE /events/:id} : delete the "id" event.
*
* @param id the id of the event to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEvent(@PathVariable("id") Long id) {
LOG.debug("REST request to delete Event : {}", id);
eventService.delete(id);
return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
.build();
}
}
@@ -0,0 +1,194 @@
package com.sasiedzi.event.web.rest;
import com.sasiedzi.event.domain.Registration;
import com.sasiedzi.event.repository.RegistrationRepository;
import com.sasiedzi.event.web.rest.errors.BadRequestAlertException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link com.sasiedzi.event.domain.Registration}.
*/
@RestController
@RequestMapping("/api/registrations")
@Transactional
public class RegistrationResource {
private static final Logger LOG = LoggerFactory.getLogger(RegistrationResource.class);
private static final String ENTITY_NAME = "registration";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final RegistrationRepository registrationRepository;
public RegistrationResource(RegistrationRepository registrationRepository) {
this.registrationRepository = registrationRepository;
}
/**
* {@code POST /registrations} : Create a new registration.
*
* @param registration the registration to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new registration, or with status {@code 400 (Bad Request)} if the registration has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("")
public ResponseEntity<Registration> createRegistration(@Valid @RequestBody Registration registration) throws URISyntaxException {
LOG.debug("REST request to save Registration : {}", registration);
if (registration.getId() != null) {
throw new BadRequestAlertException("A new registration cannot already have an ID", ENTITY_NAME, "idexists");
}
registration = registrationRepository.save(registration);
return ResponseEntity.created(new URI("/api/registrations/" + registration.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, registration.getId().toString()))
.body(registration);
}
/**
* {@code PUT /registrations/:id} : Updates an existing registration.
*
* @param id the id of the registration to save.
* @param registration the registration to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated registration,
* or with status {@code 400 (Bad Request)} if the registration is not valid,
* or with status {@code 500 (Internal Server Error)} if the registration couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/{id}")
public ResponseEntity<Registration> updateRegistration(
@PathVariable(value = "id", required = false) final Long id,
@Valid @RequestBody Registration registration
) throws URISyntaxException {
LOG.debug("REST request to update Registration : {}, {}", id, registration);
if (registration.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, registration.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!registrationRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
registration = registrationRepository.save(registration);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, registration.getId().toString()))
.body(registration);
}
/**
* {@code PATCH /registrations/:id} : Partial updates given fields of an existing registration, field will ignore if it is null
*
* @param id the id of the registration to save.
* @param registration the registration to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated registration,
* or with status {@code 400 (Bad Request)} if the registration is not valid,
* or with status {@code 404 (Not Found)} if the registration is not found,
* or with status {@code 500 (Internal Server Error)} if the registration couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity<Registration> partialUpdateRegistration(
@PathVariable(value = "id", required = false) final Long id,
@NotNull @RequestBody Registration registration
) throws URISyntaxException {
LOG.debug("REST request to partial update Registration partially : {}, {}", id, registration);
if (registration.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, registration.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!registrationRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
Optional<Registration> result = registrationRepository
.findById(registration.getId())
.map(existingRegistration -> {
if (registration.getDateTime() != null) {
existingRegistration.setDateTime(registration.getDateTime());
}
if (registration.getActive() != null) {
existingRegistration.setActive(registration.getActive());
}
if (registration.getPlayerName() != null) {
existingRegistration.setPlayerName(registration.getPlayerName());
}
if (registration.getComment() != null) {
existingRegistration.setComment(registration.getComment());
}
return existingRegistration;
})
.map(registrationRepository::save);
return ResponseUtil.wrapOrNotFound(
result,
HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, registration.getId().toString())
);
}
/**
* {@code GET /registrations} : get all the registrations.
*
* @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of registrations in body.
*/
@GetMapping("")
public List<Registration> getAllRegistrations(
@RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
) {
LOG.debug("REST request to get all Registrations");
if (eagerload) {
return registrationRepository.findAllWithEagerRelationships();
} else {
return registrationRepository.findAll();
}
}
/**
* {@code GET /registrations/:id} : get the "id" registration.
*
* @param id the id of the registration to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the registration, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/{id}")
public ResponseEntity<Registration> getRegistration(@PathVariable("id") Long id) {
LOG.debug("REST request to get Registration : {}", id);
Optional<Registration> registration = registrationRepository.findOneWithEagerRelationships(id);
return ResponseUtil.wrapOrNotFound(registration);
}
/**
* {@code DELETE /registrations/:id} : delete the "id" registration.
*
* @param id the id of the registration to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteRegistration(@PathVariable("id") Long id) {
LOG.debug("REST request to delete Registration : {}", id);
registrationRepository.deleteById(id);
return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
.build();
}
}
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<!--
Added the entity Charge.
-->
<changeSet id="20241105091001-1" author="jhipster">
<createTable tableName="charge">
<column name="id" type="bigint">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="charge_date" type="date">
<constraints nullable="false" />
</column>
<column name="type" type="varchar(255)">
<constraints nullable="false" />
</column>
<column name="amount" type="decimal(21,2)">
<constraints nullable="false" />
</column>
<column name="event_id" type="bigint">
<constraints nullable="true" />
</column>
<column name="registration_id" type="bigint">
<constraints nullable="true" />
</column>
<column name="user_id" type="varchar(100)">
<constraints nullable="true" />
</column>
<!-- jhipster-needle-liquibase-add-column - JHipster will add columns here -->
</createTable>
</changeSet>
<!-- jhipster-needle-liquibase-add-changeset - JHipster will add changesets here -->
<!--
Load sample data generated with Faker.js
- This data can be easily edited using a CSV editor (or even MS Excel) and
is located in the 'src/main/resources/config/liquibase/fake-data' directory
- By default this data is applied when running with the JHipster 'dev' profile.
This can be customized by adding or removing 'faker' in the 'spring.liquibase.contexts'
Spring Boot configuration key.
-->
<changeSet id="20241105091001-1-data" author="jhipster" context="faker">
<loadData
file="config/liquibase/fake-data/charge.csv"
separator=";"
tableName="charge"
usePreparedStatements="true">
<column name="id" type="numeric"/>
<column name="charge_date" type="date"/>
<column name="type" type="string"/>
<column name="amount" type="numeric"/>
<!-- jhipster-needle-liquibase-add-loadcolumn - JHipster (and/or extensions) can add load columns here -->
</loadData>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<!--
Added the constraints for entity Charge.
-->
<changeSet id="20241105091001-2" author="jhipster">
<addForeignKeyConstraint baseColumnNames="event_id"
baseTableName="charge"
constraintName="fk_charge__event_id"
referencedColumnNames="id"
referencedTableName="event"
/>
<addForeignKeyConstraint baseColumnNames="registration_id"
baseTableName="charge"
constraintName="fk_charge__registration_id"
referencedColumnNames="id"
referencedTableName="registration"
/>
<addForeignKeyConstraint baseColumnNames="user_id"
baseTableName="charge"
constraintName="fk_charge__user_id"
referencedColumnNames="id"
referencedTableName="jhi_user"
/>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<!--
Added the entity Event.
-->
<changeSet id="20241105091002-1" author="jhipster">
<createTable tableName="event">
<column name="id" type="bigint">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="name" type="varchar(255)">
<constraints nullable="false" />
</column>
<column name="date" type="date">
<constraints nullable="false" />
</column>
<column name="players_limit" type="integer">
<constraints nullable="true" />
</column>
<column name="cost" type="decimal(21,2)">
<constraints nullable="true" />
</column>
<column name="comment" type="${clobType}">
<constraints nullable="true" />
</column>
<!-- jhipster-needle-liquibase-add-column - JHipster will add columns here -->
</createTable>
</changeSet>
<!-- jhipster-needle-liquibase-add-changeset - JHipster will add changesets here -->
<!--
Load sample data generated with Faker.js
- This data can be easily edited using a CSV editor (or even MS Excel) and
is located in the 'src/main/resources/config/liquibase/fake-data' directory
- By default this data is applied when running with the JHipster 'dev' profile.
This can be customized by adding or removing 'faker' in the 'spring.liquibase.contexts'
Spring Boot configuration key.
-->
<changeSet id="20241105091002-1-data" author="jhipster" context="faker">
<loadData
file="config/liquibase/fake-data/event.csv"
separator=";"
tableName="event"
usePreparedStatements="true">
<column name="id" type="numeric"/>
<column name="name" type="string"/>
<column name="date" type="date"/>
<column name="players_limit" type="numeric"/>
<column name="cost" type="numeric"/>
<column name="comment" type="clob"/>
<!-- jhipster-needle-liquibase-add-loadcolumn - JHipster (and/or extensions) can add load columns here -->
</loadData>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<!--
Added the entity Registration.
-->
<changeSet id="20241105091003-1" author="jhipster">
<createTable tableName="registration">
<column name="id" type="bigint">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="date_time" type="${datetimeType}">
<constraints nullable="false" />
</column>
<column name="active" type="boolean">
<constraints nullable="false" />
</column>
<column name="player_name" type="varchar(255)">
<constraints nullable="true" />
</column>
<column name="comment" type="${clobType}">
<constraints nullable="true" />
</column>
<column name="user_id" type="varchar(100)">
<constraints nullable="true" />
</column>
<column name="event_id" type="bigint">
<constraints nullable="true" />
</column>
<!-- jhipster-needle-liquibase-add-column - JHipster will add columns here -->
</createTable>
<dropDefaultValue tableName="registration" columnName="date_time" columnDataType="${datetimeType}"/>
</changeSet>
<!-- jhipster-needle-liquibase-add-changeset - JHipster will add changesets here -->
<!--
Load sample data generated with Faker.js
- This data can be easily edited using a CSV editor (or even MS Excel) and
is located in the 'src/main/resources/config/liquibase/fake-data' directory
- By default this data is applied when running with the JHipster 'dev' profile.
This can be customized by adding or removing 'faker' in the 'spring.liquibase.contexts'
Spring Boot configuration key.
-->
<changeSet id="20241105091003-1-data" author="jhipster" context="faker">
<loadData
file="config/liquibase/fake-data/registration.csv"
separator=";"
tableName="registration"
usePreparedStatements="true">
<column name="id" type="numeric"/>
<column name="date_time" type="date"/>
<column name="active" type="boolean"/>
<column name="player_name" type="string"/>
<column name="comment" type="clob"/>
<!-- jhipster-needle-liquibase-add-loadcolumn - JHipster (and/or extensions) can add load columns here -->
</loadData>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<!--
Added the constraints for entity Registration.
-->
<changeSet id="20241105091003-2" author="jhipster">
<addForeignKeyConstraint baseColumnNames="user_id"
baseTableName="registration"
constraintName="fk_registration__user_id"
referencedColumnNames="id"
referencedTableName="jhi_user"
/>
<addForeignKeyConstraint baseColumnNames="event_id"
baseTableName="registration"
constraintName="fk_registration__event_id"
referencedColumnNames="id"
referencedTableName="event"
/>
</changeSet>
</databaseChangeLog>
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

@@ -0,0 +1 @@
JHipster is a development platform to generate, develop and deploy Spring Boot + Angular / React / Vue Web applications and Spring microservices.
@@ -0,0 +1,11 @@
id;charge_date;type;amount
1;2024-11-05;CHARGE;9041.03
2;2024-11-04;CHARGE;21481.71
3;2024-11-05;PAYMENT;20706.62
4;2024-11-05;PAYMENT;3052.82
5;2024-11-04;CHARGE;19800.11
6;2024-11-04;PAYMENT;21867.73
7;2024-11-05;PAYMENT;27189.8
8;2024-11-04;CHARGE;24639.37
9;2024-11-04;CHARGE;11995.91
10;2024-11-04;PAYMENT;14703.4
1 id charge_date type amount
2 1 2024-11-05 CHARGE 9041.03
3 2 2024-11-04 CHARGE 21481.71
4 3 2024-11-05 PAYMENT 20706.62
5 4 2024-11-05 PAYMENT 3052.82
6 5 2024-11-04 CHARGE 19800.11
7 6 2024-11-04 PAYMENT 21867.73
8 7 2024-11-05 PAYMENT 27189.8
9 8 2024-11-04 CHARGE 24639.37
10 9 2024-11-04 CHARGE 11995.91
11 10 2024-11-04 PAYMENT 14703.4
@@ -0,0 +1,11 @@
id;name;date;players_limit;cost;comment
1;beyond;2024-11-04;10433;29183.35;../fake-data/blob/hipster.txt
2;consequently um;2024-11-04;19962;5298.5;../fake-data/blob/hipster.txt
3;phooey incidentally excepting;2024-11-05;18229;24949;../fake-data/blob/hipster.txt
4;hmph;2024-11-05;12797;23126.51;../fake-data/blob/hipster.txt
5;whether;2024-11-04;29300;6622.71;../fake-data/blob/hipster.txt
6;wound;2024-11-05;5236;6534.13;../fake-data/blob/hipster.txt
7;insignificant downshift gallery;2024-11-05;6735;17678.34;../fake-data/blob/hipster.txt
8;hence astride;2024-11-04;354;399.79;../fake-data/blob/hipster.txt
9;selfishly;2024-11-05;14372;29015.86;../fake-data/blob/hipster.txt
10;whoever phooey until;2024-11-05;27795;1239.07;../fake-data/blob/hipster.txt
1 id name date players_limit cost comment
2 1 beyond 2024-11-04 10433 29183.35 ../fake-data/blob/hipster.txt
3 2 consequently um 2024-11-04 19962 5298.5 ../fake-data/blob/hipster.txt
4 3 phooey incidentally excepting 2024-11-05 18229 24949 ../fake-data/blob/hipster.txt
5 4 hmph 2024-11-05 12797 23126.51 ../fake-data/blob/hipster.txt
6 5 whether 2024-11-04 29300 6622.71 ../fake-data/blob/hipster.txt
7 6 wound 2024-11-05 5236 6534.13 ../fake-data/blob/hipster.txt
8 7 insignificant downshift gallery 2024-11-05 6735 17678.34 ../fake-data/blob/hipster.txt
9 8 hence astride 2024-11-04 354 399.79 ../fake-data/blob/hipster.txt
10 9 selfishly 2024-11-05 14372 29015.86 ../fake-data/blob/hipster.txt
11 10 whoever phooey until 2024-11-05 27795 1239.07 ../fake-data/blob/hipster.txt
@@ -0,0 +1,11 @@
id;date_time;active;player_name;comment
1;2024-11-04T21:39:10;true;towards;../fake-data/blob/hipster.txt
2;2024-11-04T16:49:21;true;because last;../fake-data/blob/hipster.txt
3;2024-11-04T20:56:23;false;even;../fake-data/blob/hipster.txt
4;2024-11-05T04:46:06;true;untrue;../fake-data/blob/hipster.txt
5;2024-11-04T12:41:16;true;devise thorn;../fake-data/blob/hipster.txt
6;2024-11-05T00:16:30;false;rotten aw bah;../fake-data/blob/hipster.txt
7;2024-11-05T02:43:46;true;amidst;../fake-data/blob/hipster.txt
8;2024-11-04T09:14:58;false;vice;../fake-data/blob/hipster.txt
9;2024-11-04T14:16:43;false;truly thoughtfully;../fake-data/blob/hipster.txt
10;2024-11-05T07:55:10;false;courtroom annex;../fake-data/blob/hipster.txt
1 id date_time active player_name comment
2 1 2024-11-04T21:39:10 true towards ../fake-data/blob/hipster.txt
3 2 2024-11-04T16:49:21 true because last ../fake-data/blob/hipster.txt
4 3 2024-11-04T20:56:23 false even ../fake-data/blob/hipster.txt
5 4 2024-11-05T04:46:06 true untrue ../fake-data/blob/hipster.txt
6 5 2024-11-04T12:41:16 true devise thorn ../fake-data/blob/hipster.txt
7 6 2024-11-05T00:16:30 false rotten aw bah ../fake-data/blob/hipster.txt
8 7 2024-11-05T02:43:46 true amidst ../fake-data/blob/hipster.txt
9 8 2024-11-04T09:14:58 false vice ../fake-data/blob/hipster.txt
10 9 2024-11-04T14:16:43 false truly thoughtfully ../fake-data/blob/hipster.txt
11 10 2024-11-05T07:55:10 false courtroom annex ../fake-data/blob/hipster.txt
@@ -11,7 +11,12 @@
<property name="datetimeType" value="datetime" dbms="postgresql"/>
<include file="config/liquibase/changelog/00000000000000_initial_schema.xml" relativeToChangelogFile="false"/>
<include file="config/liquibase/changelog/20241105091001_added_entity_Charge.xml" relativeToChangelogFile="false"/>
<include file="config/liquibase/changelog/20241105091002_added_entity_Event.xml" relativeToChangelogFile="false"/>
<include file="config/liquibase/changelog/20241105091003_added_entity_Registration.xml" relativeToChangelogFile="false"/>
<!-- jhipster-needle-liquibase-add-changelog - JHipster will add liquibase changelogs here -->
<include file="config/liquibase/changelog/20241105091001_added_entity_constraints_Charge.xml" relativeToChangelogFile="false"/>
<include file="config/liquibase/changelog/20241105091003_added_entity_constraints_Registration.xml" relativeToChangelogFile="false"/>
<!-- jhipster-needle-liquibase-add-constraints-changelog - JHipster will add liquibase constraints changelogs here -->
<!-- jhipster-needle-liquibase-add-incremental-changelog - JHipster will add incremental liquibase changelogs here -->
</databaseChangeLog>
@@ -0,0 +1,89 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import { type RouteLocation } from 'vue-router';
import ChargeDetails from './charge-details.vue';
import ChargeService from './charge.service';
import AlertService from '@/shared/alert/alert.service';
type ChargeDetailsComponentType = InstanceType<typeof ChargeDetails>;
let route: Partial<RouteLocation>;
const routerGoMock = vitest.fn();
vitest.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const chargeSample = { id: 123 };
describe('Component Tests', () => {
let alertService: AlertService;
afterEach(() => {
vitest.resetAllMocks();
});
describe('Charge Management Detail Component', () => {
let chargeServiceStub: SinonStubbedInstance<ChargeService>;
let mountOptions: MountingOptions<ChargeDetailsComponentType>['global'];
beforeEach(() => {
route = {};
chargeServiceStub = sinon.createStubInstance<ChargeService>(ChargeService);
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'router-link': true,
},
provide: {
alertService,
chargeService: () => chargeServiceStub,
},
};
});
describe('Navigate to details', () => {
it('Should call load all on init', async () => {
// GIVEN
chargeServiceStub.find.resolves(chargeSample);
route = {
params: {
chargeId: `${123}`,
},
};
const wrapper = shallowMount(ChargeDetails, { global: mountOptions });
const comp = wrapper.vm;
// WHEN
await comp.$nextTick();
// THEN
expect(comp.charge).toMatchObject(chargeSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
chargeServiceStub.find.resolves(chargeSample);
const wrapper = shallowMount(ChargeDetails, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,41 @@
import { type Ref, defineComponent, inject, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import ChargeService from './charge.service';
import { type ICharge } from '@/shared/model/charge.model';
import { useAlertService } from '@/shared/alert/alert.service';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'ChargeDetails',
setup() {
const chargeService = inject('chargeService', () => new ChargeService());
const alertService = inject('alertService', () => useAlertService(), true);
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const charge: Ref<ICharge> = ref({});
const retrieveCharge = async chargeId => {
try {
const res = await chargeService().find(chargeId);
charge.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.chargeId) {
retrieveCharge(route.params.chargeId);
}
return {
alertService,
charge,
previousState,
};
},
});
@@ -0,0 +1,63 @@
<template>
<div class="row justify-content-center">
<div class="col-8">
<div v-if="charge">
<h2 class="jh-entity-heading" data-cy="chargeDetailsHeading"><span>Charge</span> {{ charge.id }}</h2>
<dl class="row jh-entity-details">
<dt>
<span>Charge Date</span>
</dt>
<dd>
<span>{{ charge.chargeDate }}</span>
</dd>
<dt>
<span>Type</span>
</dt>
<dd>
<span>{{ charge.type }}</span>
</dd>
<dt>
<span>Amount</span>
</dt>
<dd>
<span>{{ charge.amount }}</span>
</dd>
<dt>
<span>Event</span>
</dt>
<dd>
<div v-if="charge.event">
<router-link :to="{ name: 'EventView', params: { eventId: charge.event.id } }">{{ charge.event.id }}</router-link>
</div>
</dd>
<dt>
<span>Registration</span>
</dt>
<dd>
<div v-if="charge.registration">
<router-link :to="{ name: 'RegistrationView', params: { registrationId: charge.registration.id } }">{{
charge.registration.id
}}</router-link>
</div>
</dd>
<dt>
<span>User</span>
</dt>
<dd>
{{ charge.user ? charge.user.login : '' }}
</dd>
</dl>
<button type="submit" @click.prevent="previousState()" class="btn btn-info" data-cy="entityDetailsBackButton">
<font-awesome-icon icon="arrow-left"></font-awesome-icon>&nbsp;<span>Back</span>
</button>
<router-link v-if="charge.id" :to="{ name: 'ChargeEdit', params: { chargeId: charge.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-primary">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>&nbsp;<span>Edit</span>
</button>
</router-link>
</div>
</div>
</div>
</template>
<script lang="ts" src="./charge-details.component.ts"></script>
@@ -0,0 +1,149 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import { type RouteLocation } from 'vue-router';
import ChargeUpdate from './charge-update.vue';
import ChargeService from './charge.service';
import AlertService from '@/shared/alert/alert.service';
import EventService from '@/entities/event/event.service';
import RegistrationService from '@/entities/registration/registration.service';
import UserService from '@/entities/user/user.service';
type ChargeUpdateComponentType = InstanceType<typeof ChargeUpdate>;
let route: Partial<RouteLocation>;
const routerGoMock = vitest.fn();
vitest.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const chargeSample = { id: 123 };
describe('Component Tests', () => {
let mountOptions: MountingOptions<ChargeUpdateComponentType>['global'];
let alertService: AlertService;
describe('Charge Management Update Component', () => {
let comp: ChargeUpdateComponentType;
let chargeServiceStub: SinonStubbedInstance<ChargeService>;
beforeEach(() => {
route = {};
chargeServiceStub = sinon.createStubInstance<ChargeService>(ChargeService);
chargeServiceStub.retrieve.onFirstCall().resolves(Promise.resolve([]));
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'b-input-group': true,
'b-input-group-prepend': true,
'b-form-datepicker': true,
'b-form-input': true,
},
provide: {
alertService,
chargeService: () => chargeServiceStub,
eventService: () =>
sinon.createStubInstance<EventService>(EventService, {
retrieve: sinon.stub().resolves({}),
} as any),
registrationService: () =>
sinon.createStubInstance<RegistrationService>(RegistrationService, {
retrieve: sinon.stub().resolves({}),
} as any),
userService: () =>
sinon.createStubInstance<UserService>(UserService, {
retrieve: sinon.stub().resolves({}),
} as any),
},
};
});
afterEach(() => {
vitest.resetAllMocks();
});
describe('save', () => {
it('Should call update service on save for existing entity', async () => {
// GIVEN
const wrapper = shallowMount(ChargeUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.charge = chargeSample;
chargeServiceStub.update.resolves(chargeSample);
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(chargeServiceStub.update.calledWith(chargeSample)).toBeTruthy();
expect(comp.isSaving).toEqual(false);
});
it('Should call create service on save for new entity', async () => {
// GIVEN
const entity = {};
chargeServiceStub.create.resolves(entity);
const wrapper = shallowMount(ChargeUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.charge = entity;
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(chargeServiceStub.create.calledWith(entity)).toBeTruthy();
expect(comp.isSaving).toEqual(false);
});
});
describe('Before route enter', () => {
it('Should retrieve data', async () => {
// GIVEN
chargeServiceStub.find.resolves(chargeSample);
chargeServiceStub.retrieve.resolves([chargeSample]);
// WHEN
route = {
params: {
chargeId: `${chargeSample.id}`,
},
};
const wrapper = shallowMount(ChargeUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(comp.charge).toMatchObject(chargeSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
chargeServiceStub.find.resolves(chargeSample);
const wrapper = shallowMount(ChargeUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,140 @@
import { type Ref, computed, defineComponent, inject, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useVuelidate } from '@vuelidate/core';
import ChargeService from './charge.service';
import { useValidation } from '@/shared/composables';
import { useAlertService } from '@/shared/alert/alert.service';
import EventService from '@/entities/event/event.service';
import { type IEvent } from '@/shared/model/event.model';
import RegistrationService from '@/entities/registration/registration.service';
import { type IRegistration } from '@/shared/model/registration.model';
import UserService from '@/entities/user/user.service';
import { Charge, type ICharge } from '@/shared/model/charge.model';
import { ChargeType } from '@/shared/model/enumerations/charge-type.model';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'ChargeUpdate',
setup() {
const chargeService = inject('chargeService', () => new ChargeService());
const alertService = inject('alertService', () => useAlertService(), true);
const charge: Ref<ICharge> = ref(new Charge());
const eventService = inject('eventService', () => new EventService());
const events: Ref<IEvent[]> = ref([]);
const registrationService = inject('registrationService', () => new RegistrationService());
const registrations: Ref<IRegistration[]> = ref([]);
const userService = inject('userService', () => new UserService());
const users: Ref<Array<any>> = ref([]);
const chargeTypeValues: Ref<string[]> = ref(Object.keys(ChargeType));
const isSaving = ref(false);
const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'en'), true);
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const retrieveCharge = async chargeId => {
try {
const res = await chargeService().find(chargeId);
charge.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.chargeId) {
retrieveCharge(route.params.chargeId);
}
const initRelationships = () => {
eventService()
.retrieve()
.then(res => {
events.value = res.data;
});
registrationService()
.retrieve()
.then(res => {
registrations.value = res.data;
});
userService()
.retrieve()
.then(res => {
users.value = res.data;
});
};
initRelationships();
const validations = useValidation();
const validationRules = {
chargeDate: {
required: validations.required('This field is required.'),
},
type: {
required: validations.required('This field is required.'),
},
amount: {
required: validations.required('This field is required.'),
},
event: {},
registration: {},
user: {},
};
const v$ = useVuelidate(validationRules, charge as any);
v$.value.$validate();
return {
chargeService,
alertService,
charge,
previousState,
chargeTypeValues,
isSaving,
currentLanguage,
events,
registrations,
users,
v$,
};
},
created(): void {},
methods: {
save(): void {
this.isSaving = true;
if (this.charge.id) {
this.chargeService()
.update(this.charge)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showInfo(`A Charge is updated with identifier ${param.id}`);
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
} else {
this.chargeService()
.create(this.charge)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showSuccess(`A Charge is created with identifier ${param.id}`);
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
}
},
},
});
@@ -0,0 +1,134 @@
<template>
<div class="row justify-content-center">
<div class="col-8">
<form name="editForm" novalidate @submit.prevent="save()">
<h2 id="sasiedziApp.charge.home.createOrEditLabel" data-cy="ChargeCreateUpdateHeading">Create or edit a Charge</h2>
<div>
<div class="form-group" v-if="charge.id">
<label for="id">ID</label>
<input type="text" class="form-control" id="id" name="id" v-model="charge.id" readonly />
</div>
<div class="form-group">
<label class="form-control-label" for="charge-chargeDate">Charge Date</label>
<b-input-group class="mb-3">
<b-input-group-prepend>
<b-form-datepicker
aria-controls="charge-chargeDate"
v-model="v$.chargeDate.$model"
name="chargeDate"
class="form-control"
:locale="currentLanguage"
button-only
today-button
reset-button
close-button
>
</b-form-datepicker>
</b-input-group-prepend>
<b-form-input
id="charge-chargeDate"
data-cy="chargeDate"
type="text"
class="form-control"
name="chargeDate"
:class="{ valid: !v$.chargeDate.$invalid, invalid: v$.chargeDate.$invalid }"
v-model="v$.chargeDate.$model"
required
/>
</b-input-group>
<div v-if="v$.chargeDate.$anyDirty && v$.chargeDate.$invalid">
<small class="form-text text-danger" v-for="error of v$.chargeDate.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="charge-type">Type</label>
<select
class="form-control"
name="type"
:class="{ valid: !v$.type.$invalid, invalid: v$.type.$invalid }"
v-model="v$.type.$model"
id="charge-type"
data-cy="type"
required
>
<option v-for="chargeType in chargeTypeValues" :key="chargeType" :value="chargeType">{{ chargeType }}</option>
</select>
<div v-if="v$.type.$anyDirty && v$.type.$invalid">
<small class="form-text text-danger" v-for="error of v$.type.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="charge-amount">Amount</label>
<input
type="number"
class="form-control"
name="amount"
id="charge-amount"
data-cy="amount"
:class="{ valid: !v$.amount.$invalid, invalid: v$.amount.$invalid }"
v-model.number="v$.amount.$model"
required
/>
<div v-if="v$.amount.$anyDirty && v$.amount.$invalid">
<small class="form-text text-danger" v-for="error of v$.amount.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="charge-event">Event</label>
<select class="form-control" id="charge-event" data-cy="event" name="event" v-model="charge.event">
<option :value="null"></option>
<option
:value="charge.event && eventOption.id === charge.event.id ? charge.event : eventOption"
v-for="eventOption in events"
:key="eventOption.id"
>
{{ eventOption.id }}
</option>
</select>
</div>
<div class="form-group">
<label class="form-control-label" for="charge-registration">Registration</label>
<select class="form-control" id="charge-registration" data-cy="registration" name="registration" v-model="charge.registration">
<option :value="null"></option>
<option
:value="charge.registration && registrationOption.id === charge.registration.id ? charge.registration : registrationOption"
v-for="registrationOption in registrations"
:key="registrationOption.id"
>
{{ registrationOption.id }}
</option>
</select>
</div>
<div class="form-group">
<label class="form-control-label" for="charge-user">User</label>
<select class="form-control" id="charge-user" data-cy="user" name="user" v-model="charge.user">
<option :value="null"></option>
<option
:value="charge.user && userOption.id === charge.user.id ? charge.user : userOption"
v-for="userOption in users"
:key="userOption.id"
>
{{ userOption.login }}
</option>
</select>
</div>
</div>
<div>
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" @click="previousState()">
<font-awesome-icon icon="ban"></font-awesome-icon>&nbsp;<span>Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
:disabled="v$.$invalid || isSaving"
class="btn btn-primary"
>
<font-awesome-icon icon="save"></font-awesome-icon>&nbsp;<span>Save</span>
</button>
</div>
</form>
</div>
</div>
</template>
<script lang="ts" src="./charge-update.component.ts"></script>
@@ -0,0 +1,100 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import Charge from './charge.vue';
import ChargeService from './charge.service';
import AlertService from '@/shared/alert/alert.service';
type ChargeComponentType = InstanceType<typeof Charge>;
const bModalStub = {
render: () => {},
methods: {
hide: () => {},
show: () => {},
},
};
describe('Component Tests', () => {
let alertService: AlertService;
describe('Charge Management Component', () => {
let chargeServiceStub: SinonStubbedInstance<ChargeService>;
let mountOptions: MountingOptions<ChargeComponentType>['global'];
beforeEach(() => {
chargeServiceStub = sinon.createStubInstance<ChargeService>(ChargeService);
chargeServiceStub.retrieve.resolves({ headers: {} });
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
bModal: bModalStub as any,
'font-awesome-icon': true,
'b-badge': true,
'b-button': true,
'router-link': true,
},
directives: {
'b-modal': {},
},
provide: {
alertService,
chargeService: () => chargeServiceStub,
},
};
});
describe('Mount', () => {
it('Should call load all on init', async () => {
// GIVEN
chargeServiceStub.retrieve.resolves({ headers: {}, data: [{ id: 123 }] });
// WHEN
const wrapper = shallowMount(Charge, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(chargeServiceStub.retrieve.calledOnce).toBeTruthy();
expect(comp.charges[0]).toEqual(expect.objectContaining({ id: 123 }));
});
});
describe('Handles', () => {
let comp: ChargeComponentType;
beforeEach(async () => {
const wrapper = shallowMount(Charge, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
chargeServiceStub.retrieve.reset();
chargeServiceStub.retrieve.resolves({ headers: {}, data: [] });
});
it('Should call delete service on confirmDelete', async () => {
// GIVEN
chargeServiceStub.delete.resolves({});
// WHEN
comp.prepareRemove({ id: 123 });
comp.removeCharge();
await comp.$nextTick(); // clear components
// THEN
expect(chargeServiceStub.delete.called).toBeTruthy();
// THEN
await comp.$nextTick(); // handle component clear watch
expect(chargeServiceStub.retrieve.callCount).toEqual(1);
});
});
});
});
@@ -0,0 +1,75 @@
import { type Ref, defineComponent, inject, onMounted, ref } from 'vue';
import ChargeService from './charge.service';
import { type ICharge } from '@/shared/model/charge.model';
import { useAlertService } from '@/shared/alert/alert.service';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'Charge',
setup() {
const chargeService = inject('chargeService', () => new ChargeService());
const alertService = inject('alertService', () => useAlertService(), true);
const charges: Ref<ICharge[]> = ref([]);
const isFetching = ref(false);
const clear = () => {};
const retrieveCharges = async () => {
isFetching.value = true;
try {
const res = await chargeService().retrieve();
charges.value = res.data;
} catch (err) {
alertService.showHttpError(err.response);
} finally {
isFetching.value = false;
}
};
const handleSyncList = () => {
retrieveCharges();
};
onMounted(async () => {
await retrieveCharges();
});
const removeId: Ref<number> = ref(null);
const removeEntity = ref<any>(null);
const prepareRemove = (instance: ICharge) => {
removeId.value = instance.id;
removeEntity.value.show();
};
const closeDialog = () => {
removeEntity.value.hide();
};
const removeCharge = async () => {
try {
await chargeService().delete(removeId.value);
const message = `A Charge is deleted with identifier ${removeId.value}`;
alertService.showInfo(message, { variant: 'danger' });
removeId.value = null;
retrieveCharges();
closeDialog();
} catch (error) {
alertService.showHttpError(error.response);
}
};
return {
charges,
handleSyncList,
isFetching,
retrieveCharges,
clear,
removeId,
removeEntity,
prepareRemove,
closeDialog,
removeCharge,
};
},
});
@@ -0,0 +1,164 @@
/* tslint:disable max-line-length */
import axios from 'axios';
import sinon from 'sinon';
import dayjs from 'dayjs';
import ChargeService from './charge.service';
import { DATE_FORMAT } from '@/shared/composables/date-format';
import { Charge } from '@/shared/model/charge.model';
const error = {
response: {
status: null,
data: {
type: null,
},
},
};
const axiosStub = {
get: sinon.stub(axios, 'get'),
post: sinon.stub(axios, 'post'),
put: sinon.stub(axios, 'put'),
patch: sinon.stub(axios, 'patch'),
delete: sinon.stub(axios, 'delete'),
};
describe('Service Tests', () => {
describe('Charge Service', () => {
let service: ChargeService;
let elemDefault;
let currentDate: Date;
beforeEach(() => {
service = new ChargeService();
currentDate = new Date();
elemDefault = new Charge(123, currentDate, 'CHARGE', 0);
});
describe('Service methods', () => {
it('should find an element', async () => {
const returnedFromService = { chargeDate: dayjs(currentDate).format(DATE_FORMAT), ...elemDefault };
axiosStub.get.resolves({ data: returnedFromService });
return service.find(123).then(res => {
expect(res).toMatchObject(elemDefault);
});
});
it('should not find an element', async () => {
axiosStub.get.rejects(error);
return service
.find(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should create a Charge', async () => {
const returnedFromService = { id: 123, chargeDate: dayjs(currentDate).format(DATE_FORMAT), ...elemDefault };
const expected = { chargeDate: currentDate, ...returnedFromService };
axiosStub.post.resolves({ data: returnedFromService });
return service.create({}).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not create a Charge', async () => {
axiosStub.post.rejects(error);
return service
.create({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should update a Charge', async () => {
const returnedFromService = { chargeDate: dayjs(currentDate).format(DATE_FORMAT), type: 'BBBBBB', amount: 1, ...elemDefault };
const expected = { chargeDate: currentDate, ...returnedFromService };
axiosStub.put.resolves({ data: returnedFromService });
return service.update(expected).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not update a Charge', async () => {
axiosStub.put.rejects(error);
return service
.update({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should partial update a Charge', async () => {
const patchObject = { chargeDate: dayjs(currentDate).format(DATE_FORMAT), type: 'BBBBBB', ...new Charge() };
const returnedFromService = Object.assign(patchObject, elemDefault);
const expected = { chargeDate: currentDate, ...returnedFromService };
axiosStub.patch.resolves({ data: returnedFromService });
return service.partialUpdate(patchObject).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not partial update a Charge', async () => {
axiosStub.patch.rejects(error);
return service
.partialUpdate({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should return a list of Charge', async () => {
const returnedFromService = { chargeDate: dayjs(currentDate).format(DATE_FORMAT), type: 'BBBBBB', amount: 1, ...elemDefault };
const expected = { chargeDate: currentDate, ...returnedFromService };
axiosStub.get.resolves([returnedFromService]);
return service.retrieve().then(res => {
expect(res).toContainEqual(expected);
});
});
it('should not return a list of Charge', async () => {
axiosStub.get.rejects(error);
return service
.retrieve()
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should delete a Charge', async () => {
axiosStub.delete.resolves({ ok: true });
return service.delete(123).then(res => {
expect(res.ok).toBeTruthy();
});
});
it('should not delete a Charge', async () => {
axiosStub.delete.rejects(error);
return service
.delete(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
});
});
});
@@ -0,0 +1,85 @@
import axios from 'axios';
import { type ICharge } from '@/shared/model/charge.model';
const baseApiUrl = 'api/charges';
export default class ChargeService {
public find(id: number): Promise<ICharge> {
return new Promise<ICharge>((resolve, reject) => {
axios
.get(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public retrieve(): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.get(baseApiUrl)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
public delete(id: number): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.delete(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
public create(entity: ICharge): Promise<ICharge> {
return new Promise<ICharge>((resolve, reject) => {
axios
.post(`${baseApiUrl}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public update(entity: ICharge): Promise<ICharge> {
return new Promise<ICharge>((resolve, reject) => {
axios
.put(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public partialUpdate(entity: ICharge): Promise<ICharge> {
return new Promise<ICharge>((resolve, reject) => {
axios
.patch(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
}
@@ -0,0 +1,118 @@
<template>
<div>
<h2 id="page-heading" data-cy="ChargeHeading">
<span id="charge-heading">Charges</span>
<div class="d-flex justify-content-end">
<button class="btn btn-info mr-2" @click="handleSyncList" :disabled="isFetching">
<font-awesome-icon icon="sync" :spin="isFetching"></font-awesome-icon> <span>Refresh list</span>
</button>
<router-link :to="{ name: 'ChargeCreate' }" custom v-slot="{ navigate }">
<button
@click="navigate"
id="jh-create-entity"
data-cy="entityCreateButton"
class="btn btn-primary jh-create-entity create-charge"
>
<font-awesome-icon icon="plus"></font-awesome-icon>
<span>Create a new Charge</span>
</button>
</router-link>
</div>
</h2>
<br />
<div class="alert alert-warning" v-if="!isFetching && charges && charges.length === 0">
<span>No Charges found</span>
</div>
<div class="table-responsive" v-if="charges && charges.length > 0">
<table class="table table-striped" aria-describedby="charges">
<thead>
<tr>
<th scope="row"><span>ID</span></th>
<th scope="row"><span>Charge Date</span></th>
<th scope="row"><span>Type</span></th>
<th scope="row"><span>Amount</span></th>
<th scope="row"><span>Event</span></th>
<th scope="row"><span>Registration</span></th>
<th scope="row"><span>User</span></th>
<th scope="row"></th>
</tr>
</thead>
<tbody>
<tr v-for="charge in charges" :key="charge.id" data-cy="entityTable">
<td>
<router-link :to="{ name: 'ChargeView', params: { chargeId: charge.id } }">{{ charge.id }}</router-link>
</td>
<td>{{ charge.chargeDate }}</td>
<td>{{ charge.type }}</td>
<td>{{ charge.amount }}</td>
<td>
<div v-if="charge.event">
<router-link :to="{ name: 'EventView', params: { eventId: charge.event.id } }">{{ charge.event.id }}</router-link>
</div>
</td>
<td>
<div v-if="charge.registration">
<router-link :to="{ name: 'RegistrationView', params: { registrationId: charge.registration.id } }">{{
charge.registration.id
}}</router-link>
</div>
</td>
<td>
{{ charge.user ? charge.user.login : '' }}
</td>
<td class="text-right">
<div class="btn-group">
<router-link :to="{ name: 'ChargeView', params: { chargeId: charge.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-info btn-sm details" data-cy="entityDetailsButton">
<font-awesome-icon icon="eye"></font-awesome-icon>
<span class="d-none d-md-inline">View</span>
</button>
</router-link>
<router-link :to="{ name: 'ChargeEdit', params: { chargeId: charge.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-primary btn-sm edit" data-cy="entityEditButton">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>
<span class="d-none d-md-inline">Edit</span>
</button>
</router-link>
<b-button
@click="prepareRemove(charge)"
variant="danger"
class="btn btn-sm"
data-cy="entityDeleteButton"
v-b-modal.removeEntity
>
<font-awesome-icon icon="times"></font-awesome-icon>
<span class="d-none d-md-inline">Delete</span>
</b-button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<b-modal ref="removeEntity" id="removeEntity">
<template #modal-title>
<span id="sasiedziApp.charge.delete.question" data-cy="chargeDeleteDialogHeading">Confirm delete operation</span>
</template>
<div class="modal-body">
<p id="jhi-delete-charge-heading">Are you sure you want to delete Charge {{ removeId }}?</p>
</div>
<template #modal-footer>
<div>
<button type="button" class="btn btn-secondary" @click="closeDialog()">Cancel</button>
<button
type="button"
class="btn btn-primary"
id="jhi-confirm-delete-charge"
data-cy="entityConfirmDeleteButton"
@click="removeCharge()"
>
Delete
</button>
</div>
</template>
</b-modal>
</div>
</template>
<script lang="ts" src="./charge.component.ts"></script>
@@ -1,5 +1,17 @@
<template>
<div>
<b-dropdown-item to="/charge">
<font-awesome-icon icon="asterisk" />
<span>Charge</span>
</b-dropdown-item>
<b-dropdown-item to="/event">
<font-awesome-icon icon="asterisk" />
<span>Event</span>
</b-dropdown-item>
<b-dropdown-item to="/registration">
<font-awesome-icon icon="asterisk" />
<span>Registration</span>
</b-dropdown-item>
<!-- jhipster-needle-add-entity-to-menu - JHipster will add entities to the menu here -->
</div>
</template>
@@ -1,5 +1,8 @@
import { defineComponent, provide } from 'vue';
import ChargeService from './charge/charge.service';
import EventService from './event/event.service';
import RegistrationService from './registration/registration.service';
import UserService from '@/entities/user/user.service';
// jhipster-needle-add-entity-service-to-entities-component-import - JHipster will import entities services here
@@ -8,6 +11,9 @@ export default defineComponent({
name: 'Entities',
setup() {
provide('userService', () => new UserService());
provide('chargeService', () => new ChargeService());
provide('eventService', () => new EventService());
provide('registrationService', () => new RegistrationService());
// jhipster-needle-add-entity-service-to-entities-component - JHipster will import entities services here
},
});
@@ -0,0 +1,89 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import { type RouteLocation } from 'vue-router';
import EventDetails from './event-details.vue';
import EventService from './event.service';
import AlertService from '@/shared/alert/alert.service';
type EventDetailsComponentType = InstanceType<typeof EventDetails>;
let route: Partial<RouteLocation>;
const routerGoMock = vitest.fn();
vitest.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const eventSample = { id: 123 };
describe('Component Tests', () => {
let alertService: AlertService;
afterEach(() => {
vitest.resetAllMocks();
});
describe('Event Management Detail Component', () => {
let eventServiceStub: SinonStubbedInstance<EventService>;
let mountOptions: MountingOptions<EventDetailsComponentType>['global'];
beforeEach(() => {
route = {};
eventServiceStub = sinon.createStubInstance<EventService>(EventService);
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'router-link': true,
},
provide: {
alertService,
eventService: () => eventServiceStub,
},
};
});
describe('Navigate to details', () => {
it('Should call load all on init', async () => {
// GIVEN
eventServiceStub.find.resolves(eventSample);
route = {
params: {
eventId: `${123}`,
},
};
const wrapper = shallowMount(EventDetails, { global: mountOptions });
const comp = wrapper.vm;
// WHEN
await comp.$nextTick();
// THEN
expect(comp.event).toMatchObject(eventSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
eventServiceStub.find.resolves(eventSample);
const wrapper = shallowMount(EventDetails, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,46 @@
import { type Ref, defineComponent, inject, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import EventService from './event.service';
import useDataUtils from '@/shared/data/data-utils.service';
import { type IEvent } from '@/shared/model/event.model';
import { useAlertService } from '@/shared/alert/alert.service';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'EventDetails',
setup() {
const eventService = inject('eventService', () => new EventService());
const alertService = inject('alertService', () => useAlertService(), true);
const dataUtils = useDataUtils();
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const event: Ref<IEvent> = ref({});
const retrieveEvent = async eventId => {
try {
const res = await eventService().find(eventId);
event.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.eventId) {
retrieveEvent(route.params.eventId);
}
return {
alertService,
event,
...dataUtils,
previousState,
};
},
});
@@ -0,0 +1,51 @@
<template>
<div class="row justify-content-center">
<div class="col-8">
<div v-if="event">
<h2 class="jh-entity-heading" data-cy="eventDetailsHeading"><span>Event</span> {{ event.id }}</h2>
<dl class="row jh-entity-details">
<dt>
<span>Name</span>
</dt>
<dd>
<span>{{ event.name }}</span>
</dd>
<dt>
<span>Date</span>
</dt>
<dd>
<span>{{ event.date }}</span>
</dd>
<dt>
<span>Players Limit</span>
</dt>
<dd>
<span>{{ event.playersLimit }}</span>
</dd>
<dt>
<span>Cost</span>
</dt>
<dd>
<span>{{ event.cost }}</span>
</dd>
<dt>
<span>Comment</span>
</dt>
<dd>
<span>{{ event.comment }}</span>
</dd>
</dl>
<button type="submit" @click.prevent="previousState()" class="btn btn-info" data-cy="entityDetailsBackButton">
<font-awesome-icon icon="arrow-left"></font-awesome-icon>&nbsp;<span>Back</span>
</button>
<router-link v-if="event.id" :to="{ name: 'EventEdit', params: { eventId: event.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-primary">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>&nbsp;<span>Edit</span>
</button>
</router-link>
</div>
</div>
</div>
</template>
<script lang="ts" src="./event-details.component.ts"></script>
@@ -0,0 +1,131 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import { type RouteLocation } from 'vue-router';
import EventUpdate from './event-update.vue';
import EventService from './event.service';
import AlertService from '@/shared/alert/alert.service';
type EventUpdateComponentType = InstanceType<typeof EventUpdate>;
let route: Partial<RouteLocation>;
const routerGoMock = vitest.fn();
vitest.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const eventSample = { id: 123 };
describe('Component Tests', () => {
let mountOptions: MountingOptions<EventUpdateComponentType>['global'];
let alertService: AlertService;
describe('Event Management Update Component', () => {
let comp: EventUpdateComponentType;
let eventServiceStub: SinonStubbedInstance<EventService>;
beforeEach(() => {
route = {};
eventServiceStub = sinon.createStubInstance<EventService>(EventService);
eventServiceStub.retrieve.onFirstCall().resolves(Promise.resolve([]));
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'b-input-group': true,
'b-input-group-prepend': true,
'b-form-datepicker': true,
'b-form-input': true,
},
provide: {
alertService,
eventService: () => eventServiceStub,
},
};
});
afterEach(() => {
vitest.resetAllMocks();
});
describe('save', () => {
it('Should call update service on save for existing entity', async () => {
// GIVEN
const wrapper = shallowMount(EventUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.event = eventSample;
eventServiceStub.update.resolves(eventSample);
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(eventServiceStub.update.calledWith(eventSample)).toBeTruthy();
expect(comp.isSaving).toEqual(false);
});
it('Should call create service on save for new entity', async () => {
// GIVEN
const entity = {};
eventServiceStub.create.resolves(entity);
const wrapper = shallowMount(EventUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.event = entity;
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(eventServiceStub.create.calledWith(entity)).toBeTruthy();
expect(comp.isSaving).toEqual(false);
});
});
describe('Before route enter', () => {
it('Should retrieve data', async () => {
// GIVEN
eventServiceStub.find.resolves(eventSample);
eventServiceStub.retrieve.resolves([eventSample]);
// WHEN
route = {
params: {
eventId: `${eventSample.id}`,
},
};
const wrapper = shallowMount(EventUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(comp.event).toMatchObject(eventSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
eventServiceStub.find.resolves(eventSample);
const wrapper = shallowMount(EventUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,100 @@
import { type Ref, computed, defineComponent, inject, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useVuelidate } from '@vuelidate/core';
import EventService from './event.service';
import useDataUtils from '@/shared/data/data-utils.service';
import { useValidation } from '@/shared/composables';
import { useAlertService } from '@/shared/alert/alert.service';
import { Event, type IEvent } from '@/shared/model/event.model';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'EventUpdate',
setup() {
const eventService = inject('eventService', () => new EventService());
const alertService = inject('alertService', () => useAlertService(), true);
const event: Ref<IEvent> = ref(new Event());
const isSaving = ref(false);
const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'en'), true);
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const retrieveEvent = async eventId => {
try {
const res = await eventService().find(eventId);
event.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.eventId) {
retrieveEvent(route.params.eventId);
}
const dataUtils = useDataUtils();
const validations = useValidation();
const validationRules = {
name: {
required: validations.required('This field is required.'),
},
date: {
required: validations.required('This field is required.'),
},
playersLimit: {},
cost: {},
comment: {},
};
const v$ = useVuelidate(validationRules, event as any);
v$.value.$validate();
return {
eventService,
alertService,
event,
previousState,
isSaving,
currentLanguage,
...dataUtils,
v$,
};
},
created(): void {},
methods: {
save(): void {
this.isSaving = true;
if (this.event.id) {
this.eventService()
.update(this.event)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showInfo(`A Event is updated with identifier ${param.id}`);
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
} else {
this.eventService()
.create(this.event)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showSuccess(`A Event is created with identifier ${param.id}`);
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
}
},
},
});
@@ -0,0 +1,113 @@
<template>
<div class="row justify-content-center">
<div class="col-8">
<form name="editForm" novalidate @submit.prevent="save()">
<h2 id="sasiedziApp.event.home.createOrEditLabel" data-cy="EventCreateUpdateHeading">Create or edit a Event</h2>
<div>
<div class="form-group" v-if="event.id">
<label for="id">ID</label>
<input type="text" class="form-control" id="id" name="id" v-model="event.id" readonly />
</div>
<div class="form-group">
<label class="form-control-label" for="event-name">Name</label>
<input
type="text"
class="form-control"
name="name"
id="event-name"
data-cy="name"
:class="{ valid: !v$.name.$invalid, invalid: v$.name.$invalid }"
v-model="v$.name.$model"
required
/>
<div v-if="v$.name.$anyDirty && v$.name.$invalid">
<small class="form-text text-danger" v-for="error of v$.name.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="event-date">Date</label>
<b-input-group class="mb-3">
<b-input-group-prepend>
<b-form-datepicker
aria-controls="event-date"
v-model="v$.date.$model"
name="date"
class="form-control"
:locale="currentLanguage"
button-only
today-button
reset-button
close-button
>
</b-form-datepicker>
</b-input-group-prepend>
<b-form-input
id="event-date"
data-cy="date"
type="text"
class="form-control"
name="date"
:class="{ valid: !v$.date.$invalid, invalid: v$.date.$invalid }"
v-model="v$.date.$model"
required
/>
</b-input-group>
<div v-if="v$.date.$anyDirty && v$.date.$invalid">
<small class="form-text text-danger" v-for="error of v$.date.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="event-playersLimit">Players Limit</label>
<input
type="number"
class="form-control"
name="playersLimit"
id="event-playersLimit"
data-cy="playersLimit"
:class="{ valid: !v$.playersLimit.$invalid, invalid: v$.playersLimit.$invalid }"
v-model.number="v$.playersLimit.$model"
/>
</div>
<div class="form-group">
<label class="form-control-label" for="event-cost">Cost</label>
<input
type="number"
class="form-control"
name="cost"
id="event-cost"
data-cy="cost"
:class="{ valid: !v$.cost.$invalid, invalid: v$.cost.$invalid }"
v-model.number="v$.cost.$model"
/>
</div>
<div class="form-group">
<label class="form-control-label" for="event-comment">Comment</label>
<textarea
class="form-control"
name="comment"
id="event-comment"
data-cy="comment"
:class="{ valid: !v$.comment.$invalid, invalid: v$.comment.$invalid }"
v-model="v$.comment.$model"
></textarea>
</div>
</div>
<div>
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" @click="previousState()">
<font-awesome-icon icon="ban"></font-awesome-icon>&nbsp;<span>Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
:disabled="v$.$invalid || isSaving"
class="btn btn-primary"
>
<font-awesome-icon icon="save"></font-awesome-icon>&nbsp;<span>Save</span>
</button>
</div>
</form>
</div>
</div>
</template>
<script lang="ts" src="./event-update.component.ts"></script>
@@ -0,0 +1,100 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import Event from './event.vue';
import EventService from './event.service';
import AlertService from '@/shared/alert/alert.service';
type EventComponentType = InstanceType<typeof Event>;
const bModalStub = {
render: () => {},
methods: {
hide: () => {},
show: () => {},
},
};
describe('Component Tests', () => {
let alertService: AlertService;
describe('Event Management Component', () => {
let eventServiceStub: SinonStubbedInstance<EventService>;
let mountOptions: MountingOptions<EventComponentType>['global'];
beforeEach(() => {
eventServiceStub = sinon.createStubInstance<EventService>(EventService);
eventServiceStub.retrieve.resolves({ headers: {} });
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
bModal: bModalStub as any,
'font-awesome-icon': true,
'b-badge': true,
'b-button': true,
'router-link': true,
},
directives: {
'b-modal': {},
},
provide: {
alertService,
eventService: () => eventServiceStub,
},
};
});
describe('Mount', () => {
it('Should call load all on init', async () => {
// GIVEN
eventServiceStub.retrieve.resolves({ headers: {}, data: [{ id: 123 }] });
// WHEN
const wrapper = shallowMount(Event, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(eventServiceStub.retrieve.calledOnce).toBeTruthy();
expect(comp.events[0]).toEqual(expect.objectContaining({ id: 123 }));
});
});
describe('Handles', () => {
let comp: EventComponentType;
beforeEach(async () => {
const wrapper = shallowMount(Event, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
eventServiceStub.retrieve.reset();
eventServiceStub.retrieve.resolves({ headers: {}, data: [] });
});
it('Should call delete service on confirmDelete', async () => {
// GIVEN
eventServiceStub.delete.resolves({});
// WHEN
comp.prepareRemove({ id: 123 });
comp.removeEvent();
await comp.$nextTick(); // clear components
// THEN
expect(eventServiceStub.delete.called).toBeTruthy();
// THEN
await comp.$nextTick(); // handle component clear watch
expect(eventServiceStub.retrieve.callCount).toEqual(1);
});
});
});
});
@@ -0,0 +1,78 @@
import { type Ref, defineComponent, inject, onMounted, ref } from 'vue';
import EventService from './event.service';
import { type IEvent } from '@/shared/model/event.model';
import useDataUtils from '@/shared/data/data-utils.service';
import { useAlertService } from '@/shared/alert/alert.service';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'Event',
setup() {
const dataUtils = useDataUtils();
const eventService = inject('eventService', () => new EventService());
const alertService = inject('alertService', () => useAlertService(), true);
const events: Ref<IEvent[]> = ref([]);
const isFetching = ref(false);
const clear = () => {};
const retrieveEvents = async () => {
isFetching.value = true;
try {
const res = await eventService().retrieve();
events.value = res.data;
} catch (err) {
alertService.showHttpError(err.response);
} finally {
isFetching.value = false;
}
};
const handleSyncList = () => {
retrieveEvents();
};
onMounted(async () => {
await retrieveEvents();
});
const removeId: Ref<number> = ref(null);
const removeEntity = ref<any>(null);
const prepareRemove = (instance: IEvent) => {
removeId.value = instance.id;
removeEntity.value.show();
};
const closeDialog = () => {
removeEntity.value.hide();
};
const removeEvent = async () => {
try {
await eventService().delete(removeId.value);
const message = `A Event is deleted with identifier ${removeId.value}`;
alertService.showInfo(message, { variant: 'danger' });
removeId.value = null;
retrieveEvents();
closeDialog();
} catch (error) {
alertService.showHttpError(error.response);
}
};
return {
events,
handleSyncList,
isFetching,
retrieveEvents,
clear,
removeId,
removeEntity,
prepareRemove,
closeDialog,
removeEvent,
...dataUtils,
};
},
});
@@ -0,0 +1,178 @@
/* tslint:disable max-line-length */
import axios from 'axios';
import sinon from 'sinon';
import dayjs from 'dayjs';
import EventService from './event.service';
import { DATE_FORMAT } from '@/shared/composables/date-format';
import { Event } from '@/shared/model/event.model';
const error = {
response: {
status: null,
data: {
type: null,
},
},
};
const axiosStub = {
get: sinon.stub(axios, 'get'),
post: sinon.stub(axios, 'post'),
put: sinon.stub(axios, 'put'),
patch: sinon.stub(axios, 'patch'),
delete: sinon.stub(axios, 'delete'),
};
describe('Service Tests', () => {
describe('Event Service', () => {
let service: EventService;
let elemDefault;
let currentDate: Date;
beforeEach(() => {
service = new EventService();
currentDate = new Date();
elemDefault = new Event(123, 'AAAAAAA', currentDate, 0, 0, 'AAAAAAA');
});
describe('Service methods', () => {
it('should find an element', async () => {
const returnedFromService = { date: dayjs(currentDate).format(DATE_FORMAT), ...elemDefault };
axiosStub.get.resolves({ data: returnedFromService });
return service.find(123).then(res => {
expect(res).toMatchObject(elemDefault);
});
});
it('should not find an element', async () => {
axiosStub.get.rejects(error);
return service
.find(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should create a Event', async () => {
const returnedFromService = { id: 123, date: dayjs(currentDate).format(DATE_FORMAT), ...elemDefault };
const expected = { date: currentDate, ...returnedFromService };
axiosStub.post.resolves({ data: returnedFromService });
return service.create({}).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not create a Event', async () => {
axiosStub.post.rejects(error);
return service
.create({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should update a Event', async () => {
const returnedFromService = {
name: 'BBBBBB',
date: dayjs(currentDate).format(DATE_FORMAT),
playersLimit: 1,
cost: 1,
comment: 'BBBBBB',
...elemDefault,
};
const expected = { date: currentDate, ...returnedFromService };
axiosStub.put.resolves({ data: returnedFromService });
return service.update(expected).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not update a Event', async () => {
axiosStub.put.rejects(error);
return service
.update({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should partial update a Event', async () => {
const patchObject = { name: 'BBBBBB', date: dayjs(currentDate).format(DATE_FORMAT), cost: 1, ...new Event() };
const returnedFromService = Object.assign(patchObject, elemDefault);
const expected = { date: currentDate, ...returnedFromService };
axiosStub.patch.resolves({ data: returnedFromService });
return service.partialUpdate(patchObject).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not partial update a Event', async () => {
axiosStub.patch.rejects(error);
return service
.partialUpdate({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should return a list of Event', async () => {
const returnedFromService = {
name: 'BBBBBB',
date: dayjs(currentDate).format(DATE_FORMAT),
playersLimit: 1,
cost: 1,
comment: 'BBBBBB',
...elemDefault,
};
const expected = { date: currentDate, ...returnedFromService };
axiosStub.get.resolves([returnedFromService]);
return service.retrieve().then(res => {
expect(res).toContainEqual(expected);
});
});
it('should not return a list of Event', async () => {
axiosStub.get.rejects(error);
return service
.retrieve()
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should delete a Event', async () => {
axiosStub.delete.resolves({ ok: true });
return service.delete(123).then(res => {
expect(res.ok).toBeTruthy();
});
});
it('should not delete a Event', async () => {
axiosStub.delete.rejects(error);
return service
.delete(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
});
});
});
@@ -0,0 +1,85 @@
import axios from 'axios';
import { type IEvent } from '@/shared/model/event.model';
const baseApiUrl = 'api/events';
export default class EventService {
public find(id: number): Promise<IEvent> {
return new Promise<IEvent>((resolve, reject) => {
axios
.get(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public retrieve(): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.get(baseApiUrl)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
public delete(id: number): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.delete(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
public create(entity: IEvent): Promise<IEvent> {
return new Promise<IEvent>((resolve, reject) => {
axios
.post(`${baseApiUrl}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public update(entity: IEvent): Promise<IEvent> {
return new Promise<IEvent>((resolve, reject) => {
axios
.put(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public partialUpdate(entity: IEvent): Promise<IEvent> {
return new Promise<IEvent>((resolve, reject) => {
axios
.patch(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
}
@@ -0,0 +1,104 @@
<template>
<div>
<h2 id="page-heading" data-cy="EventHeading">
<span id="event-heading">Events</span>
<div class="d-flex justify-content-end">
<button class="btn btn-info mr-2" @click="handleSyncList" :disabled="isFetching">
<font-awesome-icon icon="sync" :spin="isFetching"></font-awesome-icon> <span>Refresh list</span>
</button>
<router-link :to="{ name: 'EventCreate' }" custom v-slot="{ navigate }">
<button
@click="navigate"
id="jh-create-entity"
data-cy="entityCreateButton"
class="btn btn-primary jh-create-entity create-event"
>
<font-awesome-icon icon="plus"></font-awesome-icon>
<span>Create a new Event</span>
</button>
</router-link>
</div>
</h2>
<br />
<div class="alert alert-warning" v-if="!isFetching && events && events.length === 0">
<span>No Events found</span>
</div>
<div class="table-responsive" v-if="events && events.length > 0">
<table class="table table-striped" aria-describedby="events">
<thead>
<tr>
<th scope="row"><span>ID</span></th>
<th scope="row"><span>Name</span></th>
<th scope="row"><span>Date</span></th>
<th scope="row"><span>Players Limit</span></th>
<th scope="row"><span>Cost</span></th>
<th scope="row"><span>Comment</span></th>
<th scope="row"></th>
</tr>
</thead>
<tbody>
<tr v-for="event in events" :key="event.id" data-cy="entityTable">
<td>
<router-link :to="{ name: 'EventView', params: { eventId: event.id } }">{{ event.id }}</router-link>
</td>
<td>{{ event.name }}</td>
<td>{{ event.date }}</td>
<td>{{ event.playersLimit }}</td>
<td>{{ event.cost }}</td>
<td>{{ event.comment }}</td>
<td class="text-right">
<div class="btn-group">
<router-link :to="{ name: 'EventView', params: { eventId: event.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-info btn-sm details" data-cy="entityDetailsButton">
<font-awesome-icon icon="eye"></font-awesome-icon>
<span class="d-none d-md-inline">View</span>
</button>
</router-link>
<router-link :to="{ name: 'EventEdit', params: { eventId: event.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-primary btn-sm edit" data-cy="entityEditButton">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>
<span class="d-none d-md-inline">Edit</span>
</button>
</router-link>
<b-button
@click="prepareRemove(event)"
variant="danger"
class="btn btn-sm"
data-cy="entityDeleteButton"
v-b-modal.removeEntity
>
<font-awesome-icon icon="times"></font-awesome-icon>
<span class="d-none d-md-inline">Delete</span>
</b-button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<b-modal ref="removeEntity" id="removeEntity">
<template #modal-title>
<span id="sasiedziApp.event.delete.question" data-cy="eventDeleteDialogHeading">Confirm delete operation</span>
</template>
<div class="modal-body">
<p id="jhi-delete-event-heading">Are you sure you want to delete Event {{ removeId }}?</p>
</div>
<template #modal-footer>
<div>
<button type="button" class="btn btn-secondary" @click="closeDialog()">Cancel</button>
<button
type="button"
class="btn btn-primary"
id="jhi-confirm-delete-event"
data-cy="entityConfirmDeleteButton"
@click="removeEvent()"
>
Delete
</button>
</div>
</template>
</b-modal>
</div>
</template>
<script lang="ts" src="./event.component.ts"></script>
@@ -0,0 +1,89 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import { type RouteLocation } from 'vue-router';
import RegistrationDetails from './registration-details.vue';
import RegistrationService from './registration.service';
import AlertService from '@/shared/alert/alert.service';
type RegistrationDetailsComponentType = InstanceType<typeof RegistrationDetails>;
let route: Partial<RouteLocation>;
const routerGoMock = vitest.fn();
vitest.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const registrationSample = { id: 123 };
describe('Component Tests', () => {
let alertService: AlertService;
afterEach(() => {
vitest.resetAllMocks();
});
describe('Registration Management Detail Component', () => {
let registrationServiceStub: SinonStubbedInstance<RegistrationService>;
let mountOptions: MountingOptions<RegistrationDetailsComponentType>['global'];
beforeEach(() => {
route = {};
registrationServiceStub = sinon.createStubInstance<RegistrationService>(RegistrationService);
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'router-link': true,
},
provide: {
alertService,
registrationService: () => registrationServiceStub,
},
};
});
describe('Navigate to details', () => {
it('Should call load all on init', async () => {
// GIVEN
registrationServiceStub.find.resolves(registrationSample);
route = {
params: {
registrationId: `${123}`,
},
};
const wrapper = shallowMount(RegistrationDetails, { global: mountOptions });
const comp = wrapper.vm;
// WHEN
await comp.$nextTick();
// THEN
expect(comp.registration).toMatchObject(registrationSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
registrationServiceStub.find.resolves(registrationSample);
const wrapper = shallowMount(RegistrationDetails, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,49 @@
import { type Ref, defineComponent, inject, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import RegistrationService from './registration.service';
import useDataUtils from '@/shared/data/data-utils.service';
import { useDateFormat } from '@/shared/composables';
import { type IRegistration } from '@/shared/model/registration.model';
import { useAlertService } from '@/shared/alert/alert.service';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'RegistrationDetails',
setup() {
const dateFormat = useDateFormat();
const registrationService = inject('registrationService', () => new RegistrationService());
const alertService = inject('alertService', () => useAlertService(), true);
const dataUtils = useDataUtils();
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const registration: Ref<IRegistration> = ref({});
const retrieveRegistration = async registrationId => {
try {
const res = await registrationService().find(registrationId);
registration.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.registrationId) {
retrieveRegistration(route.params.registrationId);
}
return {
...dateFormat,
alertService,
registration,
...dataUtils,
previousState,
};
},
});
@@ -0,0 +1,66 @@
<template>
<div class="row justify-content-center">
<div class="col-8">
<div v-if="registration">
<h2 class="jh-entity-heading" data-cy="registrationDetailsHeading"><span>Registration</span> {{ registration.id }}</h2>
<dl class="row jh-entity-details">
<dt>
<span>Date Time</span>
</dt>
<dd>
<span v-if="registration.dateTime">{{ formatDateLong(registration.dateTime) }}</span>
</dd>
<dt>
<span>Active</span>
</dt>
<dd>
<span>{{ registration.active }}</span>
</dd>
<dt>
<span>Player Name</span>
</dt>
<dd>
<span>{{ registration.playerName }}</span>
</dd>
<dt>
<span>Comment</span>
</dt>
<dd>
<span>{{ registration.comment }}</span>
</dd>
<dt>
<span>User</span>
</dt>
<dd>
{{ registration.user ? registration.user.login : '' }}
</dd>
<dt>
<span>Event</span>
</dt>
<dd>
<div v-if="registration.event">
<router-link :to="{ name: 'EventView', params: { eventId: registration.event.id } }">{{
registration.event.name
}}</router-link>
</div>
</dd>
</dl>
<button type="submit" @click.prevent="previousState()" class="btn btn-info" data-cy="entityDetailsBackButton">
<font-awesome-icon icon="arrow-left"></font-awesome-icon>&nbsp;<span>Back</span>
</button>
<router-link
v-if="registration.id"
:to="{ name: 'RegistrationEdit', params: { registrationId: registration.id } }"
custom
v-slot="{ navigate }"
>
<button @click="navigate" class="btn btn-primary">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>&nbsp;<span>Edit</span>
</button>
</router-link>
</div>
</div>
</div>
</template>
<script lang="ts" src="./registration-details.component.ts"></script>
@@ -0,0 +1,166 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import { type RouteLocation } from 'vue-router';
import dayjs from 'dayjs';
import RegistrationUpdate from './registration-update.vue';
import RegistrationService from './registration.service';
import { DATE_TIME_LONG_FORMAT } from '@/shared/composables/date-format';
import AlertService from '@/shared/alert/alert.service';
import UserService from '@/entities/user/user.service';
import EventService from '@/entities/event/event.service';
type RegistrationUpdateComponentType = InstanceType<typeof RegistrationUpdate>;
let route: Partial<RouteLocation>;
const routerGoMock = vitest.fn();
vitest.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const registrationSample = { id: 123 };
describe('Component Tests', () => {
let mountOptions: MountingOptions<RegistrationUpdateComponentType>['global'];
let alertService: AlertService;
describe('Registration Management Update Component', () => {
let comp: RegistrationUpdateComponentType;
let registrationServiceStub: SinonStubbedInstance<RegistrationService>;
beforeEach(() => {
route = {};
registrationServiceStub = sinon.createStubInstance<RegistrationService>(RegistrationService);
registrationServiceStub.retrieve.onFirstCall().resolves(Promise.resolve([]));
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'b-input-group': true,
'b-input-group-prepend': true,
'b-form-datepicker': true,
'b-form-input': true,
},
provide: {
alertService,
registrationService: () => registrationServiceStub,
userService: () =>
sinon.createStubInstance<UserService>(UserService, {
retrieve: sinon.stub().resolves({}),
} as any),
eventService: () =>
sinon.createStubInstance<EventService>(EventService, {
retrieve: sinon.stub().resolves({}),
} as any),
},
};
});
afterEach(() => {
vitest.resetAllMocks();
});
describe('load', () => {
beforeEach(() => {
const wrapper = shallowMount(RegistrationUpdate, { global: mountOptions });
comp = wrapper.vm;
});
it('Should convert date from string', () => {
// GIVEN
const date = new Date('2019-10-15T11:42:02Z');
// WHEN
const convertedDate = comp.convertDateTimeFromServer(date);
// THEN
expect(convertedDate).toEqual(dayjs(date).format(DATE_TIME_LONG_FORMAT));
});
it('Should not convert date if date is not present', () => {
expect(comp.convertDateTimeFromServer(null)).toBeNull();
});
});
describe('save', () => {
it('Should call update service on save for existing entity', async () => {
// GIVEN
const wrapper = shallowMount(RegistrationUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.registration = registrationSample;
registrationServiceStub.update.resolves(registrationSample);
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(registrationServiceStub.update.calledWith(registrationSample)).toBeTruthy();
expect(comp.isSaving).toEqual(false);
});
it('Should call create service on save for new entity', async () => {
// GIVEN
const entity = {};
registrationServiceStub.create.resolves(entity);
const wrapper = shallowMount(RegistrationUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.registration = entity;
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(registrationServiceStub.create.calledWith(entity)).toBeTruthy();
expect(comp.isSaving).toEqual(false);
});
});
describe('Before route enter', () => {
it('Should retrieve data', async () => {
// GIVEN
registrationServiceStub.find.resolves(registrationSample);
registrationServiceStub.retrieve.resolves([registrationSample]);
// WHEN
route = {
params: {
registrationId: `${registrationSample.id}`,
},
};
const wrapper = shallowMount(RegistrationUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(comp.registration).toMatchObject(registrationSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
registrationServiceStub.find.resolves(registrationSample);
const wrapper = shallowMount(RegistrationUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,129 @@
import { type Ref, computed, defineComponent, inject, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useVuelidate } from '@vuelidate/core';
import RegistrationService from './registration.service';
import useDataUtils from '@/shared/data/data-utils.service';
import { useDateFormat, useValidation } from '@/shared/composables';
import { useAlertService } from '@/shared/alert/alert.service';
import UserService from '@/entities/user/user.service';
import EventService from '@/entities/event/event.service';
import { type IEvent } from '@/shared/model/event.model';
import { type IRegistration, Registration } from '@/shared/model/registration.model';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'RegistrationUpdate',
setup() {
const registrationService = inject('registrationService', () => new RegistrationService());
const alertService = inject('alertService', () => useAlertService(), true);
const registration: Ref<IRegistration> = ref(new Registration());
const userService = inject('userService', () => new UserService());
const users: Ref<Array<any>> = ref([]);
const eventService = inject('eventService', () => new EventService());
const events: Ref<IEvent[]> = ref([]);
const isSaving = ref(false);
const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'en'), true);
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const retrieveRegistration = async registrationId => {
try {
const res = await registrationService().find(registrationId);
res.dateTime = new Date(res.dateTime);
registration.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.registrationId) {
retrieveRegistration(route.params.registrationId);
}
const initRelationships = () => {
userService()
.retrieve()
.then(res => {
users.value = res.data;
});
eventService()
.retrieve()
.then(res => {
events.value = res.data;
});
};
initRelationships();
const dataUtils = useDataUtils();
const validations = useValidation();
const validationRules = {
dateTime: {
required: validations.required('This field is required.'),
},
active: {
required: validations.required('This field is required.'),
},
playerName: {},
comment: {},
user: {},
event: {},
};
const v$ = useVuelidate(validationRules, registration as any);
v$.value.$validate();
return {
registrationService,
alertService,
registration,
previousState,
isSaving,
currentLanguage,
users,
events,
...dataUtils,
v$,
...useDateFormat({ entityRef: registration }),
};
},
created(): void {},
methods: {
save(): void {
this.isSaving = true;
if (this.registration.id) {
this.registrationService()
.update(this.registration)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showInfo(`A Registration is updated with identifier ${param.id}`);
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
} else {
this.registrationService()
.create(this.registration)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showSuccess(`A Registration is created with identifier ${param.id}`);
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
}
},
},
});
@@ -0,0 +1,116 @@
<template>
<div class="row justify-content-center">
<div class="col-8">
<form name="editForm" novalidate @submit.prevent="save()">
<h2 id="sasiedziApp.registration.home.createOrEditLabel" data-cy="RegistrationCreateUpdateHeading">
Create or edit a Registration
</h2>
<div>
<div class="form-group" v-if="registration.id">
<label for="id">ID</label>
<input type="text" class="form-control" id="id" name="id" v-model="registration.id" readonly />
</div>
<div class="form-group">
<label class="form-control-label" for="registration-dateTime">Date Time</label>
<div class="d-flex">
<input
id="registration-dateTime"
data-cy="dateTime"
type="datetime-local"
class="form-control"
name="dateTime"
:class="{ valid: !v$.dateTime.$invalid, invalid: v$.dateTime.$invalid }"
required
:value="convertDateTimeFromServer(v$.dateTime.$model)"
@change="updateZonedDateTimeField('dateTime', $event)"
/>
</div>
<div v-if="v$.dateTime.$anyDirty && v$.dateTime.$invalid">
<small class="form-text text-danger" v-for="error of v$.dateTime.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="registration-active">Active</label>
<input
type="checkbox"
class="form-check"
name="active"
id="registration-active"
data-cy="active"
:class="{ valid: !v$.active.$invalid, invalid: v$.active.$invalid }"
v-model="v$.active.$model"
required
/>
<div v-if="v$.active.$anyDirty && v$.active.$invalid">
<small class="form-text text-danger" v-for="error of v$.active.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" for="registration-playerName">Player Name</label>
<input
type="text"
class="form-control"
name="playerName"
id="registration-playerName"
data-cy="playerName"
:class="{ valid: !v$.playerName.$invalid, invalid: v$.playerName.$invalid }"
v-model="v$.playerName.$model"
/>
</div>
<div class="form-group">
<label class="form-control-label" for="registration-comment">Comment</label>
<textarea
class="form-control"
name="comment"
id="registration-comment"
data-cy="comment"
:class="{ valid: !v$.comment.$invalid, invalid: v$.comment.$invalid }"
v-model="v$.comment.$model"
></textarea>
</div>
<div class="form-group">
<label class="form-control-label" for="registration-user">User</label>
<select class="form-control" id="registration-user" data-cy="user" name="user" v-model="registration.user">
<option :value="null"></option>
<option
:value="registration.user && userOption.id === registration.user.id ? registration.user : userOption"
v-for="userOption in users"
:key="userOption.id"
>
{{ userOption.login }}
</option>
</select>
</div>
<div class="form-group">
<label class="form-control-label" for="registration-event">Event</label>
<select class="form-control" id="registration-event" data-cy="event" name="event" v-model="registration.event">
<option :value="null"></option>
<option
:value="registration.event && eventOption.id === registration.event.id ? registration.event : eventOption"
v-for="eventOption in events"
:key="eventOption.id"
>
{{ eventOption.name }}
</option>
</select>
</div>
</div>
<div>
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" @click="previousState()">
<font-awesome-icon icon="ban"></font-awesome-icon>&nbsp;<span>Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
:disabled="v$.$invalid || isSaving"
class="btn btn-primary"
>
<font-awesome-icon icon="save"></font-awesome-icon>&nbsp;<span>Save</span>
</button>
</div>
</form>
</div>
</div>
</template>
<script lang="ts" src="./registration-update.component.ts"></script>
@@ -0,0 +1,100 @@
/* tslint:disable max-line-length */
import { vitest } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import sinon, { type SinonStubbedInstance } from 'sinon';
import Registration from './registration.vue';
import RegistrationService from './registration.service';
import AlertService from '@/shared/alert/alert.service';
type RegistrationComponentType = InstanceType<typeof Registration>;
const bModalStub = {
render: () => {},
methods: {
hide: () => {},
show: () => {},
},
};
describe('Component Tests', () => {
let alertService: AlertService;
describe('Registration Management Component', () => {
let registrationServiceStub: SinonStubbedInstance<RegistrationService>;
let mountOptions: MountingOptions<RegistrationComponentType>['global'];
beforeEach(() => {
registrationServiceStub = sinon.createStubInstance<RegistrationService>(RegistrationService);
registrationServiceStub.retrieve.resolves({ headers: {} });
alertService = new AlertService({
bvToast: {
toast: vitest.fn(),
} as any,
});
mountOptions = {
stubs: {
bModal: bModalStub as any,
'font-awesome-icon': true,
'b-badge': true,
'b-button': true,
'router-link': true,
},
directives: {
'b-modal': {},
},
provide: {
alertService,
registrationService: () => registrationServiceStub,
},
};
});
describe('Mount', () => {
it('Should call load all on init', async () => {
// GIVEN
registrationServiceStub.retrieve.resolves({ headers: {}, data: [{ id: 123 }] });
// WHEN
const wrapper = shallowMount(Registration, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(registrationServiceStub.retrieve.calledOnce).toBeTruthy();
expect(comp.registrations[0]).toEqual(expect.objectContaining({ id: 123 }));
});
});
describe('Handles', () => {
let comp: RegistrationComponentType;
beforeEach(async () => {
const wrapper = shallowMount(Registration, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
registrationServiceStub.retrieve.reset();
registrationServiceStub.retrieve.resolves({ headers: {}, data: [] });
});
it('Should call delete service on confirmDelete', async () => {
// GIVEN
registrationServiceStub.delete.resolves({});
// WHEN
comp.prepareRemove({ id: 123 });
comp.removeRegistration();
await comp.$nextTick(); // clear components
// THEN
expect(registrationServiceStub.delete.called).toBeTruthy();
// THEN
await comp.$nextTick(); // handle component clear watch
expect(registrationServiceStub.retrieve.callCount).toEqual(1);
});
});
});
});
@@ -0,0 +1,81 @@
import { type Ref, defineComponent, inject, onMounted, ref } from 'vue';
import RegistrationService from './registration.service';
import { type IRegistration } from '@/shared/model/registration.model';
import useDataUtils from '@/shared/data/data-utils.service';
import { useDateFormat } from '@/shared/composables';
import { useAlertService } from '@/shared/alert/alert.service';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'Registration',
setup() {
const dateFormat = useDateFormat();
const dataUtils = useDataUtils();
const registrationService = inject('registrationService', () => new RegistrationService());
const alertService = inject('alertService', () => useAlertService(), true);
const registrations: Ref<IRegistration[]> = ref([]);
const isFetching = ref(false);
const clear = () => {};
const retrieveRegistrations = async () => {
isFetching.value = true;
try {
const res = await registrationService().retrieve();
registrations.value = res.data;
} catch (err) {
alertService.showHttpError(err.response);
} finally {
isFetching.value = false;
}
};
const handleSyncList = () => {
retrieveRegistrations();
};
onMounted(async () => {
await retrieveRegistrations();
});
const removeId: Ref<number> = ref(null);
const removeEntity = ref<any>(null);
const prepareRemove = (instance: IRegistration) => {
removeId.value = instance.id;
removeEntity.value.show();
};
const closeDialog = () => {
removeEntity.value.hide();
};
const removeRegistration = async () => {
try {
await registrationService().delete(removeId.value);
const message = `A Registration is deleted with identifier ${removeId.value}`;
alertService.showInfo(message, { variant: 'danger' });
removeId.value = null;
retrieveRegistrations();
closeDialog();
} catch (error) {
alertService.showHttpError(error.response);
}
};
return {
registrations,
handleSyncList,
isFetching,
retrieveRegistrations,
clear,
...dateFormat,
removeId,
removeEntity,
prepareRemove,
closeDialog,
removeRegistration,
...dataUtils,
};
},
});
@@ -0,0 +1,176 @@
/* tslint:disable max-line-length */
import axios from 'axios';
import sinon from 'sinon';
import dayjs from 'dayjs';
import RegistrationService from './registration.service';
import { DATE_TIME_FORMAT } from '@/shared/composables/date-format';
import { Registration } from '@/shared/model/registration.model';
const error = {
response: {
status: null,
data: {
type: null,
},
},
};
const axiosStub = {
get: sinon.stub(axios, 'get'),
post: sinon.stub(axios, 'post'),
put: sinon.stub(axios, 'put'),
patch: sinon.stub(axios, 'patch'),
delete: sinon.stub(axios, 'delete'),
};
describe('Service Tests', () => {
describe('Registration Service', () => {
let service: RegistrationService;
let elemDefault;
let currentDate: Date;
beforeEach(() => {
service = new RegistrationService();
currentDate = new Date();
elemDefault = new Registration(123, currentDate, false, 'AAAAAAA', 'AAAAAAA');
});
describe('Service methods', () => {
it('should find an element', async () => {
const returnedFromService = { dateTime: dayjs(currentDate).format(DATE_TIME_FORMAT), ...elemDefault };
axiosStub.get.resolves({ data: returnedFromService });
return service.find(123).then(res => {
expect(res).toMatchObject(elemDefault);
});
});
it('should not find an element', async () => {
axiosStub.get.rejects(error);
return service
.find(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should create a Registration', async () => {
const returnedFromService = { id: 123, dateTime: dayjs(currentDate).format(DATE_TIME_FORMAT), ...elemDefault };
const expected = { dateTime: currentDate, ...returnedFromService };
axiosStub.post.resolves({ data: returnedFromService });
return service.create({}).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not create a Registration', async () => {
axiosStub.post.rejects(error);
return service
.create({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should update a Registration', async () => {
const returnedFromService = {
dateTime: dayjs(currentDate).format(DATE_TIME_FORMAT),
active: true,
playerName: 'BBBBBB',
comment: 'BBBBBB',
...elemDefault,
};
const expected = { dateTime: currentDate, ...returnedFromService };
axiosStub.put.resolves({ data: returnedFromService });
return service.update(expected).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not update a Registration', async () => {
axiosStub.put.rejects(error);
return service
.update({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should partial update a Registration', async () => {
const patchObject = { comment: 'BBBBBB', ...new Registration() };
const returnedFromService = Object.assign(patchObject, elemDefault);
const expected = { dateTime: currentDate, ...returnedFromService };
axiosStub.patch.resolves({ data: returnedFromService });
return service.partialUpdate(patchObject).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not partial update a Registration', async () => {
axiosStub.patch.rejects(error);
return service
.partialUpdate({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should return a list of Registration', async () => {
const returnedFromService = {
dateTime: dayjs(currentDate).format(DATE_TIME_FORMAT),
active: true,
playerName: 'BBBBBB',
comment: 'BBBBBB',
...elemDefault,
};
const expected = { dateTime: currentDate, ...returnedFromService };
axiosStub.get.resolves([returnedFromService]);
return service.retrieve().then(res => {
expect(res).toContainEqual(expected);
});
});
it('should not return a list of Registration', async () => {
axiosStub.get.rejects(error);
return service
.retrieve()
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should delete a Registration', async () => {
axiosStub.delete.resolves({ ok: true });
return service.delete(123).then(res => {
expect(res.ok).toBeTruthy();
});
});
it('should not delete a Registration', async () => {
axiosStub.delete.rejects(error);
return service
.delete(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
});
});
});
@@ -0,0 +1,85 @@
import axios from 'axios';
import { type IRegistration } from '@/shared/model/registration.model';
const baseApiUrl = 'api/registrations';
export default class RegistrationService {
public find(id: number): Promise<IRegistration> {
return new Promise<IRegistration>((resolve, reject) => {
axios
.get(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public retrieve(): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.get(baseApiUrl)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
public delete(id: number): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.delete(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
public create(entity: IRegistration): Promise<IRegistration> {
return new Promise<IRegistration>((resolve, reject) => {
axios
.post(`${baseApiUrl}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public update(entity: IRegistration): Promise<IRegistration> {
return new Promise<IRegistration>((resolve, reject) => {
axios
.put(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
public partialUpdate(entity: IRegistration): Promise<IRegistration> {
return new Promise<IRegistration>((resolve, reject) => {
axios
.patch(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
}
@@ -0,0 +1,116 @@
<template>
<div>
<h2 id="page-heading" data-cy="RegistrationHeading">
<span id="registration-heading">Registrations</span>
<div class="d-flex justify-content-end">
<button class="btn btn-info mr-2" @click="handleSyncList" :disabled="isFetching">
<font-awesome-icon icon="sync" :spin="isFetching"></font-awesome-icon> <span>Refresh list</span>
</button>
<router-link :to="{ name: 'RegistrationCreate' }" custom v-slot="{ navigate }">
<button
@click="navigate"
id="jh-create-entity"
data-cy="entityCreateButton"
class="btn btn-primary jh-create-entity create-registration"
>
<font-awesome-icon icon="plus"></font-awesome-icon>
<span>Create a new Registration</span>
</button>
</router-link>
</div>
</h2>
<br />
<div class="alert alert-warning" v-if="!isFetching && registrations && registrations.length === 0">
<span>No Registrations found</span>
</div>
<div class="table-responsive" v-if="registrations && registrations.length > 0">
<table class="table table-striped" aria-describedby="registrations">
<thead>
<tr>
<th scope="row"><span>ID</span></th>
<th scope="row"><span>Date Time</span></th>
<th scope="row"><span>Active</span></th>
<th scope="row"><span>Player Name</span></th>
<th scope="row"><span>Comment</span></th>
<th scope="row"><span>User</span></th>
<th scope="row"><span>Event</span></th>
<th scope="row"></th>
</tr>
</thead>
<tbody>
<tr v-for="registration in registrations" :key="registration.id" data-cy="entityTable">
<td>
<router-link :to="{ name: 'RegistrationView', params: { registrationId: registration.id } }">{{
registration.id
}}</router-link>
</td>
<td>{{ formatDateShort(registration.dateTime) || '' }}</td>
<td>{{ registration.active }}</td>
<td>{{ registration.playerName }}</td>
<td>{{ registration.comment }}</td>
<td>
{{ registration.user ? registration.user.login : '' }}
</td>
<td>
<div v-if="registration.event">
<router-link :to="{ name: 'EventView', params: { eventId: registration.event.id } }">{{
registration.event.name
}}</router-link>
</div>
</td>
<td class="text-right">
<div class="btn-group">
<router-link :to="{ name: 'RegistrationView', params: { registrationId: registration.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-info btn-sm details" data-cy="entityDetailsButton">
<font-awesome-icon icon="eye"></font-awesome-icon>
<span class="d-none d-md-inline">View</span>
</button>
</router-link>
<router-link :to="{ name: 'RegistrationEdit', params: { registrationId: registration.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-primary btn-sm edit" data-cy="entityEditButton">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>
<span class="d-none d-md-inline">Edit</span>
</button>
</router-link>
<b-button
@click="prepareRemove(registration)"
variant="danger"
class="btn btn-sm"
data-cy="entityDeleteButton"
v-b-modal.removeEntity
>
<font-awesome-icon icon="times"></font-awesome-icon>
<span class="d-none d-md-inline">Delete</span>
</b-button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<b-modal ref="removeEntity" id="removeEntity">
<template #modal-title>
<span id="sasiedziApp.registration.delete.question" data-cy="registrationDeleteDialogHeading">Confirm delete operation</span>
</template>
<div class="modal-body">
<p id="jhi-delete-registration-heading">Are you sure you want to delete Registration {{ removeId }}?</p>
</div>
<template #modal-footer>
<div>
<button type="button" class="btn btn-secondary" @click="closeDialog()">Cancel</button>
<button
type="button"
class="btn btn-primary"
id="jhi-confirm-delete-registration"
data-cy="entityConfirmDeleteButton"
@click="removeRegistration()"
>
Delete
</button>
</div>
</template>
</b-modal>
</div>
</template>
<script lang="ts" src="./registration.component.ts"></script>
+85
View File
@@ -1,13 +1,98 @@
import { Authority } from '@/shared/security/authority';
/* tslint:disable */
// prettier-ignore
const Entities = () => import('@/entities/entities.vue');
const Charge = () => import('@/entities/charge/charge.vue');
const ChargeUpdate = () => import('@/entities/charge/charge-update.vue');
const ChargeDetails = () => import('@/entities/charge/charge-details.vue');
const Event = () => import('@/entities/event/event.vue');
const EventUpdate = () => import('@/entities/event/event-update.vue');
const EventDetails = () => import('@/entities/event/event-details.vue');
const Registration = () => import('@/entities/registration/registration.vue');
const RegistrationUpdate = () => import('@/entities/registration/registration-update.vue');
const RegistrationDetails = () => import('@/entities/registration/registration-details.vue');
// jhipster-needle-add-entity-to-router-import - JHipster will import entities to the router here
export default {
path: '/',
component: Entities,
children: [
{
path: 'charge',
name: 'Charge',
component: Charge,
meta: { authorities: [Authority.USER] },
},
{
path: 'charge/new',
name: 'ChargeCreate',
component: ChargeUpdate,
meta: { authorities: [Authority.USER] },
},
{
path: 'charge/:chargeId/edit',
name: 'ChargeEdit',
component: ChargeUpdate,
meta: { authorities: [Authority.USER] },
},
{
path: 'charge/:chargeId/view',
name: 'ChargeView',
component: ChargeDetails,
meta: { authorities: [Authority.USER] },
},
{
path: 'event',
name: 'Event',
component: Event,
meta: { authorities: [Authority.USER] },
},
{
path: 'event/new',
name: 'EventCreate',
component: EventUpdate,
meta: { authorities: [Authority.USER] },
},
{
path: 'event/:eventId/edit',
name: 'EventEdit',
component: EventUpdate,
meta: { authorities: [Authority.USER] },
},
{
path: 'event/:eventId/view',
name: 'EventView',
component: EventDetails,
meta: { authorities: [Authority.USER] },
},
{
path: 'registration',
name: 'Registration',
component: Registration,
meta: { authorities: [Authority.USER] },
},
{
path: 'registration/new',
name: 'RegistrationCreate',
component: RegistrationUpdate,
meta: { authorities: [Authority.USER] },
},
{
path: 'registration/:registrationId/edit',
name: 'RegistrationEdit',
component: RegistrationUpdate,
meta: { authorities: [Authority.USER] },
},
{
path: 'registration/:registrationId/view',
name: 'RegistrationView',
component: RegistrationDetails,
meta: { authorities: [Authority.USER] },
},
// jhipster-needle-add-entity-to-router - JHipster will add entities to the router here
],
};
@@ -0,0 +1,26 @@
import { type IEvent } from '@/shared/model/event.model';
import { type IRegistration } from '@/shared/model/registration.model';
import { type IUser } from '@/shared/model/user.model';
import { type ChargeType } from '@/shared/model/enumerations/charge-type.model';
export interface ICharge {
id?: number;
chargeDate?: Date;
type?: keyof typeof ChargeType;
amount?: number;
event?: IEvent | null;
registration?: IRegistration | null;
user?: IUser | null;
}
export class Charge implements ICharge {
constructor(
public id?: number,
public chargeDate?: Date,
public type?: keyof typeof ChargeType,
public amount?: number,
public event?: IEvent | null,
public registration?: IRegistration | null,
public user?: IUser | null,
) {}
}
@@ -0,0 +1,5 @@
export enum ChargeType {
CHARGE = 'CHARGE',
PAYMENT = 'PAYMENT',
}
@@ -0,0 +1,19 @@
export interface IEvent {
id?: number;
name?: string;
date?: Date;
playersLimit?: number | null;
cost?: number | null;
comment?: string | null;
}
export class Event implements IEvent {
constructor(
public id?: number,
public name?: string,
public date?: Date,
public playersLimit?: number | null,
public cost?: number | null,
public comment?: string | null,
) {}
}
@@ -0,0 +1,26 @@
import { type IUser } from '@/shared/model/user.model';
import { type IEvent } from '@/shared/model/event.model';
export interface IRegistration {
id?: number;
dateTime?: Date;
active?: boolean;
playerName?: string | null;
comment?: string | null;
user?: IUser | null;
event?: IEvent | null;
}
export class Registration implements IRegistration {
constructor(
public id?: number,
public dateTime?: Date,
public active?: boolean,
public playerName?: string | null,
public comment?: string | null,
public user?: IUser | null,
public event?: IEvent | null,
) {
this.active = this.active ?? false;
}
}
@@ -0,0 +1,69 @@
package com.sasiedzi.event.domain;
import static com.sasiedzi.event.domain.AssertUtils.bigDecimalCompareTo;
import static org.assertj.core.api.Assertions.assertThat;
public class ChargeAsserts {
/**
* Asserts that the entity has all properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertChargeAllPropertiesEquals(Charge expected, Charge actual) {
assertChargeAutoGeneratedPropertiesEquals(expected, actual);
assertChargeAllUpdatablePropertiesEquals(expected, actual);
}
/**
* Asserts that the entity has all updatable properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertChargeAllUpdatablePropertiesEquals(Charge expected, Charge actual) {
assertChargeUpdatableFieldsEquals(expected, actual);
assertChargeUpdatableRelationshipsEquals(expected, actual);
}
/**
* Asserts that the entity has all the auto generated properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertChargeAutoGeneratedPropertiesEquals(Charge expected, Charge actual) {
assertThat(expected)
.as("Verify Charge auto generated properties")
.satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId()));
}
/**
* Asserts that the entity has all the updatable fields set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertChargeUpdatableFieldsEquals(Charge expected, Charge actual) {
assertThat(expected)
.as("Verify Charge relevant properties")
.satisfies(e -> assertThat(e.getChargeDate()).as("check chargeDate").isEqualTo(actual.getChargeDate()))
.satisfies(e -> assertThat(e.getType()).as("check type").isEqualTo(actual.getType()))
.satisfies(e -> assertThat(e.getAmount()).as("check amount").usingComparator(bigDecimalCompareTo).isEqualTo(actual.getAmount())
);
}
/**
* Asserts that the entity has all the updatable relationships set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertChargeUpdatableRelationshipsEquals(Charge expected, Charge actual) {
assertThat(expected)
.as("Verify Charge relationships")
.satisfies(e -> assertThat(e.getEvent()).as("check event").isEqualTo(actual.getEvent()))
.satisfies(e -> assertThat(e.getRegistration()).as("check registration").isEqualTo(actual.getRegistration()));
}
}
@@ -0,0 +1,50 @@
package com.sasiedzi.event.domain;
import static com.sasiedzi.event.domain.ChargeTestSamples.*;
import static com.sasiedzi.event.domain.EventTestSamples.*;
import static com.sasiedzi.event.domain.RegistrationTestSamples.*;
import static org.assertj.core.api.Assertions.assertThat;
import com.sasiedzi.event.web.rest.TestUtil;
import org.junit.jupiter.api.Test;
class ChargeTest {
@Test
void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Charge.class);
Charge charge1 = getChargeSample1();
Charge charge2 = new Charge();
assertThat(charge1).isNotEqualTo(charge2);
charge2.setId(charge1.getId());
assertThat(charge1).isEqualTo(charge2);
charge2 = getChargeSample2();
assertThat(charge1).isNotEqualTo(charge2);
}
@Test
void eventTest() {
Charge charge = getChargeRandomSampleGenerator();
Event eventBack = getEventRandomSampleGenerator();
charge.setEvent(eventBack);
assertThat(charge.getEvent()).isEqualTo(eventBack);
charge.event(null);
assertThat(charge.getEvent()).isNull();
}
@Test
void registrationTest() {
Charge charge = getChargeRandomSampleGenerator();
Registration registrationBack = getRegistrationRandomSampleGenerator();
charge.setRegistration(registrationBack);
assertThat(charge.getRegistration()).isEqualTo(registrationBack);
charge.registration(null);
assertThat(charge.getRegistration()).isNull();
}
}
@@ -0,0 +1,22 @@
package com.sasiedzi.event.domain;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class ChargeTestSamples {
private static final Random random = new Random();
private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
public static Charge getChargeSample1() {
return new Charge().id(1L);
}
public static Charge getChargeSample2() {
return new Charge().id(2L);
}
public static Charge getChargeRandomSampleGenerator() {
return new Charge().id(longCount.incrementAndGet());
}
}
@@ -0,0 +1,67 @@
package com.sasiedzi.event.domain;
import static com.sasiedzi.event.domain.AssertUtils.bigDecimalCompareTo;
import static org.assertj.core.api.Assertions.assertThat;
public class EventAsserts {
/**
* Asserts that the entity has all properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertEventAllPropertiesEquals(Event expected, Event actual) {
assertEventAutoGeneratedPropertiesEquals(expected, actual);
assertEventAllUpdatablePropertiesEquals(expected, actual);
}
/**
* Asserts that the entity has all updatable properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertEventAllUpdatablePropertiesEquals(Event expected, Event actual) {
assertEventUpdatableFieldsEquals(expected, actual);
assertEventUpdatableRelationshipsEquals(expected, actual);
}
/**
* Asserts that the entity has all the auto generated properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertEventAutoGeneratedPropertiesEquals(Event expected, Event actual) {
assertThat(expected)
.as("Verify Event auto generated properties")
.satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId()));
}
/**
* Asserts that the entity has all the updatable fields set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertEventUpdatableFieldsEquals(Event expected, Event actual) {
assertThat(expected)
.as("Verify Event relevant properties")
.satisfies(e -> assertThat(e.getName()).as("check name").isEqualTo(actual.getName()))
.satisfies(e -> assertThat(e.getDate()).as("check date").isEqualTo(actual.getDate()))
.satisfies(e -> assertThat(e.getPlayersLimit()).as("check playersLimit").isEqualTo(actual.getPlayersLimit()))
.satisfies(e -> assertThat(e.getCost()).as("check cost").usingComparator(bigDecimalCompareTo).isEqualTo(actual.getCost()))
.satisfies(e -> assertThat(e.getComment()).as("check comment").isEqualTo(actual.getComment()));
}
/**
* Asserts that the entity has all the updatable relationships set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertEventUpdatableRelationshipsEquals(Event expected, Event actual) {
// empty method
}
}
@@ -0,0 +1,49 @@
package com.sasiedzi.event.domain;
import static com.sasiedzi.event.domain.EventTestSamples.*;
import static com.sasiedzi.event.domain.RegistrationTestSamples.*;
import static org.assertj.core.api.Assertions.assertThat;
import com.sasiedzi.event.web.rest.TestUtil;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class EventTest {
@Test
void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Event.class);
Event event1 = getEventSample1();
Event event2 = new Event();
assertThat(event1).isNotEqualTo(event2);
event2.setId(event1.getId());
assertThat(event1).isEqualTo(event2);
event2 = getEventSample2();
assertThat(event1).isNotEqualTo(event2);
}
@Test
void registrationsTest() {
Event event = getEventRandomSampleGenerator();
Registration registrationBack = getRegistrationRandomSampleGenerator();
event.addRegistrations(registrationBack);
assertThat(event.getRegistrations()).containsOnly(registrationBack);
assertThat(registrationBack.getEvent()).isEqualTo(event);
event.removeRegistrations(registrationBack);
assertThat(event.getRegistrations()).doesNotContain(registrationBack);
assertThat(registrationBack.getEvent()).isNull();
event.registrations(new HashSet<>(Set.of(registrationBack)));
assertThat(event.getRegistrations()).containsOnly(registrationBack);
assertThat(registrationBack.getEvent()).isEqualTo(event);
event.setRegistrations(new HashSet<>());
assertThat(event.getRegistrations()).doesNotContain(registrationBack);
assertThat(registrationBack.getEvent()).isNull();
}
}
@@ -0,0 +1,25 @@
package com.sasiedzi.event.domain;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class EventTestSamples {
private static final Random random = new Random();
private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
private static final AtomicInteger intCount = new AtomicInteger(random.nextInt() + (2 * Short.MAX_VALUE));
public static Event getEventSample1() {
return new Event().id(1L).name("name1").playersLimit(1);
}
public static Event getEventSample2() {
return new Event().id(2L).name("name2").playersLimit(2);
}
public static Event getEventRandomSampleGenerator() {
return new Event().id(longCount.incrementAndGet()).name(UUID.randomUUID().toString()).playersLimit(intCount.incrementAndGet());
}
}
@@ -0,0 +1,70 @@
package com.sasiedzi.event.domain;
import static com.sasiedzi.event.domain.AssertUtils.zonedDataTimeSameInstant;
import static org.assertj.core.api.Assertions.assertThat;
public class RegistrationAsserts {
/**
* Asserts that the entity has all properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertRegistrationAllPropertiesEquals(Registration expected, Registration actual) {
assertRegistrationAutoGeneratedPropertiesEquals(expected, actual);
assertRegistrationAllUpdatablePropertiesEquals(expected, actual);
}
/**
* Asserts that the entity has all updatable properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertRegistrationAllUpdatablePropertiesEquals(Registration expected, Registration actual) {
assertRegistrationUpdatableFieldsEquals(expected, actual);
assertRegistrationUpdatableRelationshipsEquals(expected, actual);
}
/**
* Asserts that the entity has all the auto generated properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertRegistrationAutoGeneratedPropertiesEquals(Registration expected, Registration actual) {
assertThat(expected)
.as("Verify Registration auto generated properties")
.satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId()));
}
/**
* Asserts that the entity has all the updatable fields set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertRegistrationUpdatableFieldsEquals(Registration expected, Registration actual) {
assertThat(expected)
.as("Verify Registration relevant properties")
.satisfies(e ->
assertThat(e.getDateTime()).as("check dateTime").usingComparator(zonedDataTimeSameInstant).isEqualTo(actual.getDateTime())
)
.satisfies(e -> assertThat(e.getActive()).as("check active").isEqualTo(actual.getActive()))
.satisfies(e -> assertThat(e.getPlayerName()).as("check playerName").isEqualTo(actual.getPlayerName()))
.satisfies(e -> assertThat(e.getComment()).as("check comment").isEqualTo(actual.getComment()));
}
/**
* Asserts that the entity has all the updatable relationships set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertRegistrationUpdatableRelationshipsEquals(Registration expected, Registration actual) {
assertThat(expected)
.as("Verify Registration relationships")
.satisfies(e -> assertThat(e.getEvent()).as("check event").isEqualTo(actual.getEvent()));
}
}
@@ -0,0 +1,37 @@
package com.sasiedzi.event.domain;
import static com.sasiedzi.event.domain.EventTestSamples.*;
import static com.sasiedzi.event.domain.RegistrationTestSamples.*;
import static org.assertj.core.api.Assertions.assertThat;
import com.sasiedzi.event.web.rest.TestUtil;
import org.junit.jupiter.api.Test;
class RegistrationTest {
@Test
void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Registration.class);
Registration registration1 = getRegistrationSample1();
Registration registration2 = new Registration();
assertThat(registration1).isNotEqualTo(registration2);
registration2.setId(registration1.getId());
assertThat(registration1).isEqualTo(registration2);
registration2 = getRegistrationSample2();
assertThat(registration1).isNotEqualTo(registration2);
}
@Test
void eventTest() {
Registration registration = getRegistrationRandomSampleGenerator();
Event eventBack = getEventRandomSampleGenerator();
registration.setEvent(eventBack);
assertThat(registration.getEvent()).isEqualTo(eventBack);
registration.event(null);
assertThat(registration.getEvent()).isNull();
}
}
@@ -0,0 +1,23 @@
package com.sasiedzi.event.domain;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
public class RegistrationTestSamples {
private static final Random random = new Random();
private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
public static Registration getRegistrationSample1() {
return new Registration().id(1L).playerName("playerName1");
}
public static Registration getRegistrationSample2() {
return new Registration().id(2L).playerName("playerName2");
}
public static Registration getRegistrationRandomSampleGenerator() {
return new Registration().id(longCount.incrementAndGet()).playerName(UUID.randomUUID().toString());
}
}
@@ -0,0 +1,506 @@
package com.sasiedzi.event.web.rest;
import static com.sasiedzi.event.domain.ChargeAsserts.*;
import static com.sasiedzi.event.web.rest.TestUtil.createUpdateProxyForBean;
import static com.sasiedzi.event.web.rest.TestUtil.sameNumber;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sasiedzi.event.IntegrationTest;
import com.sasiedzi.event.domain.Charge;
import com.sasiedzi.event.domain.enumeration.ChargeType;
import com.sasiedzi.event.repository.ChargeRepository;
import com.sasiedzi.event.repository.UserRepository;
import jakarta.persistence.EntityManager;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link ChargeResource} REST controller.
*/
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class ChargeResourceIT {
private static final LocalDate DEFAULT_CHARGE_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_CHARGE_DATE = LocalDate.now(ZoneId.systemDefault());
private static final ChargeType DEFAULT_TYPE = ChargeType.CHARGE;
private static final ChargeType UPDATED_TYPE = ChargeType.PAYMENT;
private static final BigDecimal DEFAULT_AMOUNT = new BigDecimal(1);
private static final BigDecimal UPDATED_AMOUNT = new BigDecimal(2);
private static final String ENTITY_API_URL = "/api/charges";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
@Autowired
private ObjectMapper om;
@Autowired
private ChargeRepository chargeRepository;
@Autowired
private UserRepository userRepository;
@Mock
private ChargeRepository chargeRepositoryMock;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restChargeMockMvc;
private Charge charge;
private Charge insertedCharge;
/**
* 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 Charge createEntity() {
return new Charge().chargeDate(DEFAULT_CHARGE_DATE).type(DEFAULT_TYPE).amount(DEFAULT_AMOUNT);
}
/**
* Create an updated 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 Charge createUpdatedEntity() {
return new Charge().chargeDate(UPDATED_CHARGE_DATE).type(UPDATED_TYPE).amount(UPDATED_AMOUNT);
}
@BeforeEach
public void initTest() {
charge = createEntity();
}
@AfterEach
public void cleanup() {
if (insertedCharge != null) {
chargeRepository.delete(insertedCharge);
insertedCharge = null;
}
userRepository.deleteAll();
}
@Test
@Transactional
void createCharge() throws Exception {
long databaseSizeBeforeCreate = getRepositoryCount();
// Create the Charge
var returnedCharge = om.readValue(
restChargeMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(charge)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getContentAsString(),
Charge.class
);
// Validate the Charge in the database
assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
assertChargeUpdatableFieldsEquals(returnedCharge, getPersistedCharge(returnedCharge));
insertedCharge = returnedCharge;
}
@Test
@Transactional
void createChargeWithExistingId() throws Exception {
// Create the Charge with an existing ID
charge.setId(1L);
long databaseSizeBeforeCreate = getRepositoryCount();
// An entity with an existing ID cannot be created, so this API call must fail
restChargeMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(charge)))
.andExpect(status().isBadRequest());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeCreate);
}
@Test
@Transactional
void checkChargeDateIsRequired() throws Exception {
long databaseSizeBeforeTest = getRepositoryCount();
// set the field null
charge.setChargeDate(null);
// Create the Charge, which fails.
restChargeMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(charge)))
.andExpect(status().isBadRequest());
assertSameRepositoryCount(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkTypeIsRequired() throws Exception {
long databaseSizeBeforeTest = getRepositoryCount();
// set the field null
charge.setType(null);
// Create the Charge, which fails.
restChargeMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(charge)))
.andExpect(status().isBadRequest());
assertSameRepositoryCount(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkAmountIsRequired() throws Exception {
long databaseSizeBeforeTest = getRepositoryCount();
// set the field null
charge.setAmount(null);
// Create the Charge, which fails.
restChargeMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(charge)))
.andExpect(status().isBadRequest());
assertSameRepositoryCount(databaseSizeBeforeTest);
}
@Test
@Transactional
void getAllCharges() throws Exception {
// Initialize the database
insertedCharge = chargeRepository.saveAndFlush(charge);
// Get all the chargeList
restChargeMockMvc
.perform(get(ENTITY_API_URL + "?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(charge.getId().intValue())))
.andExpect(jsonPath("$.[*].chargeDate").value(hasItem(DEFAULT_CHARGE_DATE.toString())))
.andExpect(jsonPath("$.[*].type").value(hasItem(DEFAULT_TYPE.toString())))
.andExpect(jsonPath("$.[*].amount").value(hasItem(sameNumber(DEFAULT_AMOUNT))));
}
@SuppressWarnings({ "unchecked" })
void getAllChargesWithEagerRelationshipsIsEnabled() throws Exception {
when(chargeRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
restChargeMockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")).andExpect(status().isOk());
verify(chargeRepositoryMock, times(1)).findAllWithEagerRelationships(any());
}
@SuppressWarnings({ "unchecked" })
void getAllChargesWithEagerRelationshipsIsNotEnabled() throws Exception {
when(chargeRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
restChargeMockMvc.perform(get(ENTITY_API_URL + "?eagerload=false")).andExpect(status().isOk());
verify(chargeRepositoryMock, times(1)).findAll(any(Pageable.class));
}
@Test
@Transactional
void getCharge() throws Exception {
// Initialize the database
insertedCharge = chargeRepository.saveAndFlush(charge);
// Get the charge
restChargeMockMvc
.perform(get(ENTITY_API_URL_ID, charge.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(charge.getId().intValue()))
.andExpect(jsonPath("$.chargeDate").value(DEFAULT_CHARGE_DATE.toString()))
.andExpect(jsonPath("$.type").value(DEFAULT_TYPE.toString()))
.andExpect(jsonPath("$.amount").value(sameNumber(DEFAULT_AMOUNT)));
}
@Test
@Transactional
void getNonExistingCharge() throws Exception {
// Get the charge
restChargeMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void putExistingCharge() throws Exception {
// Initialize the database
insertedCharge = chargeRepository.saveAndFlush(charge);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the charge
Charge updatedCharge = chargeRepository.findById(charge.getId()).orElseThrow();
// Disconnect from session so that the updates on updatedCharge are not directly saved in db
em.detach(updatedCharge);
updatedCharge.chargeDate(UPDATED_CHARGE_DATE).type(UPDATED_TYPE).amount(UPDATED_AMOUNT);
restChargeMockMvc
.perform(
put(ENTITY_API_URL_ID, updatedCharge.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(updatedCharge))
)
.andExpect(status().isOk());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertPersistedChargeToMatchAllProperties(updatedCharge);
}
@Test
@Transactional
void putNonExistingCharge() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
charge.setId(longCount.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restChargeMockMvc
.perform(
put(ENTITY_API_URL_ID, charge.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(charge))
)
.andExpect(status().isBadRequest());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithIdMismatchCharge() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
charge.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restChargeMockMvc
.perform(
put(ENTITY_API_URL_ID, longCount.incrementAndGet())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(charge))
)
.andExpect(status().isBadRequest());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithMissingIdPathParamCharge() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
charge.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restChargeMockMvc
.perform(put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(charge)))
.andExpect(status().isMethodNotAllowed());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void partialUpdateChargeWithPatch() throws Exception {
// Initialize the database
insertedCharge = chargeRepository.saveAndFlush(charge);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the charge using partial update
Charge partialUpdatedCharge = new Charge();
partialUpdatedCharge.setId(charge.getId());
partialUpdatedCharge.chargeDate(UPDATED_CHARGE_DATE).amount(UPDATED_AMOUNT);
restChargeMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedCharge.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(partialUpdatedCharge))
)
.andExpect(status().isOk());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertChargeUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedCharge, charge), getPersistedCharge(charge));
}
@Test
@Transactional
void fullUpdateChargeWithPatch() throws Exception {
// Initialize the database
insertedCharge = chargeRepository.saveAndFlush(charge);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the charge using partial update
Charge partialUpdatedCharge = new Charge();
partialUpdatedCharge.setId(charge.getId());
partialUpdatedCharge.chargeDate(UPDATED_CHARGE_DATE).type(UPDATED_TYPE).amount(UPDATED_AMOUNT);
restChargeMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedCharge.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(partialUpdatedCharge))
)
.andExpect(status().isOk());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertChargeUpdatableFieldsEquals(partialUpdatedCharge, getPersistedCharge(partialUpdatedCharge));
}
@Test
@Transactional
void patchNonExistingCharge() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
charge.setId(longCount.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restChargeMockMvc
.perform(
patch(ENTITY_API_URL_ID, charge.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(charge))
)
.andExpect(status().isBadRequest());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithIdMismatchCharge() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
charge.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restChargeMockMvc
.perform(
patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(charge))
)
.andExpect(status().isBadRequest());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithMissingIdPathParamCharge() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
charge.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restChargeMockMvc
.perform(patch(ENTITY_API_URL).with(csrf()).contentType("application/merge-patch+json").content(om.writeValueAsBytes(charge)))
.andExpect(status().isMethodNotAllowed());
// Validate the Charge in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void deleteCharge() throws Exception {
// Initialize the database
insertedCharge = chargeRepository.saveAndFlush(charge);
long databaseSizeBeforeDelete = getRepositoryCount();
// Delete the charge
restChargeMockMvc
.perform(delete(ENTITY_API_URL_ID, charge.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
}
protected long getRepositoryCount() {
return chargeRepository.count();
}
protected void assertIncrementedRepositoryCount(long countBefore) {
assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
}
protected void assertDecrementedRepositoryCount(long countBefore) {
assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
}
protected void assertSameRepositoryCount(long countBefore) {
assertThat(countBefore).isEqualTo(getRepositoryCount());
}
protected Charge getPersistedCharge(Charge charge) {
return chargeRepository.findById(charge.getId()).orElseThrow();
}
protected void assertPersistedChargeToMatchAllProperties(Charge expectedCharge) {
assertChargeAllPropertiesEquals(expectedCharge, getPersistedCharge(expectedCharge));
}
protected void assertPersistedChargeToMatchUpdatableProperties(Charge expectedCharge) {
assertChargeAllUpdatablePropertiesEquals(expectedCharge, getPersistedCharge(expectedCharge));
}
}
@@ -0,0 +1,481 @@
package com.sasiedzi.event.web.rest;
import static com.sasiedzi.event.domain.EventAsserts.*;
import static com.sasiedzi.event.web.rest.TestUtil.createUpdateProxyForBean;
import static com.sasiedzi.event.web.rest.TestUtil.sameNumber;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sasiedzi.event.IntegrationTest;
import com.sasiedzi.event.domain.Event;
import com.sasiedzi.event.repository.EventRepository;
import jakarta.persistence.EntityManager;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link EventResource} REST controller.
*/
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class EventResourceIT {
private static final String DEFAULT_NAME = "AAAAAAAAAA";
private static final String UPDATED_NAME = "BBBBBBBBBB";
private static final LocalDate DEFAULT_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_DATE = LocalDate.now(ZoneId.systemDefault());
private static final Integer DEFAULT_PLAYERS_LIMIT = 1;
private static final Integer UPDATED_PLAYERS_LIMIT = 2;
private static final BigDecimal DEFAULT_COST = new BigDecimal(1);
private static final BigDecimal UPDATED_COST = new BigDecimal(2);
private static final String DEFAULT_COMMENT = "AAAAAAAAAA";
private static final String UPDATED_COMMENT = "BBBBBBBBBB";
private static final String ENTITY_API_URL = "/api/events";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
@Autowired
private ObjectMapper om;
@Autowired
private EventRepository eventRepository;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restEventMockMvc;
private Event event;
private Event insertedEvent;
/**
* 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 Event createEntity() {
return new Event()
.name(DEFAULT_NAME)
.date(DEFAULT_DATE)
.playersLimit(DEFAULT_PLAYERS_LIMIT)
.cost(DEFAULT_COST)
.comment(DEFAULT_COMMENT);
}
/**
* Create an updated 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 Event createUpdatedEntity() {
return new Event()
.name(UPDATED_NAME)
.date(UPDATED_DATE)
.playersLimit(UPDATED_PLAYERS_LIMIT)
.cost(UPDATED_COST)
.comment(UPDATED_COMMENT);
}
@BeforeEach
public void initTest() {
event = createEntity();
}
@AfterEach
public void cleanup() {
if (insertedEvent != null) {
eventRepository.delete(insertedEvent);
insertedEvent = null;
}
}
@Test
@Transactional
void createEvent() throws Exception {
long databaseSizeBeforeCreate = getRepositoryCount();
// Create the Event
var returnedEvent = om.readValue(
restEventMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(event)))
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getContentAsString(),
Event.class
);
// Validate the Event in the database
assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
assertEventUpdatableFieldsEquals(returnedEvent, getPersistedEvent(returnedEvent));
insertedEvent = returnedEvent;
}
@Test
@Transactional
void createEventWithExistingId() throws Exception {
// Create the Event with an existing ID
event.setId(1L);
long databaseSizeBeforeCreate = getRepositoryCount();
// An entity with an existing ID cannot be created, so this API call must fail
restEventMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(event)))
.andExpect(status().isBadRequest());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeCreate);
}
@Test
@Transactional
void checkNameIsRequired() throws Exception {
long databaseSizeBeforeTest = getRepositoryCount();
// set the field null
event.setName(null);
// Create the Event, which fails.
restEventMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(event)))
.andExpect(status().isBadRequest());
assertSameRepositoryCount(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkDateIsRequired() throws Exception {
long databaseSizeBeforeTest = getRepositoryCount();
// set the field null
event.setDate(null);
// Create the Event, which fails.
restEventMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(event)))
.andExpect(status().isBadRequest());
assertSameRepositoryCount(databaseSizeBeforeTest);
}
@Test
@Transactional
void getAllEvents() throws Exception {
// Initialize the database
insertedEvent = eventRepository.saveAndFlush(event);
// Get all the eventList
restEventMockMvc
.perform(get(ENTITY_API_URL + "?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(event.getId().intValue())))
.andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
.andExpect(jsonPath("$.[*].date").value(hasItem(DEFAULT_DATE.toString())))
.andExpect(jsonPath("$.[*].playersLimit").value(hasItem(DEFAULT_PLAYERS_LIMIT)))
.andExpect(jsonPath("$.[*].cost").value(hasItem(sameNumber(DEFAULT_COST))))
.andExpect(jsonPath("$.[*].comment").value(hasItem(DEFAULT_COMMENT.toString())));
}
@Test
@Transactional
void getEvent() throws Exception {
// Initialize the database
insertedEvent = eventRepository.saveAndFlush(event);
// Get the event
restEventMockMvc
.perform(get(ENTITY_API_URL_ID, event.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(event.getId().intValue()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME))
.andExpect(jsonPath("$.date").value(DEFAULT_DATE.toString()))
.andExpect(jsonPath("$.playersLimit").value(DEFAULT_PLAYERS_LIMIT))
.andExpect(jsonPath("$.cost").value(sameNumber(DEFAULT_COST)))
.andExpect(jsonPath("$.comment").value(DEFAULT_COMMENT.toString()));
}
@Test
@Transactional
void getNonExistingEvent() throws Exception {
// Get the event
restEventMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void putExistingEvent() throws Exception {
// Initialize the database
insertedEvent = eventRepository.saveAndFlush(event);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the event
Event updatedEvent = eventRepository.findById(event.getId()).orElseThrow();
// Disconnect from session so that the updates on updatedEvent are not directly saved in db
em.detach(updatedEvent);
updatedEvent.name(UPDATED_NAME).date(UPDATED_DATE).playersLimit(UPDATED_PLAYERS_LIMIT).cost(UPDATED_COST).comment(UPDATED_COMMENT);
restEventMockMvc
.perform(
put(ENTITY_API_URL_ID, updatedEvent.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(updatedEvent))
)
.andExpect(status().isOk());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertPersistedEventToMatchAllProperties(updatedEvent);
}
@Test
@Transactional
void putNonExistingEvent() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
event.setId(longCount.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restEventMockMvc
.perform(
put(ENTITY_API_URL_ID, event.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(event))
)
.andExpect(status().isBadRequest());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithIdMismatchEvent() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
event.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restEventMockMvc
.perform(
put(ENTITY_API_URL_ID, longCount.incrementAndGet())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(event))
)
.andExpect(status().isBadRequest());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithMissingIdPathParamEvent() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
event.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restEventMockMvc
.perform(put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(event)))
.andExpect(status().isMethodNotAllowed());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void partialUpdateEventWithPatch() throws Exception {
// Initialize the database
insertedEvent = eventRepository.saveAndFlush(event);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the event using partial update
Event partialUpdatedEvent = new Event();
partialUpdatedEvent.setId(event.getId());
partialUpdatedEvent.name(UPDATED_NAME).date(UPDATED_DATE).playersLimit(UPDATED_PLAYERS_LIMIT);
restEventMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedEvent.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(partialUpdatedEvent))
)
.andExpect(status().isOk());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertEventUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedEvent, event), getPersistedEvent(event));
}
@Test
@Transactional
void fullUpdateEventWithPatch() throws Exception {
// Initialize the database
insertedEvent = eventRepository.saveAndFlush(event);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the event using partial update
Event partialUpdatedEvent = new Event();
partialUpdatedEvent.setId(event.getId());
partialUpdatedEvent
.name(UPDATED_NAME)
.date(UPDATED_DATE)
.playersLimit(UPDATED_PLAYERS_LIMIT)
.cost(UPDATED_COST)
.comment(UPDATED_COMMENT);
restEventMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedEvent.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(partialUpdatedEvent))
)
.andExpect(status().isOk());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertEventUpdatableFieldsEquals(partialUpdatedEvent, getPersistedEvent(partialUpdatedEvent));
}
@Test
@Transactional
void patchNonExistingEvent() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
event.setId(longCount.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restEventMockMvc
.perform(
patch(ENTITY_API_URL_ID, event.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(event))
)
.andExpect(status().isBadRequest());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithIdMismatchEvent() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
event.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restEventMockMvc
.perform(
patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(event))
)
.andExpect(status().isBadRequest());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithMissingIdPathParamEvent() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
event.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restEventMockMvc
.perform(patch(ENTITY_API_URL).with(csrf()).contentType("application/merge-patch+json").content(om.writeValueAsBytes(event)))
.andExpect(status().isMethodNotAllowed());
// Validate the Event in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void deleteEvent() throws Exception {
// Initialize the database
insertedEvent = eventRepository.saveAndFlush(event);
long databaseSizeBeforeDelete = getRepositoryCount();
// Delete the event
restEventMockMvc
.perform(delete(ENTITY_API_URL_ID, event.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
}
protected long getRepositoryCount() {
return eventRepository.count();
}
protected void assertIncrementedRepositoryCount(long countBefore) {
assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
}
protected void assertDecrementedRepositoryCount(long countBefore) {
assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
}
protected void assertSameRepositoryCount(long countBefore) {
assertThat(countBefore).isEqualTo(getRepositoryCount());
}
protected Event getPersistedEvent(Event event) {
return eventRepository.findById(event.getId()).orElseThrow();
}
protected void assertPersistedEventToMatchAllProperties(Event expectedEvent) {
assertEventAllPropertiesEquals(expectedEvent, getPersistedEvent(expectedEvent));
}
protected void assertPersistedEventToMatchUpdatableProperties(Event expectedEvent) {
assertEventAllUpdatablePropertiesEquals(expectedEvent, getPersistedEvent(expectedEvent));
}
}
@@ -0,0 +1,514 @@
package com.sasiedzi.event.web.rest;
import static com.sasiedzi.event.domain.RegistrationAsserts.*;
import static com.sasiedzi.event.web.rest.TestUtil.createUpdateProxyForBean;
import static com.sasiedzi.event.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sasiedzi.event.IntegrationTest;
import com.sasiedzi.event.domain.Registration;
import com.sasiedzi.event.repository.RegistrationRepository;
import com.sasiedzi.event.repository.UserRepository;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link RegistrationResource} REST controller.
*/
@IntegrationTest
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithMockUser
class RegistrationResourceIT {
private static final ZonedDateTime DEFAULT_DATE_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_DATE_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final Boolean DEFAULT_ACTIVE = false;
private static final Boolean UPDATED_ACTIVE = true;
private static final String DEFAULT_PLAYER_NAME = "AAAAAAAAAA";
private static final String UPDATED_PLAYER_NAME = "BBBBBBBBBB";
private static final String DEFAULT_COMMENT = "AAAAAAAAAA";
private static final String UPDATED_COMMENT = "BBBBBBBBBB";
private static final String ENTITY_API_URL = "/api/registrations";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
@Autowired
private ObjectMapper om;
@Autowired
private RegistrationRepository registrationRepository;
@Autowired
private UserRepository userRepository;
@Mock
private RegistrationRepository registrationRepositoryMock;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restRegistrationMockMvc;
private Registration registration;
private Registration insertedRegistration;
/**
* 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 Registration createEntity() {
return new Registration()
.dateTime(DEFAULT_DATE_TIME)
.active(DEFAULT_ACTIVE)
.playerName(DEFAULT_PLAYER_NAME)
.comment(DEFAULT_COMMENT);
}
/**
* Create an updated 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 Registration createUpdatedEntity() {
return new Registration()
.dateTime(UPDATED_DATE_TIME)
.active(UPDATED_ACTIVE)
.playerName(UPDATED_PLAYER_NAME)
.comment(UPDATED_COMMENT);
}
@BeforeEach
public void initTest() {
registration = createEntity();
}
@AfterEach
public void cleanup() {
if (insertedRegistration != null) {
registrationRepository.delete(insertedRegistration);
insertedRegistration = null;
}
userRepository.deleteAll();
}
@Test
@Transactional
void createRegistration() throws Exception {
long databaseSizeBeforeCreate = getRepositoryCount();
// Create the Registration
var returnedRegistration = om.readValue(
restRegistrationMockMvc
.perform(
post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(registration))
)
.andExpect(status().isCreated())
.andReturn()
.getResponse()
.getContentAsString(),
Registration.class
);
// Validate the Registration in the database
assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
assertRegistrationUpdatableFieldsEquals(returnedRegistration, getPersistedRegistration(returnedRegistration));
insertedRegistration = returnedRegistration;
}
@Test
@Transactional
void createRegistrationWithExistingId() throws Exception {
// Create the Registration with an existing ID
registration.setId(1L);
long databaseSizeBeforeCreate = getRepositoryCount();
// An entity with an existing ID cannot be created, so this API call must fail
restRegistrationMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(registration)))
.andExpect(status().isBadRequest());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeCreate);
}
@Test
@Transactional
void checkDateTimeIsRequired() throws Exception {
long databaseSizeBeforeTest = getRepositoryCount();
// set the field null
registration.setDateTime(null);
// Create the Registration, which fails.
restRegistrationMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(registration)))
.andExpect(status().isBadRequest());
assertSameRepositoryCount(databaseSizeBeforeTest);
}
@Test
@Transactional
void checkActiveIsRequired() throws Exception {
long databaseSizeBeforeTest = getRepositoryCount();
// set the field null
registration.setActive(null);
// Create the Registration, which fails.
restRegistrationMockMvc
.perform(post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(registration)))
.andExpect(status().isBadRequest());
assertSameRepositoryCount(databaseSizeBeforeTest);
}
@Test
@Transactional
void getAllRegistrations() throws Exception {
// Initialize the database
insertedRegistration = registrationRepository.saveAndFlush(registration);
// Get all the registrationList
restRegistrationMockMvc
.perform(get(ENTITY_API_URL + "?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(registration.getId().intValue())))
.andExpect(jsonPath("$.[*].dateTime").value(hasItem(sameInstant(DEFAULT_DATE_TIME))))
.andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue())))
.andExpect(jsonPath("$.[*].playerName").value(hasItem(DEFAULT_PLAYER_NAME)))
.andExpect(jsonPath("$.[*].comment").value(hasItem(DEFAULT_COMMENT.toString())));
}
@SuppressWarnings({ "unchecked" })
void getAllRegistrationsWithEagerRelationshipsIsEnabled() throws Exception {
when(registrationRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
restRegistrationMockMvc.perform(get(ENTITY_API_URL + "?eagerload=true")).andExpect(status().isOk());
verify(registrationRepositoryMock, times(1)).findAllWithEagerRelationships(any());
}
@SuppressWarnings({ "unchecked" })
void getAllRegistrationsWithEagerRelationshipsIsNotEnabled() throws Exception {
when(registrationRepositoryMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>()));
restRegistrationMockMvc.perform(get(ENTITY_API_URL + "?eagerload=false")).andExpect(status().isOk());
verify(registrationRepositoryMock, times(1)).findAll(any(Pageable.class));
}
@Test
@Transactional
void getRegistration() throws Exception {
// Initialize the database
insertedRegistration = registrationRepository.saveAndFlush(registration);
// Get the registration
restRegistrationMockMvc
.perform(get(ENTITY_API_URL_ID, registration.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(registration.getId().intValue()))
.andExpect(jsonPath("$.dateTime").value(sameInstant(DEFAULT_DATE_TIME)))
.andExpect(jsonPath("$.active").value(DEFAULT_ACTIVE.booleanValue()))
.andExpect(jsonPath("$.playerName").value(DEFAULT_PLAYER_NAME))
.andExpect(jsonPath("$.comment").value(DEFAULT_COMMENT.toString()));
}
@Test
@Transactional
void getNonExistingRegistration() throws Exception {
// Get the registration
restRegistrationMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void putExistingRegistration() throws Exception {
// Initialize the database
insertedRegistration = registrationRepository.saveAndFlush(registration);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the registration
Registration updatedRegistration = registrationRepository.findById(registration.getId()).orElseThrow();
// Disconnect from session so that the updates on updatedRegistration are not directly saved in db
em.detach(updatedRegistration);
updatedRegistration.dateTime(UPDATED_DATE_TIME).active(UPDATED_ACTIVE).playerName(UPDATED_PLAYER_NAME).comment(UPDATED_COMMENT);
restRegistrationMockMvc
.perform(
put(ENTITY_API_URL_ID, updatedRegistration.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(updatedRegistration))
)
.andExpect(status().isOk());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertPersistedRegistrationToMatchAllProperties(updatedRegistration);
}
@Test
@Transactional
void putNonExistingRegistration() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
registration.setId(longCount.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restRegistrationMockMvc
.perform(
put(ENTITY_API_URL_ID, registration.getId())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(registration))
)
.andExpect(status().isBadRequest());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithIdMismatchRegistration() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
registration.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restRegistrationMockMvc
.perform(
put(ENTITY_API_URL_ID, longCount.incrementAndGet())
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(om.writeValueAsBytes(registration))
)
.andExpect(status().isBadRequest());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithMissingIdPathParamRegistration() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
registration.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restRegistrationMockMvc
.perform(put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(registration)))
.andExpect(status().isMethodNotAllowed());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void partialUpdateRegistrationWithPatch() throws Exception {
// Initialize the database
insertedRegistration = registrationRepository.saveAndFlush(registration);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the registration using partial update
Registration partialUpdatedRegistration = new Registration();
partialUpdatedRegistration.setId(registration.getId());
partialUpdatedRegistration.active(UPDATED_ACTIVE).comment(UPDATED_COMMENT);
restRegistrationMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedRegistration.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(partialUpdatedRegistration))
)
.andExpect(status().isOk());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertRegistrationUpdatableFieldsEquals(
createUpdateProxyForBean(partialUpdatedRegistration, registration),
getPersistedRegistration(registration)
);
}
@Test
@Transactional
void fullUpdateRegistrationWithPatch() throws Exception {
// Initialize the database
insertedRegistration = registrationRepository.saveAndFlush(registration);
long databaseSizeBeforeUpdate = getRepositoryCount();
// Update the registration using partial update
Registration partialUpdatedRegistration = new Registration();
partialUpdatedRegistration.setId(registration.getId());
partialUpdatedRegistration
.dateTime(UPDATED_DATE_TIME)
.active(UPDATED_ACTIVE)
.playerName(UPDATED_PLAYER_NAME)
.comment(UPDATED_COMMENT);
restRegistrationMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedRegistration.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(partialUpdatedRegistration))
)
.andExpect(status().isOk());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
assertRegistrationUpdatableFieldsEquals(partialUpdatedRegistration, getPersistedRegistration(partialUpdatedRegistration));
}
@Test
@Transactional
void patchNonExistingRegistration() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
registration.setId(longCount.incrementAndGet());
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restRegistrationMockMvc
.perform(
patch(ENTITY_API_URL_ID, registration.getId())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(registration))
)
.andExpect(status().isBadRequest());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithIdMismatchRegistration() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
registration.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restRegistrationMockMvc
.perform(
patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
.with(csrf())
.contentType("application/merge-patch+json")
.content(om.writeValueAsBytes(registration))
)
.andExpect(status().isBadRequest());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithMissingIdPathParamRegistration() throws Exception {
long databaseSizeBeforeUpdate = getRepositoryCount();
registration.setId(longCount.incrementAndGet());
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restRegistrationMockMvc
.perform(
patch(ENTITY_API_URL).with(csrf()).contentType("application/merge-patch+json").content(om.writeValueAsBytes(registration))
)
.andExpect(status().isMethodNotAllowed());
// Validate the Registration in the database
assertSameRepositoryCount(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void deleteRegistration() throws Exception {
// Initialize the database
insertedRegistration = registrationRepository.saveAndFlush(registration);
long databaseSizeBeforeDelete = getRepositoryCount();
// Delete the registration
restRegistrationMockMvc
.perform(delete(ENTITY_API_URL_ID, registration.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
}
protected long getRepositoryCount() {
return registrationRepository.count();
}
protected void assertIncrementedRepositoryCount(long countBefore) {
assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
}
protected void assertDecrementedRepositoryCount(long countBefore) {
assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
}
protected void assertSameRepositoryCount(long countBefore) {
assertThat(countBefore).isEqualTo(getRepositoryCount());
}
protected Registration getPersistedRegistration(Registration registration) {
return registrationRepository.findById(registration.getId()).orElseThrow();
}
protected void assertPersistedRegistrationToMatchAllProperties(Registration expectedRegistration) {
assertRegistrationAllPropertiesEquals(expectedRegistration, getPersistedRegistration(expectedRegistration));
}
protected void assertPersistedRegistrationToMatchUpdatableProperties(Registration expectedRegistration) {
assertRegistrationAllUpdatablePropertiesEquals(expectedRegistration, getPersistedRegistration(expectedRegistration));
}
}