From c2bf40c1a4f868519f3415203874fdc82cb1ac65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C5=82awek=20Zatorski?= Date: Tue, 5 Nov 2024 10:11:11 +0100 Subject: [PATCH] init --- .jhipster/Charge.json | 50 ++ .jhipster/Event.json | 42 ++ .jhipster/Registration.json | 46 ++ .yo-rc.json | 3 +- domain.jdl | 55 ++ .../com/sasiedzi/event/domain/Charge.java | 173 ++++++ .../java/com/sasiedzi/event/domain/Event.java | 192 +++++++ .../sasiedzi/event/domain/Registration.java | 170 ++++++ .../event/domain/enumeration/ChargeType.java | 9 + .../domain/enumeration/package-info.java | 4 + .../event/repository/ChargeRepository.java | 40 ++ .../event/repository/EventRepository.java | 12 + .../repository/RegistrationRepository.java | 45 ++ .../sasiedzi/event/service/EventService.java | 114 ++++ .../event/web/rest/ChargeResource.java | 189 +++++++ .../event/web/rest/EventResource.java | 169 ++++++ .../event/web/rest/RegistrationResource.java | 194 +++++++ .../20241105091001_added_entity_Charge.xml | 62 +++ ...091001_added_entity_constraints_Charge.xml | 34 ++ .../20241105091002_added_entity_Event.xml | 61 +++ ...241105091003_added_entity_Registration.xml | 64 +++ ..._added_entity_constraints_Registration.xml | 27 + .../liquibase/fake-data/blob/hipster.png | Bin 0 -> 7564 bytes .../liquibase/fake-data/blob/hipster.txt | 1 + .../config/liquibase/fake-data/charge.csv | 11 + .../config/liquibase/fake-data/event.csv | 11 + .../liquibase/fake-data/registration.csv | 11 + .../resources/config/liquibase/master.xml | 5 + .../charge/charge-details.component.spec.ts | 89 +++ .../charge/charge-details.component.ts | 41 ++ .../app/entities/charge/charge-details.vue | 63 +++ .../charge/charge-update.component.spec.ts | 149 +++++ .../charge/charge-update.component.ts | 140 +++++ .../app/entities/charge/charge-update.vue | 134 +++++ .../entities/charge/charge.component.spec.ts | 100 ++++ .../app/entities/charge/charge.component.ts | 75 +++ .../entities/charge/charge.service.spec.ts | 164 ++++++ .../app/entities/charge/charge.service.ts | 85 +++ .../webapp/app/entities/charge/charge.vue | 118 ++++ .../webapp/app/entities/entities-menu.vue | 12 + .../webapp/app/entities/entities.component.ts | 6 + .../event/event-details.component.spec.ts | 89 +++ .../entities/event/event-details.component.ts | 46 ++ .../app/entities/event/event-details.vue | 51 ++ .../event/event-update.component.spec.ts | 131 +++++ .../entities/event/event-update.component.ts | 100 ++++ .../app/entities/event/event-update.vue | 113 ++++ .../entities/event/event.component.spec.ts | 100 ++++ .../app/entities/event/event.component.ts | 78 +++ .../app/entities/event/event.service.spec.ts | 178 ++++++ .../app/entities/event/event.service.ts | 85 +++ src/main/webapp/app/entities/event/event.vue | 104 ++++ .../registration-details.component.spec.ts | 89 +++ .../registration-details.component.ts | 49 ++ .../registration/registration-details.vue | 66 +++ .../registration-update.component.spec.ts | 166 ++++++ .../registration-update.component.ts | 129 +++++ .../registration/registration-update.vue | 116 ++++ .../registration.component.spec.ts | 100 ++++ .../registration/registration.component.ts | 81 +++ .../registration/registration.service.spec.ts | 176 ++++++ .../registration/registration.service.ts | 85 +++ .../entities/registration/registration.vue | 116 ++++ src/main/webapp/app/router/entities.ts | 85 +++ .../webapp/app/shared/model/charge.model.ts | 26 + .../model/enumerations/charge-type.model.ts | 5 + .../webapp/app/shared/model/event.model.ts | 19 + .../app/shared/model/registration.model.ts | 26 + .../sasiedzi/event/domain/ChargeAsserts.java | 69 +++ .../com/sasiedzi/event/domain/ChargeTest.java | 50 ++ .../event/domain/ChargeTestSamples.java | 22 + .../sasiedzi/event/domain/EventAsserts.java | 67 +++ .../com/sasiedzi/event/domain/EventTest.java | 49 ++ .../event/domain/EventTestSamples.java | 25 + .../event/domain/RegistrationAsserts.java | 70 +++ .../event/domain/RegistrationTest.java | 37 ++ .../event/domain/RegistrationTestSamples.java | 23 + .../event/web/rest/ChargeResourceIT.java | 506 +++++++++++++++++ .../event/web/rest/EventResourceIT.java | 481 ++++++++++++++++ .../web/rest/RegistrationResourceIT.java | 514 ++++++++++++++++++ 80 files changed, 7291 insertions(+), 1 deletion(-) create mode 100644 .jhipster/Charge.json create mode 100644 .jhipster/Event.json create mode 100644 .jhipster/Registration.json create mode 100644 domain.jdl create mode 100644 src/main/java/com/sasiedzi/event/domain/Charge.java create mode 100644 src/main/java/com/sasiedzi/event/domain/Event.java create mode 100644 src/main/java/com/sasiedzi/event/domain/Registration.java create mode 100644 src/main/java/com/sasiedzi/event/domain/enumeration/ChargeType.java create mode 100644 src/main/java/com/sasiedzi/event/domain/enumeration/package-info.java create mode 100644 src/main/java/com/sasiedzi/event/repository/ChargeRepository.java create mode 100644 src/main/java/com/sasiedzi/event/repository/EventRepository.java create mode 100644 src/main/java/com/sasiedzi/event/repository/RegistrationRepository.java create mode 100644 src/main/java/com/sasiedzi/event/service/EventService.java create mode 100644 src/main/java/com/sasiedzi/event/web/rest/ChargeResource.java create mode 100644 src/main/java/com/sasiedzi/event/web/rest/EventResource.java create mode 100644 src/main/java/com/sasiedzi/event/web/rest/RegistrationResource.java create mode 100644 src/main/resources/config/liquibase/changelog/20241105091001_added_entity_Charge.xml create mode 100644 src/main/resources/config/liquibase/changelog/20241105091001_added_entity_constraints_Charge.xml create mode 100644 src/main/resources/config/liquibase/changelog/20241105091002_added_entity_Event.xml create mode 100644 src/main/resources/config/liquibase/changelog/20241105091003_added_entity_Registration.xml create mode 100644 src/main/resources/config/liquibase/changelog/20241105091003_added_entity_constraints_Registration.xml create mode 100644 src/main/resources/config/liquibase/fake-data/blob/hipster.png create mode 100644 src/main/resources/config/liquibase/fake-data/blob/hipster.txt create mode 100644 src/main/resources/config/liquibase/fake-data/charge.csv create mode 100644 src/main/resources/config/liquibase/fake-data/event.csv create mode 100644 src/main/resources/config/liquibase/fake-data/registration.csv create mode 100644 src/main/webapp/app/entities/charge/charge-details.component.spec.ts create mode 100644 src/main/webapp/app/entities/charge/charge-details.component.ts create mode 100644 src/main/webapp/app/entities/charge/charge-details.vue create mode 100644 src/main/webapp/app/entities/charge/charge-update.component.spec.ts create mode 100644 src/main/webapp/app/entities/charge/charge-update.component.ts create mode 100644 src/main/webapp/app/entities/charge/charge-update.vue create mode 100644 src/main/webapp/app/entities/charge/charge.component.spec.ts create mode 100644 src/main/webapp/app/entities/charge/charge.component.ts create mode 100644 src/main/webapp/app/entities/charge/charge.service.spec.ts create mode 100644 src/main/webapp/app/entities/charge/charge.service.ts create mode 100644 src/main/webapp/app/entities/charge/charge.vue create mode 100644 src/main/webapp/app/entities/event/event-details.component.spec.ts create mode 100644 src/main/webapp/app/entities/event/event-details.component.ts create mode 100644 src/main/webapp/app/entities/event/event-details.vue create mode 100644 src/main/webapp/app/entities/event/event-update.component.spec.ts create mode 100644 src/main/webapp/app/entities/event/event-update.component.ts create mode 100644 src/main/webapp/app/entities/event/event-update.vue create mode 100644 src/main/webapp/app/entities/event/event.component.spec.ts create mode 100644 src/main/webapp/app/entities/event/event.component.ts create mode 100644 src/main/webapp/app/entities/event/event.service.spec.ts create mode 100644 src/main/webapp/app/entities/event/event.service.ts create mode 100644 src/main/webapp/app/entities/event/event.vue create mode 100644 src/main/webapp/app/entities/registration/registration-details.component.spec.ts create mode 100644 src/main/webapp/app/entities/registration/registration-details.component.ts create mode 100644 src/main/webapp/app/entities/registration/registration-details.vue create mode 100644 src/main/webapp/app/entities/registration/registration-update.component.spec.ts create mode 100644 src/main/webapp/app/entities/registration/registration-update.component.ts create mode 100644 src/main/webapp/app/entities/registration/registration-update.vue create mode 100644 src/main/webapp/app/entities/registration/registration.component.spec.ts create mode 100644 src/main/webapp/app/entities/registration/registration.component.ts create mode 100644 src/main/webapp/app/entities/registration/registration.service.spec.ts create mode 100644 src/main/webapp/app/entities/registration/registration.service.ts create mode 100644 src/main/webapp/app/entities/registration/registration.vue create mode 100644 src/main/webapp/app/shared/model/charge.model.ts create mode 100644 src/main/webapp/app/shared/model/enumerations/charge-type.model.ts create mode 100644 src/main/webapp/app/shared/model/event.model.ts create mode 100644 src/main/webapp/app/shared/model/registration.model.ts create mode 100644 src/test/java/com/sasiedzi/event/domain/ChargeAsserts.java create mode 100644 src/test/java/com/sasiedzi/event/domain/ChargeTest.java create mode 100644 src/test/java/com/sasiedzi/event/domain/ChargeTestSamples.java create mode 100644 src/test/java/com/sasiedzi/event/domain/EventAsserts.java create mode 100644 src/test/java/com/sasiedzi/event/domain/EventTest.java create mode 100644 src/test/java/com/sasiedzi/event/domain/EventTestSamples.java create mode 100644 src/test/java/com/sasiedzi/event/domain/RegistrationAsserts.java create mode 100644 src/test/java/com/sasiedzi/event/domain/RegistrationTest.java create mode 100644 src/test/java/com/sasiedzi/event/domain/RegistrationTestSamples.java create mode 100644 src/test/java/com/sasiedzi/event/web/rest/ChargeResourceIT.java create mode 100644 src/test/java/com/sasiedzi/event/web/rest/EventResourceIT.java create mode 100644 src/test/java/com/sasiedzi/event/web/rest/RegistrationResourceIT.java diff --git a/.jhipster/Charge.json b/.jhipster/Charge.json new file mode 100644 index 0000000..c861a79 --- /dev/null +++ b/.jhipster/Charge.json @@ -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" +} diff --git a/.jhipster/Event.json b/.jhipster/Event.json new file mode 100644 index 0000000..68c4e04 --- /dev/null +++ b/.jhipster/Event.json @@ -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" +} diff --git a/.jhipster/Registration.json b/.jhipster/Registration.json new file mode 100644 index 0000000..ccb7d33 --- /dev/null +++ b/.jhipster/Registration.json @@ -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" +} diff --git a/.yo-rc.json b/.yo-rc.json index 4abed7e..d83b33c 100644 --- a/.yo-rc.json +++ b/.yo-rc.json @@ -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": [], diff --git a/domain.jdl b/domain.jdl new file mode 100644 index 0000000..909491c --- /dev/null +++ b/domain.jdl @@ -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 * diff --git a/src/main/java/com/sasiedzi/event/domain/Charge.java b/src/main/java/com/sasiedzi/event/domain/Charge.java new file mode 100644 index 0000000..74cc1de --- /dev/null +++ b/src/main/java/com/sasiedzi/event/domain/Charge.java @@ -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() + + "}"; + } +} diff --git a/src/main/java/com/sasiedzi/event/domain/Event.java b/src/main/java/com/sasiedzi/event/domain/Event.java new file mode 100644 index 0000000..2a6083d --- /dev/null +++ b/src/main/java/com/sasiedzi/event/domain/Event.java @@ -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 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 getRegistrations() { + return this.registrations; + } + + public void setRegistrations(Set 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 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() + "'" + + "}"; + } +} diff --git a/src/main/java/com/sasiedzi/event/domain/Registration.java b/src/main/java/com/sasiedzi/event/domain/Registration.java new file mode 100644 index 0000000..70aa207 --- /dev/null +++ b/src/main/java/com/sasiedzi/event/domain/Registration.java @@ -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() + "'" + + "}"; + } +} diff --git a/src/main/java/com/sasiedzi/event/domain/enumeration/ChargeType.java b/src/main/java/com/sasiedzi/event/domain/enumeration/ChargeType.java new file mode 100644 index 0000000..cd707ce --- /dev/null +++ b/src/main/java/com/sasiedzi/event/domain/enumeration/ChargeType.java @@ -0,0 +1,9 @@ +package com.sasiedzi.event.domain.enumeration; + +/** + * The ChargeType enumeration. + */ +public enum ChargeType { + CHARGE, + PAYMENT, +} diff --git a/src/main/java/com/sasiedzi/event/domain/enumeration/package-info.java b/src/main/java/com/sasiedzi/event/domain/enumeration/package-info.java new file mode 100644 index 0000000..d21ccc5 --- /dev/null +++ b/src/main/java/com/sasiedzi/event/domain/enumeration/package-info.java @@ -0,0 +1,4 @@ +/** + * This package file was generated by JHipster + */ +package com.sasiedzi.event.domain.enumeration; diff --git a/src/main/java/com/sasiedzi/event/repository/ChargeRepository.java b/src/main/java/com/sasiedzi/event/repository/ChargeRepository.java new file mode 100644 index 0000000..6f89161 --- /dev/null +++ b/src/main/java/com/sasiedzi/event/repository/ChargeRepository.java @@ -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 { + @Query("select charge from Charge charge where charge.user.login = ?#{authentication.name}") + List findByUserIsCurrentUser(); + + default Optional findOneWithEagerRelationships(Long id) { + return this.findOneWithToOneRelationships(id); + } + + default List findAllWithEagerRelationships() { + return this.findAllWithToOneRelationships(); + } + + default Page 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 findAllWithToOneRelationships(Pageable pageable); + + @Query("select charge from Charge charge left join fetch charge.user") + List findAllWithToOneRelationships(); + + @Query("select charge from Charge charge left join fetch charge.user where charge.id =:id") + Optional findOneWithToOneRelationships(@Param("id") Long id); +} diff --git a/src/main/java/com/sasiedzi/event/repository/EventRepository.java b/src/main/java/com/sasiedzi/event/repository/EventRepository.java new file mode 100644 index 0000000..c9f00e1 --- /dev/null +++ b/src/main/java/com/sasiedzi/event/repository/EventRepository.java @@ -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 {} diff --git a/src/main/java/com/sasiedzi/event/repository/RegistrationRepository.java b/src/main/java/com/sasiedzi/event/repository/RegistrationRepository.java new file mode 100644 index 0000000..545523a --- /dev/null +++ b/src/main/java/com/sasiedzi/event/repository/RegistrationRepository.java @@ -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 { + @Query("select registration from Registration registration where registration.user.login = ?#{authentication.name}") + List findByUserIsCurrentUser(); + + default Optional findOneWithEagerRelationships(Long id) { + return this.findOneWithToOneRelationships(id); + } + + default List findAllWithEagerRelationships() { + return this.findAllWithToOneRelationships(); + } + + default Page 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 findAllWithToOneRelationships(Pageable pageable); + + @Query("select registration from Registration registration left join fetch registration.user left join fetch registration.event") + List findAllWithToOneRelationships(); + + @Query( + "select registration from Registration registration left join fetch registration.user left join fetch registration.event where registration.id =:id" + ) + Optional findOneWithToOneRelationships(@Param("id") Long id); +} diff --git a/src/main/java/com/sasiedzi/event/service/EventService.java b/src/main/java/com/sasiedzi/event/service/EventService.java new file mode 100644 index 0000000..77b84da --- /dev/null +++ b/src/main/java/com/sasiedzi/event/service/EventService.java @@ -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 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 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 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); + } +} diff --git a/src/main/java/com/sasiedzi/event/web/rest/ChargeResource.java b/src/main/java/com/sasiedzi/event/web/rest/ChargeResource.java new file mode 100644 index 0000000..46f4151 --- /dev/null +++ b/src/main/java/com/sasiedzi/event/web/rest/ChargeResource.java @@ -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 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 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 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 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 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 getCharge(@PathVariable("id") Long id) { + LOG.debug("REST request to get Charge : {}", id); + Optional 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 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(); + } +} diff --git a/src/main/java/com/sasiedzi/event/web/rest/EventResource.java b/src/main/java/com/sasiedzi/event/web/rest/EventResource.java new file mode 100644 index 0000000..77977ec --- /dev/null +++ b/src/main/java/com/sasiedzi/event/web/rest/EventResource.java @@ -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 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 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 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 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 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 getEvent(@PathVariable("id") Long id) { + LOG.debug("REST request to get Event : {}", id); + Optional 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 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(); + } +} diff --git a/src/main/java/com/sasiedzi/event/web/rest/RegistrationResource.java b/src/main/java/com/sasiedzi/event/web/rest/RegistrationResource.java new file mode 100644 index 0000000..6010abc --- /dev/null +++ b/src/main/java/com/sasiedzi/event/web/rest/RegistrationResource.java @@ -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 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 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 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 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 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 getRegistration(@PathVariable("id") Long id) { + LOG.debug("REST request to get Registration : {}", id); + Optional 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 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(); + } +} diff --git a/src/main/resources/config/liquibase/changelog/20241105091001_added_entity_Charge.xml b/src/main/resources/config/liquibase/changelog/20241105091001_added_entity_Charge.xml new file mode 100644 index 0000000..9856a87 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20241105091001_added_entity_Charge.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20241105091001_added_entity_constraints_Charge.xml b/src/main/resources/config/liquibase/changelog/20241105091001_added_entity_constraints_Charge.xml new file mode 100644 index 0000000..aca1514 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20241105091001_added_entity_constraints_Charge.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20241105091002_added_entity_Event.xml b/src/main/resources/config/liquibase/changelog/20241105091002_added_entity_Event.xml new file mode 100644 index 0000000..fca9251 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20241105091002_added_entity_Event.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20241105091003_added_entity_Registration.xml b/src/main/resources/config/liquibase/changelog/20241105091003_added_entity_Registration.xml new file mode 100644 index 0000000..66b951a --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20241105091003_added_entity_Registration.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20241105091003_added_entity_constraints_Registration.xml b/src/main/resources/config/liquibase/changelog/20241105091003_added_entity_constraints_Registration.xml new file mode 100644 index 0000000..30c9fda --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20241105091003_added_entity_constraints_Registration.xml @@ -0,0 +1,27 @@ + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/fake-data/blob/hipster.png b/src/main/resources/config/liquibase/fake-data/blob/hipster.png new file mode 100644 index 0000000000000000000000000000000000000000..5b7d50756b00d556bd39a082e16e28a041caa150 GIT binary patch literal 7564 zcmb_>^;aBCw{;JL3=$Y5xD$ee;0}R-;O@aKK|*j#LXg3NOK^wa5Foe)hXDqHI{^lF z0z9~Wyw82Vb^n3eYuE0xPwjJhRadRmKXjOen*0+SN*n+Ho+v8FXg%IL{xcxpN47%C z5C8zQI}H^b*+)58ny0L1UzQr!Toh545?mSWTN&$Hml#wT<69FKQ1uP|AH@3oO8wfD z6jT-aI18_f4`@gVu88t}^gQA*Sr*|_8z1m!dz6UpQPuyJJeGfU{Wy>pGf|e@l^Omx zTOH?L9^o}xnKoP$Ulj{)PY?YO_OUd?qa!zds491?zIeK&yeTcbuQYw*cgNq^p??;~ z&R1tH*JqFBhyQfd{mP0)^)(+(BhOHimuu7KD^sV-6DNO0k>%NYlYOU4V{6FP;hKW& z(Vp4%s-B{h>y5eMAlK97$?LVLoIX4}+~3_j9BU(@> zd~)ieXLq>kv37T~TQ{a}b8;x7Y!KPrEF9D+6*>60a1r0e@unYTRsFKx#zX?zA2W~W z%#Cl&j+T5IcD^!svN-z4OT)db^;J{-9nlF%)j!KKGBcCYGvriE6x7X>b?xNU%pWl` zGtVQgt)OnMsA2Ix_%}9JRR6D(kTcXbbx_r{QPO(%AA`Dug67-*aX#Z!QFxRZ7Q`%a zkD139poGc2ae~q>4+?uhoH9=rvkU*Vl%a%leF`U6ZWgP* zdC0NYw*8yE3bP2jeQ+6gI7z4gC$+tn$7Mi+tuUkTYt4b$1N5_!?EoWx5@gH_llHEhcXViou zBfM`faJ$2>Rg(;?r=wjjFMm}yLo6nL?#f-7P6YDI6VB(BksGY{cfF~uXF!+QV^H&4 zIN%Hme(Bpzs4tIS#jfnOeuYif`4PPAG8vAZ@SqRJ(YD?<2TC}MuAxQPY1 za$cWBj-h1IK!A(DDX7QH@nPs2O1S~~z1Tvf6g$)4GZuIfa7SmjaX3eZ2DPm<6n|zF z-6{WM=6hCr>CGE`83N@%))XuMGsMLs+8TP(yB1Fke-97+ob>jlY`0m;mz0sXTSRMY z^?1(i^@z9X^V_0oPG>y2oZp6SMw9+Wf2AfM7MhDKfB|*qMJhG1F{uZ%WE*c^?y}qo zG?w5ItbU0|eu}KhleK}CT%xUC8e9x94FbOqMV^!Q?ptb;83hWs$9|yWP>p1VfYGFG zOeSdqn?GXivFuMddmhNQZ0w(1=|92D(X{cHGk+KosnNA)WcQUbtG(UFdIH<~AjwfT zac&~}0vY2zqY#YsLSZ%U8y2JTz&<|OQV8ik!IgO`C6gq>@mKLew#(ff#--xSCluUuiZ_xN>ns+RoDz);Xvr-WrMG9TaJ zywxKsFIU9ciTq)kS3&SP{?rtIS)Rj!_&F+p$LWE4|BDvY_YlKn6iEJ;~k~1 zX%jM4dZBj@mfUL!r!IE)0=jTn2Wz)4Jq+kimN#k_OKdUkFKubmam&d&%69NREw9Zq zIVOJaC7p|*a9me#_|4y5JJZj^H+v^AddcNI{BUGVyIZ~>3JfHBk!gmrozL8XC8%wfj(0|9G5Mb8x-0Bw*jx!(L;a}RokfV@2N}ynpw2nQZokgEz zN{Lx&n8)#B^ZPVU-eJHI>h1jmDjtHS7|ScibDZVx5{cdQ!jF1cPTxRXB;w0^)6-yg zM$B%)7P(Jg#cexhzl*lB&HV?Wb$-gag}nZ`P-d{q(`0qUmmD-96J>l^tS^H#r^AR` zccHBQgLbI-<{Om5_S`>P+*Bi25%=b8`}Npc5DkhLU06dL@_NdZK3}7rWTVH28=qlK z!I58<0c1=?k_`aWONIMY+{-ZfF=T&>s;5b$ov>t(Re9V>GeJq9LpKI}dx95g;@ zYele1Kj|$zNQ4l18(H&CNAimY^E6KDl53C~%k>fY5ndLjG~6Lyr0O?Mg0F-=K}+V6 zXZ?Ix(RJZjU0W@ima8Xbd92UQgaH%IuOCyvE)voO{H5>Mj?1pWRdSqf<%XxHL2I)# z2Qhu@F#Q%M$J95$r94@i>OF=cbeV*Wuasf%BC}mlyp*zyRRWHhU9Pai__PlBP6GAs zxu}&xzw8;SNMWq%Qqa!eXO$Ix!d83_bafU*h^;uGo&W=GlS~jwV!h}yniD=&te`8f z6w#cK@wDa$fRFtW0eJdZGiu#e0Ewtw5>aAgDI(gudqvXa`vn#}D7rvbHSB4;Xf%UM z{G3lQ$El__WW}Do%uY=uW=bAb0Ck3!`VDG!6t;SivL1h%9k;-lZUu3eva zI0HE@43w`xtjcMYK- z(uQq_j{EZS)?BM?dya5chq&~SP@mcIVhCnqG1?T=y0BNAE+#p?EooCwTA-kWkxs16 zgGWGXCVcvI;fCJ%BMrd{kYl$wtC6MFWk_)1E*Q>~kC*2u^j9p%Xj6IZoRo(b!5SuC z!=J5W;Xs29y)Nzk4K^dhg7ZrbTW&ahPuCn~lU1RYLR7uVK>pzW5ZrI`ZQ?ahB*(TT zti3tg}FG{`7F*)BDHusg7t=+XBPJSq-5xNWHjpv3MCt7p@C6C z$l3U$Yt_@>A8$byhA*)?rD+a`q2cj(&kFaB&6d z{OlZvk<GFtP<_hh$XE`iApjvl5*;a?#$!2vvoKt zFIYOM;IjacHFWHGt@dnmA8Zmm5=3nWbVLJj$u zW83<0567G-X6FlnwYy9x1Hu+ed?l{Rmv7Hcw#CC8&4#F{n;|kxyQ)lPPC&fX-1?3# z{gd?JZ`L26`heg0^{31nu zZY|Bci1Qak*7-?=0b%=u(~S#-2n>xsAZ8MX-6#+RwQYUzG$x zEMT30vu@r`ZC%vT zj==jQ4F2}Y#>$?<4Z?FE_Lk#lBe8d?j)*Dcn=u7!+zTWjXM9VQZbT&Q2v@wkZ}iZQ;4cqrHi)6izrBj*A zq4ru@`k1psp&ir!9M6aC4YFciW0Xn3FsqU8sL#UcAAKFdx@(*e9jPF30LEei8Zv5F zXd-Ih$M2}c1U`y`G>(ocjR_M2p3j4xUV~;A!M?2D$LG6fpX?u2YfBee_vETHsQhO8 zUhw7Odr;RQ(JK3dlkErO40~}vGzbMv>&Ocu@PuLg3KM}_yFPxV=X*YOdM2FNuSSG~ z)PAK69e~CEUCDb1Txxq-0gQQRlAIPkUox*pI)KfV{-VKYG2ul7!DukzMj%$TV|AooupQslE(}_|y0X5vpJdKDP zk)sSSwP_i+@yxO;erH4ZygmMdOpDbNn7lzd)7Zv7umO_;a4v*5iU2_G>w7{!Grf=A4#R`ifPAR(egruYMw^H)COlkMrjTa8>~Qs+O1+aiP_smkBt@>b-Y^ zS}gT@TjkNBx1-DU%zZCx1N*qDqXx+c3mNUUiY3bTCTPcZaDPGq`il=d!A3;(G?Qq5 zLjryU8wG(nyyh#u*TZt2ysdLv*L_`p@+Jt)u-Q`}OzqIEbbzdKNwS5DH`rdd#NPh% z&y*jSSMRCrd)CnGu#69{(eoZsnsAn8qv)wMf}L>AP0^>5T7pgJu6iXFL>8LF==7c@ zH+6+0IXL2(N+MU!dH8M{toK`E&d*3hNPI$NQ6<)Qu7@pn3^p4t^StVhZie%4? zf5?C0SOyyre7uk*!El%%j`xbAl_pENnCUt`M9d?E!epzWCdId99;Dokj>_)lX^wTK~dd-f96dRD|qVsz5d{iQ-lPX;Z;ll2kN9|pb zJXS7esB5n#tKMO%%=yJCbb~rBg2wR-QC>>-RkQG} zp7%^Nc8w*=cV&Alz6j^&pO*Tb`5-)5J*EalXBRITXJ zwls$|@feL+n4qZ{0ox1F>X4xzS8d{DSAWE*+q|Gqte9K@@QytQl1Q~Pt`+Dk2UiQW z>tsKaR)VKTW7M3P4O~+yD`RYo=nd-fqVChA@StZr$Q6V{{Ca&pTkhLDnnA}Ru~F*n zNJk2raQ!dAKh!C;$jf)ogE?NZKoH=PjU{|k9V=wNLq47Qn3B41kITaqgZT1Js=PW; z)m3-x+I+8t76_}Ew9*mbe)Ze@-N9>OSJoXEHBlO)lu{H{m zMAB52ebf^KhsIV}?F!4`m25~GRrTBo!qhG`W+!-b`eEcYX%&0!cC!LH#p}iJ+`FA1 zK7_D5gXUt)+U(DnG+L_+*79wv^;a;(`VRUhBmWF(7Ht}a^$7X4mavg4giZV^Mg7Ht zr!LcT?;czZ6~w_n!>t(s-k<5`@uzR)5S-r{k$E2oC&V^-F_kqTu&F(?a4N? zZgL90HNwMy?+GXuLfh8TB3V~MkaM3M;0bZ;d*l!&_pdH;^qx1*S1`$Y)h+wo%rw3$ zVRi_Qy>cVYQWMr5`IWF$d1ay4{7ZN1U6Pa!emwhFlclC+9}#!(cl2l=pWn1BMtMx-D( za6Wg9idy;uXB6A_yE%o!R?|XKI z$;~-(szFH^HF`0lBEmVnkw6$ccb>1wGNH|G6QJQL~bvmg(K_F}!59iiNm5Gu^^^;s}Ex%Zz zkQ5wF!DAUwUzYKk0sws;8!f|114Z;k%1V+_=F%7?IrLR>K!t1gV0f0~peJx<7rb6#psp+B3!hS97SI+h|k20yWfW}fxTKlf--F$VX7fanc16Bb0wYAzZ zc%bjlgfye^OfYO38||vID36udt$(Lc{CE zU*u1qVOEtFTXxSYJzG(j|J2)q8Cyrb;(0(0%fpsa2MXh$AflpZ*TcX>&)T{pPh$&HP`3%L7;5wf|*I>mV zoEDJnLUWrg!%$Vr);+D4tU0;YwBs6nTmd3-Y;UC%u@0edie)e0u!{6F4(hAyWF(5h zBT0lE)xhZE&~ZxL7PNb9@&~ttg`Wx&&TU>7bJEfI*8M4pWO|jE?=q5i(ij(BXiH#e zB+)!-^tFjw&(peE^;+P9m5l_yfRKE4hwql2(mqL(P`%K zFh9|K&D{|O3t5p&%zFd7RVW{!kpIMU4U@}y=%|n>*q#nEOO-f0*UB0*@9^g{bdrtM z107|bRXbZ*Y+RzHNA&YCwEVLvc$>_ng7#%D%O1_;r6!_AKu1{g*0~(@l%`qswDT`n zk8zCC0KuJWfPYQN#LKnve0$u#Uu15nd@K$^Ex_B7By&qkUG%JQ}S&&n~FEsFpd%Xf?ZWk=lwXZlI^p8$hZkC5u}khP*xEQ z(kd)_N#=Wupt^bZQvML~u21W9#)&fOZ^N++pTIGnI}$@UZ!cPJw>opKnIMxEM?KAb;IoGJOaPX^Jt!m9E12G|eb~Bktb6f6bp|bA zhus&v=zwTw-iy2W8i=jcC?5%eh!D$2+~vwr!o#T6{~6t_oxWCVP+3G%I-g-o|KfZq zVIC67RGIViiZWCS*5MoY8`S5FORC}PZX=(@Vireb4*xo^Aj1rPGRlOa3S8U~KaC%_ zU)#j2h^F&`n4>cb>t*4To1W@lk=KbP_Z<=Zfj| z+y}jgnt>H68O(s@KO3EkZq!&r#X8DFU2RLu9mr(9P*(I6OyeBXF?rGh4eh$B!^ULg zM>`V>Tv5;if2AK#Ux$vi#}nZ}dGSs%UF4wEBc)}mgGDJ5a8pcnTnIO?u=eZMYKRSM z(dC7$Wrub{sB1x)S$6yr>fNvJp`&}}W*Y=wKTi@!rV9PZyApT@&99l> zo~Wj#h65|tdx5rWTp=E<{$pxz4OFw$-#{aX%<+VgxWsH4YODti<_$(f?Cu;VVoBse zI+$<)2x}rNywImElo;rN!kRn>Z=TFH-WrfZe{xfJ$RNXz^?7c}mYZ9^RSR;VWO!Je zmAGoWtqEZcnEB(s9FW`QKW1>m))n{b;d}7K=-a+5%@O0P#;Z0V>>LdJXI2Q9qf~=B z_KKUVit@C@d9AnL`T7l^3r@R^fcSCFC$6|l9XV7727wkLqHJJ)&^ML;cX$R^F literal 0 HcmV?d00001 diff --git a/src/main/resources/config/liquibase/fake-data/blob/hipster.txt b/src/main/resources/config/liquibase/fake-data/blob/hipster.txt new file mode 100644 index 0000000..3bf9d1e --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/blob/hipster.txt @@ -0,0 +1 @@ +JHipster is a development platform to generate, develop and deploy Spring Boot + Angular / React / Vue Web applications and Spring microservices. \ No newline at end of file diff --git a/src/main/resources/config/liquibase/fake-data/charge.csv b/src/main/resources/config/liquibase/fake-data/charge.csv new file mode 100644 index 0000000..d0e7b4b --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/charge.csv @@ -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 diff --git a/src/main/resources/config/liquibase/fake-data/event.csv b/src/main/resources/config/liquibase/fake-data/event.csv new file mode 100644 index 0000000..8eb58de --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/event.csv @@ -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 diff --git a/src/main/resources/config/liquibase/fake-data/registration.csv b/src/main/resources/config/liquibase/fake-data/registration.csv new file mode 100644 index 0000000..81f36e9 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/registration.csv @@ -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 diff --git a/src/main/resources/config/liquibase/master.xml b/src/main/resources/config/liquibase/master.xml index 7e23350..512c6fb 100644 --- a/src/main/resources/config/liquibase/master.xml +++ b/src/main/resources/config/liquibase/master.xml @@ -11,7 +11,12 @@ + + + + + diff --git a/src/main/webapp/app/entities/charge/charge-details.component.spec.ts b/src/main/webapp/app/entities/charge/charge-details.component.spec.ts new file mode 100644 index 0000000..a14d732 --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge-details.component.spec.ts @@ -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; + +let route: Partial; +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; + let mountOptions: MountingOptions['global']; + + beforeEach(() => { + route = {}; + chargeServiceStub = sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/charge/charge-details.component.ts b/src/main/webapp/app/entities/charge/charge-details.component.ts new file mode 100644 index 0000000..699b8fb --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge-details.component.ts @@ -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 = 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, + }; + }, +}); diff --git a/src/main/webapp/app/entities/charge/charge-details.vue b/src/main/webapp/app/entities/charge/charge-details.vue new file mode 100644 index 0000000..d318312 --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge-details.vue @@ -0,0 +1,63 @@ + + + diff --git a/src/main/webapp/app/entities/charge/charge-update.component.spec.ts b/src/main/webapp/app/entities/charge/charge-update.component.spec.ts new file mode 100644 index 0000000..6fbe1ec --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge-update.component.spec.ts @@ -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; + +let route: Partial; +const routerGoMock = vitest.fn(); + +vitest.mock('vue-router', () => ({ + useRoute: () => route, + useRouter: () => ({ go: routerGoMock }), +})); + +const chargeSample = { id: 123 }; + +describe('Component Tests', () => { + let mountOptions: MountingOptions['global']; + let alertService: AlertService; + + describe('Charge Management Update Component', () => { + let comp: ChargeUpdateComponentType; + let chargeServiceStub: SinonStubbedInstance; + + beforeEach(() => { + route = {}; + chargeServiceStub = sinon.createStubInstance(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, { + retrieve: sinon.stub().resolves({}), + } as any), + registrationService: () => + sinon.createStubInstance(RegistrationService, { + retrieve: sinon.stub().resolves({}), + } as any), + + userService: () => + sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/charge/charge-update.component.ts b/src/main/webapp/app/entities/charge/charge-update.component.ts new file mode 100644 index 0000000..5dbf208 --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge-update.component.ts @@ -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 = ref(new Charge()); + + const eventService = inject('eventService', () => new EventService()); + + const events: Ref = ref([]); + + const registrationService = inject('registrationService', () => new RegistrationService()); + + const registrations: Ref = ref([]); + const userService = inject('userService', () => new UserService()); + const users: Ref> = ref([]); + const chargeTypeValues: Ref = 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); + }); + } + }, + }, +}); diff --git a/src/main/webapp/app/entities/charge/charge-update.vue b/src/main/webapp/app/entities/charge/charge-update.vue new file mode 100644 index 0000000..60fc62e --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge-update.vue @@ -0,0 +1,134 @@ + + diff --git a/src/main/webapp/app/entities/charge/charge.component.spec.ts b/src/main/webapp/app/entities/charge/charge.component.spec.ts new file mode 100644 index 0000000..6017ee8 --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge.component.spec.ts @@ -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; + +const bModalStub = { + render: () => {}, + methods: { + hide: () => {}, + show: () => {}, + }, +}; + +describe('Component Tests', () => { + let alertService: AlertService; + + describe('Charge Management Component', () => { + let chargeServiceStub: SinonStubbedInstance; + let mountOptions: MountingOptions['global']; + + beforeEach(() => { + chargeServiceStub = sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/charge/charge.component.ts b/src/main/webapp/app/entities/charge/charge.component.ts new file mode 100644 index 0000000..0f2b1fd --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge.component.ts @@ -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 = 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 = ref(null); + const removeEntity = ref(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, + }; + }, +}); diff --git a/src/main/webapp/app/entities/charge/charge.service.spec.ts b/src/main/webapp/app/entities/charge/charge.service.spec.ts new file mode 100644 index 0000000..8a812a7 --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge.service.spec.ts @@ -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); + }); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/charge/charge.service.ts b/src/main/webapp/app/entities/charge/charge.service.ts new file mode 100644 index 0000000..dbed4b7 --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge.service.ts @@ -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 { + return new Promise((resolve, reject) => { + axios + .get(`${baseApiUrl}/${id}`) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public retrieve(): Promise { + return new Promise((resolve, reject) => { + axios + .get(baseApiUrl) + .then(res => { + resolve(res); + }) + .catch(err => { + reject(err); + }); + }); + } + + public delete(id: number): Promise { + return new Promise((resolve, reject) => { + axios + .delete(`${baseApiUrl}/${id}`) + .then(res => { + resolve(res); + }) + .catch(err => { + reject(err); + }); + }); + } + + public create(entity: ICharge): Promise { + return new Promise((resolve, reject) => { + axios + .post(`${baseApiUrl}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public update(entity: ICharge): Promise { + return new Promise((resolve, reject) => { + axios + .put(`${baseApiUrl}/${entity.id}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public partialUpdate(entity: ICharge): Promise { + return new Promise((resolve, reject) => { + axios + .patch(`${baseApiUrl}/${entity.id}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } +} diff --git a/src/main/webapp/app/entities/charge/charge.vue b/src/main/webapp/app/entities/charge/charge.vue new file mode 100644 index 0000000..da38896 --- /dev/null +++ b/src/main/webapp/app/entities/charge/charge.vue @@ -0,0 +1,118 @@ + + + diff --git a/src/main/webapp/app/entities/entities-menu.vue b/src/main/webapp/app/entities/entities-menu.vue index 22b4569..242733a 100644 --- a/src/main/webapp/app/entities/entities-menu.vue +++ b/src/main/webapp/app/entities/entities-menu.vue @@ -1,5 +1,17 @@ diff --git a/src/main/webapp/app/entities/entities.component.ts b/src/main/webapp/app/entities/entities.component.ts index 09089af..8593ff2 100644 --- a/src/main/webapp/app/entities/entities.component.ts +++ b/src/main/webapp/app/entities/entities.component.ts @@ -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 }, }); diff --git a/src/main/webapp/app/entities/event/event-details.component.spec.ts b/src/main/webapp/app/entities/event/event-details.component.spec.ts new file mode 100644 index 0000000..be8aaa7 --- /dev/null +++ b/src/main/webapp/app/entities/event/event-details.component.spec.ts @@ -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; + +let route: Partial; +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; + let mountOptions: MountingOptions['global']; + + beforeEach(() => { + route = {}; + eventServiceStub = sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/event/event-details.component.ts b/src/main/webapp/app/entities/event/event-details.component.ts new file mode 100644 index 0000000..0642abf --- /dev/null +++ b/src/main/webapp/app/entities/event/event-details.component.ts @@ -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 = 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, + }; + }, +}); diff --git a/src/main/webapp/app/entities/event/event-details.vue b/src/main/webapp/app/entities/event/event-details.vue new file mode 100644 index 0000000..33f015f --- /dev/null +++ b/src/main/webapp/app/entities/event/event-details.vue @@ -0,0 +1,51 @@ + + + diff --git a/src/main/webapp/app/entities/event/event-update.component.spec.ts b/src/main/webapp/app/entities/event/event-update.component.spec.ts new file mode 100644 index 0000000..fd2922c --- /dev/null +++ b/src/main/webapp/app/entities/event/event-update.component.spec.ts @@ -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; + +let route: Partial; +const routerGoMock = vitest.fn(); + +vitest.mock('vue-router', () => ({ + useRoute: () => route, + useRouter: () => ({ go: routerGoMock }), +})); + +const eventSample = { id: 123 }; + +describe('Component Tests', () => { + let mountOptions: MountingOptions['global']; + let alertService: AlertService; + + describe('Event Management Update Component', () => { + let comp: EventUpdateComponentType; + let eventServiceStub: SinonStubbedInstance; + + beforeEach(() => { + route = {}; + eventServiceStub = sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/event/event-update.component.ts b/src/main/webapp/app/entities/event/event-update.component.ts new file mode 100644 index 0000000..ebc67aa --- /dev/null +++ b/src/main/webapp/app/entities/event/event-update.component.ts @@ -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 = 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); + }); + } + }, + }, +}); diff --git a/src/main/webapp/app/entities/event/event-update.vue b/src/main/webapp/app/entities/event/event-update.vue new file mode 100644 index 0000000..577d11e --- /dev/null +++ b/src/main/webapp/app/entities/event/event-update.vue @@ -0,0 +1,113 @@ + + diff --git a/src/main/webapp/app/entities/event/event.component.spec.ts b/src/main/webapp/app/entities/event/event.component.spec.ts new file mode 100644 index 0000000..3a9eac7 --- /dev/null +++ b/src/main/webapp/app/entities/event/event.component.spec.ts @@ -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; + +const bModalStub = { + render: () => {}, + methods: { + hide: () => {}, + show: () => {}, + }, +}; + +describe('Component Tests', () => { + let alertService: AlertService; + + describe('Event Management Component', () => { + let eventServiceStub: SinonStubbedInstance; + let mountOptions: MountingOptions['global']; + + beforeEach(() => { + eventServiceStub = sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/event/event.component.ts b/src/main/webapp/app/entities/event/event.component.ts new file mode 100644 index 0000000..c850b0e --- /dev/null +++ b/src/main/webapp/app/entities/event/event.component.ts @@ -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 = 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 = ref(null); + const removeEntity = ref(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, + }; + }, +}); diff --git a/src/main/webapp/app/entities/event/event.service.spec.ts b/src/main/webapp/app/entities/event/event.service.spec.ts new file mode 100644 index 0000000..5857942 --- /dev/null +++ b/src/main/webapp/app/entities/event/event.service.spec.ts @@ -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); + }); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/event/event.service.ts b/src/main/webapp/app/entities/event/event.service.ts new file mode 100644 index 0000000..f93f4bb --- /dev/null +++ b/src/main/webapp/app/entities/event/event.service.ts @@ -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 { + return new Promise((resolve, reject) => { + axios + .get(`${baseApiUrl}/${id}`) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public retrieve(): Promise { + return new Promise((resolve, reject) => { + axios + .get(baseApiUrl) + .then(res => { + resolve(res); + }) + .catch(err => { + reject(err); + }); + }); + } + + public delete(id: number): Promise { + return new Promise((resolve, reject) => { + axios + .delete(`${baseApiUrl}/${id}`) + .then(res => { + resolve(res); + }) + .catch(err => { + reject(err); + }); + }); + } + + public create(entity: IEvent): Promise { + return new Promise((resolve, reject) => { + axios + .post(`${baseApiUrl}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public update(entity: IEvent): Promise { + return new Promise((resolve, reject) => { + axios + .put(`${baseApiUrl}/${entity.id}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public partialUpdate(entity: IEvent): Promise { + return new Promise((resolve, reject) => { + axios + .patch(`${baseApiUrl}/${entity.id}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } +} diff --git a/src/main/webapp/app/entities/event/event.vue b/src/main/webapp/app/entities/event/event.vue new file mode 100644 index 0000000..a2d71a1 --- /dev/null +++ b/src/main/webapp/app/entities/event/event.vue @@ -0,0 +1,104 @@ + + + diff --git a/src/main/webapp/app/entities/registration/registration-details.component.spec.ts b/src/main/webapp/app/entities/registration/registration-details.component.spec.ts new file mode 100644 index 0000000..2cebcf5 --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration-details.component.spec.ts @@ -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; + +let route: Partial; +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; + let mountOptions: MountingOptions['global']; + + beforeEach(() => { + route = {}; + registrationServiceStub = sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/registration/registration-details.component.ts b/src/main/webapp/app/entities/registration/registration-details.component.ts new file mode 100644 index 0000000..c0093bc --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration-details.component.ts @@ -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 = 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, + }; + }, +}); diff --git a/src/main/webapp/app/entities/registration/registration-details.vue b/src/main/webapp/app/entities/registration/registration-details.vue new file mode 100644 index 0000000..1c0c3f3 --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration-details.vue @@ -0,0 +1,66 @@ + + + diff --git a/src/main/webapp/app/entities/registration/registration-update.component.spec.ts b/src/main/webapp/app/entities/registration/registration-update.component.spec.ts new file mode 100644 index 0000000..d9b40bf --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration-update.component.spec.ts @@ -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; + +let route: Partial; +const routerGoMock = vitest.fn(); + +vitest.mock('vue-router', () => ({ + useRoute: () => route, + useRouter: () => ({ go: routerGoMock }), +})); + +const registrationSample = { id: 123 }; + +describe('Component Tests', () => { + let mountOptions: MountingOptions['global']; + let alertService: AlertService; + + describe('Registration Management Update Component', () => { + let comp: RegistrationUpdateComponentType; + let registrationServiceStub: SinonStubbedInstance; + + beforeEach(() => { + route = {}; + registrationServiceStub = sinon.createStubInstance(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, { + retrieve: sinon.stub().resolves({}), + } as any), + eventService: () => + sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/registration/registration-update.component.ts b/src/main/webapp/app/entities/registration/registration-update.component.ts new file mode 100644 index 0000000..c74812f --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration-update.component.ts @@ -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 = ref(new Registration()); + const userService = inject('userService', () => new UserService()); + const users: Ref> = ref([]); + + const eventService = inject('eventService', () => new EventService()); + + const events: Ref = 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); + }); + } + }, + }, +}); diff --git a/src/main/webapp/app/entities/registration/registration-update.vue b/src/main/webapp/app/entities/registration/registration-update.vue new file mode 100644 index 0000000..8877b6d --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration-update.vue @@ -0,0 +1,116 @@ + + diff --git a/src/main/webapp/app/entities/registration/registration.component.spec.ts b/src/main/webapp/app/entities/registration/registration.component.spec.ts new file mode 100644 index 0000000..a5f4bd0 --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration.component.spec.ts @@ -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; + +const bModalStub = { + render: () => {}, + methods: { + hide: () => {}, + show: () => {}, + }, +}; + +describe('Component Tests', () => { + let alertService: AlertService; + + describe('Registration Management Component', () => { + let registrationServiceStub: SinonStubbedInstance; + let mountOptions: MountingOptions['global']; + + beforeEach(() => { + registrationServiceStub = sinon.createStubInstance(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); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/registration/registration.component.ts b/src/main/webapp/app/entities/registration/registration.component.ts new file mode 100644 index 0000000..e72b320 --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration.component.ts @@ -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 = 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 = ref(null); + const removeEntity = ref(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, + }; + }, +}); diff --git a/src/main/webapp/app/entities/registration/registration.service.spec.ts b/src/main/webapp/app/entities/registration/registration.service.spec.ts new file mode 100644 index 0000000..d5aa072 --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration.service.spec.ts @@ -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); + }); + }); + }); + }); +}); diff --git a/src/main/webapp/app/entities/registration/registration.service.ts b/src/main/webapp/app/entities/registration/registration.service.ts new file mode 100644 index 0000000..bc76eb1 --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration.service.ts @@ -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 { + return new Promise((resolve, reject) => { + axios + .get(`${baseApiUrl}/${id}`) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public retrieve(): Promise { + return new Promise((resolve, reject) => { + axios + .get(baseApiUrl) + .then(res => { + resolve(res); + }) + .catch(err => { + reject(err); + }); + }); + } + + public delete(id: number): Promise { + return new Promise((resolve, reject) => { + axios + .delete(`${baseApiUrl}/${id}`) + .then(res => { + resolve(res); + }) + .catch(err => { + reject(err); + }); + }); + } + + public create(entity: IRegistration): Promise { + return new Promise((resolve, reject) => { + axios + .post(`${baseApiUrl}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public update(entity: IRegistration): Promise { + return new Promise((resolve, reject) => { + axios + .put(`${baseApiUrl}/${entity.id}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } + + public partialUpdate(entity: IRegistration): Promise { + return new Promise((resolve, reject) => { + axios + .patch(`${baseApiUrl}/${entity.id}`, entity) + .then(res => { + resolve(res.data); + }) + .catch(err => { + reject(err); + }); + }); + } +} diff --git a/src/main/webapp/app/entities/registration/registration.vue b/src/main/webapp/app/entities/registration/registration.vue new file mode 100644 index 0000000..be344ad --- /dev/null +++ b/src/main/webapp/app/entities/registration/registration.vue @@ -0,0 +1,116 @@ + + + diff --git a/src/main/webapp/app/router/entities.ts b/src/main/webapp/app/router/entities.ts index 6b5929c..7bc13ad 100644 --- a/src/main/webapp/app/router/entities.ts +++ b/src/main/webapp/app/router/entities.ts @@ -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 ], }; diff --git a/src/main/webapp/app/shared/model/charge.model.ts b/src/main/webapp/app/shared/model/charge.model.ts new file mode 100644 index 0000000..7faad9b --- /dev/null +++ b/src/main/webapp/app/shared/model/charge.model.ts @@ -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, + ) {} +} diff --git a/src/main/webapp/app/shared/model/enumerations/charge-type.model.ts b/src/main/webapp/app/shared/model/enumerations/charge-type.model.ts new file mode 100644 index 0000000..967de0f --- /dev/null +++ b/src/main/webapp/app/shared/model/enumerations/charge-type.model.ts @@ -0,0 +1,5 @@ +export enum ChargeType { + CHARGE = 'CHARGE', + + PAYMENT = 'PAYMENT', +} diff --git a/src/main/webapp/app/shared/model/event.model.ts b/src/main/webapp/app/shared/model/event.model.ts new file mode 100644 index 0000000..0059d6f --- /dev/null +++ b/src/main/webapp/app/shared/model/event.model.ts @@ -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, + ) {} +} diff --git a/src/main/webapp/app/shared/model/registration.model.ts b/src/main/webapp/app/shared/model/registration.model.ts new file mode 100644 index 0000000..ec154c5 --- /dev/null +++ b/src/main/webapp/app/shared/model/registration.model.ts @@ -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; + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/ChargeAsserts.java b/src/test/java/com/sasiedzi/event/domain/ChargeAsserts.java new file mode 100644 index 0000000..f4050fd --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/ChargeAsserts.java @@ -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())); + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/ChargeTest.java b/src/test/java/com/sasiedzi/event/domain/ChargeTest.java new file mode 100644 index 0000000..038671d --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/ChargeTest.java @@ -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(); + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/ChargeTestSamples.java b/src/test/java/com/sasiedzi/event/domain/ChargeTestSamples.java new file mode 100644 index 0000000..13e331d --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/ChargeTestSamples.java @@ -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()); + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/EventAsserts.java b/src/test/java/com/sasiedzi/event/domain/EventAsserts.java new file mode 100644 index 0000000..0afd1cd --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/EventAsserts.java @@ -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 + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/EventTest.java b/src/test/java/com/sasiedzi/event/domain/EventTest.java new file mode 100644 index 0000000..6fdc0fb --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/EventTest.java @@ -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(); + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/EventTestSamples.java b/src/test/java/com/sasiedzi/event/domain/EventTestSamples.java new file mode 100644 index 0000000..f5449b4 --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/EventTestSamples.java @@ -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()); + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/RegistrationAsserts.java b/src/test/java/com/sasiedzi/event/domain/RegistrationAsserts.java new file mode 100644 index 0000000..d23f498 --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/RegistrationAsserts.java @@ -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())); + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/RegistrationTest.java b/src/test/java/com/sasiedzi/event/domain/RegistrationTest.java new file mode 100644 index 0000000..2477ede --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/RegistrationTest.java @@ -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(); + } +} diff --git a/src/test/java/com/sasiedzi/event/domain/RegistrationTestSamples.java b/src/test/java/com/sasiedzi/event/domain/RegistrationTestSamples.java new file mode 100644 index 0000000..5276045 --- /dev/null +++ b/src/test/java/com/sasiedzi/event/domain/RegistrationTestSamples.java @@ -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()); + } +} diff --git a/src/test/java/com/sasiedzi/event/web/rest/ChargeResourceIT.java b/src/test/java/com/sasiedzi/event/web/rest/ChargeResourceIT.java new file mode 100644 index 0000000..c7398f5 --- /dev/null +++ b/src/test/java/com/sasiedzi/event/web/rest/ChargeResourceIT.java @@ -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)); + } +} diff --git a/src/test/java/com/sasiedzi/event/web/rest/EventResourceIT.java b/src/test/java/com/sasiedzi/event/web/rest/EventResourceIT.java new file mode 100644 index 0000000..c103d38 --- /dev/null +++ b/src/test/java/com/sasiedzi/event/web/rest/EventResourceIT.java @@ -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)); + } +} diff --git a/src/test/java/com/sasiedzi/event/web/rest/RegistrationResourceIT.java b/src/test/java/com/sasiedzi/event/web/rest/RegistrationResourceIT.java new file mode 100644 index 0000000..bf0c95a --- /dev/null +++ b/src/test/java/com/sasiedzi/event/web/rest/RegistrationResourceIT.java @@ -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)); + } +}