diff --git a/.jhipster/Developer.json b/.jhipster/Developer.json new file mode 100644 index 0000000..3cbec09 --- /dev/null +++ b/.jhipster/Developer.json @@ -0,0 +1,29 @@ +{ + "name": "Developer", + "fields": [ + { + "fieldName": "name", + "javadoc": "开发人员姓名", + "fieldType": "String", + "fieldValidateRules": [ + "required", + "minlength", + "maxlength" + ], + "fieldValidateRulesMinlength": 0, + "fieldValidateRulesMaxlength": 12 + } + ], + "relationships": [], + "changelogDate": "20191019020827", + "javadoc": "开发人员", + "entityTableName": "developer", + "dto": "mapstruct", + "pagination": "pagination", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "readOnly": false, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/Project.json b/.jhipster/Project.json new file mode 100644 index 0000000..cf74082 --- /dev/null +++ b/.jhipster/Project.json @@ -0,0 +1,47 @@ +{ + "name": "Project", + "fields": [ + { + "fieldName": "name", + "javadoc": "项目名称", + "fieldType": "String", + "fieldValidateRules": [ + "required", + "minlength", + "maxlength" + ], + "fieldValidateRulesMinlength": 0, + "fieldValidateRulesMaxlength": 12 + }, + { + "fieldName": "code", + "javadoc": "项目编号", + "fieldType": "String", + "fieldValidateRules": [ + "required", + "minlength", + "maxlength" + ], + "fieldValidateRulesMinlength": 0, + "fieldValidateRulesMaxlength": 64 + }, + { + "fieldName": "desc", + "javadoc": "备注", + "fieldType": "byte[]", + "fieldTypeBlobContent": "text" + } + ], + "relationships": [], + "changelogDate": "20191019020826", + "javadoc": "项目", + "entityTableName": "project", + "dto": "mapstruct", + "pagination": "pagination", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "readOnly": false, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/SubmitRecord.json b/.jhipster/SubmitRecord.json new file mode 100644 index 0000000..210d6f7 --- /dev/null +++ b/.jhipster/SubmitRecord.json @@ -0,0 +1,48 @@ +{ + "name": "SubmitRecord", + "fields": [ + { + "fieldName": "recordDate", + "javadoc": "记录时间", + "fieldType": "LocalDate", + "fieldValidateRules": [ + "required" + ] + }, + { + "fieldName": "cnt", + "javadoc": "代码行数", + "fieldType": "Integer", + "fieldValidateRules": [ + "required" + ] + } + ], + "relationships": [ + { + "relationshipType": "many-to-one", + "otherEntityName": "developer", + "otherEntityRelationshipName": "submitRecord", + "relationshipName": "developer", + "otherEntityField": "name" + }, + { + "relationshipType": "many-to-one", + "otherEntityName": "project", + "otherEntityRelationshipName": "submitRecord", + "relationshipName": "project", + "otherEntityField": "name" + } + ], + "changelogDate": "20191019020828", + "javadoc": "提交记录", + "entityTableName": "submit_record", + "dto": "mapstruct", + "pagination": "pagination", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "readOnly": false, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/code-record.jh b/code-record.jh new file mode 100644 index 0000000..0711dc6 --- /dev/null +++ b/code-record.jh @@ -0,0 +1,36 @@ +/** 项目 */ +entity Project { + /** 项目名称 */ + name String required minlength(0) maxlength(12), + /** 项目编号 */ + code String required minlength(0) maxlength(64), + /** 备注 */ + desc TextBlob +} + + +/** 开发人员 */ +entity Developer { + /** 开发人员姓名 */ + name String required minlength(0) maxlength(12) +} + +/** 提交记录 */ +entity SubmitRecord { + /** 记录时间 */ + recordDate LocalDate required, + + /** 代码行数 */ + cnt Integer required +} + + +relationship ManyToOne { + SubmitRecord{Developer(name)} to Developer, + SubmitRecord{Project(name)} to Project +} + + +service all with serviceImpl +dto all with mapstruct +paginate all with pagination \ No newline at end of file diff --git a/src/main/java/com/aiyun/code/record/config/CacheConfiguration.java b/src/main/java/com/aiyun/code/record/config/CacheConfiguration.java index d139be3..dbd0745 100644 --- a/src/main/java/com/aiyun/code/record/config/CacheConfiguration.java +++ b/src/main/java/com/aiyun/code/record/config/CacheConfiguration.java @@ -42,6 +42,9 @@ public JCacheManagerCustomizer cacheManagerCustomizer() { createCache(cm, com.aiyun.code.record.domain.User.class.getName()); createCache(cm, com.aiyun.code.record.domain.Authority.class.getName()); createCache(cm, com.aiyun.code.record.domain.User.class.getName() + ".authorities"); + createCache(cm, com.aiyun.code.record.domain.Project.class.getName()); + createCache(cm, com.aiyun.code.record.domain.Developer.class.getName()); + createCache(cm, com.aiyun.code.record.domain.SubmitRecord.class.getName()); // jhipster-needle-ehcache-add-entry }; } diff --git a/src/main/java/com/aiyun/code/record/domain/Developer.java b/src/main/java/com/aiyun/code/record/domain/Developer.java new file mode 100644 index 0000000..1371f24 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/domain/Developer.java @@ -0,0 +1,81 @@ +package com.aiyun.code.record.domain; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; + +import javax.persistence.*; +import javax.validation.constraints.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; + +/** + * 开发人员 + */ +@Entity +@Table(name = "developer") +@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) +@org.springframework.data.elasticsearch.annotations.Document(indexName = "developer") +public class Developer implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + /** + * 开发人员姓名 + */ + @NotNull + @Size(min = 0, max = 12) + @Column(name = "name", length = 12, nullable = false) + private String name; + + // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public Developer name(String name) { + this.name = name; + return this; + } + + public void setName(String name) { + this.name = name; + } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Developer)) { + return false; + } + return id != null && id.equals(((Developer) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Developer{" + + "id=" + getId() + + ", name='" + getName() + "'" + + "}"; + } +} diff --git a/src/main/java/com/aiyun/code/record/domain/Project.java b/src/main/java/com/aiyun/code/record/domain/Project.java new file mode 100644 index 0000000..420e356 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/domain/Project.java @@ -0,0 +1,124 @@ +package com.aiyun.code.record.domain; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; + +import javax.persistence.*; +import javax.validation.constraints.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; + +/** + * 项目 + */ +@Entity +@Table(name = "project") +@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) +@org.springframework.data.elasticsearch.annotations.Document(indexName = "project") +public class Project implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + /** + * 项目名称 + */ + @NotNull + @Size(min = 0, max = 12) + @Column(name = "name", length = 12, nullable = false) + private String name; + + /** + * 项目编号 + */ + @NotNull + @Size(min = 0, max = 64) + @Column(name = "code", length = 64, nullable = false) + private String code; + + /** + * 备注 + */ + @Lob + @Column(name = "jhi_desc") + private String desc; + + // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public Project name(String name) { + this.name = name; + return this; + } + + public void setName(String name) { + this.name = name; + } + + public String getCode() { + return code; + } + + public Project code(String code) { + this.code = code; + return this; + } + + public void setCode(String code) { + this.code = code; + } + + public String getDesc() { + return desc; + } + + public Project desc(String desc) { + this.desc = desc; + return this; + } + + public void setDesc(String desc) { + this.desc = desc; + } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Project)) { + return false; + } + return id != null && id.equals(((Project) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Project{" + + "id=" + getId() + + ", name='" + getName() + "'" + + ", code='" + getCode() + "'" + + ", desc='" + getDesc() + "'" + + "}"; + } +} diff --git a/src/main/java/com/aiyun/code/record/domain/SubmitRecord.java b/src/main/java/com/aiyun/code/record/domain/SubmitRecord.java new file mode 100644 index 0000000..7a95ac2 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/domain/SubmitRecord.java @@ -0,0 +1,137 @@ +package com.aiyun.code.record.domain; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; + +import javax.persistence.*; +import javax.validation.constraints.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; +import java.time.LocalDate; + +/** + * 提交记录 + */ +@Entity +@Table(name = "submit_record") +@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) +@org.springframework.data.elasticsearch.annotations.Document(indexName = "submitrecord") +public class SubmitRecord implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + /** + * 记录时间 + */ + @NotNull + @Column(name = "record_date", nullable = false) + private LocalDate recordDate; + + /** + * 代码行数 + */ + @NotNull + @Column(name = "cnt", nullable = false) + private Integer cnt; + + @ManyToOne + @JsonIgnoreProperties("submitRecords") + private Developer developer; + + @ManyToOne + @JsonIgnoreProperties("submitRecords") + private Project project; + + // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public LocalDate getRecordDate() { + return recordDate; + } + + public SubmitRecord recordDate(LocalDate recordDate) { + this.recordDate = recordDate; + return this; + } + + public void setRecordDate(LocalDate recordDate) { + this.recordDate = recordDate; + } + + public Integer getCnt() { + return cnt; + } + + public SubmitRecord cnt(Integer cnt) { + this.cnt = cnt; + return this; + } + + public void setCnt(Integer cnt) { + this.cnt = cnt; + } + + public Developer getDeveloper() { + return developer; + } + + public SubmitRecord developer(Developer developer) { + this.developer = developer; + return this; + } + + public void setDeveloper(Developer developer) { + this.developer = developer; + } + + public Project getProject() { + return project; + } + + public SubmitRecord project(Project project) { + this.project = project; + return this; + } + + public void setProject(Project project) { + this.project = project; + } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof SubmitRecord)) { + return false; + } + return id != null && id.equals(((SubmitRecord) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "SubmitRecord{" + + "id=" + getId() + + ", recordDate='" + getRecordDate() + "'" + + ", cnt=" + getCnt() + + "}"; + } +} diff --git a/src/main/java/com/aiyun/code/record/repository/DeveloperRepository.java b/src/main/java/com/aiyun/code/record/repository/DeveloperRepository.java new file mode 100644 index 0000000..dec78b7 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/repository/DeveloperRepository.java @@ -0,0 +1,14 @@ +package com.aiyun.code.record.repository; +import com.aiyun.code.record.domain.Developer; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Developer entity. + */ +@SuppressWarnings("unused") +@Repository +public interface DeveloperRepository extends JpaRepository { + +} diff --git a/src/main/java/com/aiyun/code/record/repository/ProjectRepository.java b/src/main/java/com/aiyun/code/record/repository/ProjectRepository.java new file mode 100644 index 0000000..6ee9ba1 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/repository/ProjectRepository.java @@ -0,0 +1,14 @@ +package com.aiyun.code.record.repository; +import com.aiyun.code.record.domain.Project; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Project entity. + */ +@SuppressWarnings("unused") +@Repository +public interface ProjectRepository extends JpaRepository { + +} diff --git a/src/main/java/com/aiyun/code/record/repository/SubmitRecordRepository.java b/src/main/java/com/aiyun/code/record/repository/SubmitRecordRepository.java new file mode 100644 index 0000000..700ec47 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/repository/SubmitRecordRepository.java @@ -0,0 +1,14 @@ +package com.aiyun.code.record.repository; +import com.aiyun.code.record.domain.SubmitRecord; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the SubmitRecord entity. + */ +@SuppressWarnings("unused") +@Repository +public interface SubmitRecordRepository extends JpaRepository { + +} diff --git a/src/main/java/com/aiyun/code/record/repository/search/DeveloperSearchRepository.java b/src/main/java/com/aiyun/code/record/repository/search/DeveloperSearchRepository.java new file mode 100644 index 0000000..709fc8d --- /dev/null +++ b/src/main/java/com/aiyun/code/record/repository/search/DeveloperSearchRepository.java @@ -0,0 +1,9 @@ +package com.aiyun.code.record.repository.search; +import com.aiyun.code.record.domain.Developer; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Developer} entity. + */ +public interface DeveloperSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/com/aiyun/code/record/repository/search/ProjectSearchRepository.java b/src/main/java/com/aiyun/code/record/repository/search/ProjectSearchRepository.java new file mode 100644 index 0000000..0475acf --- /dev/null +++ b/src/main/java/com/aiyun/code/record/repository/search/ProjectSearchRepository.java @@ -0,0 +1,9 @@ +package com.aiyun.code.record.repository.search; +import com.aiyun.code.record.domain.Project; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Project} entity. + */ +public interface ProjectSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/com/aiyun/code/record/repository/search/SubmitRecordSearchRepository.java b/src/main/java/com/aiyun/code/record/repository/search/SubmitRecordSearchRepository.java new file mode 100644 index 0000000..5a2a073 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/repository/search/SubmitRecordSearchRepository.java @@ -0,0 +1,9 @@ +package com.aiyun.code.record.repository.search; +import com.aiyun.code.record.domain.SubmitRecord; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link SubmitRecord} entity. + */ +public interface SubmitRecordSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/com/aiyun/code/record/service/DeveloperService.java b/src/main/java/com/aiyun/code/record/service/DeveloperService.java new file mode 100644 index 0000000..cbfb811 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/DeveloperService.java @@ -0,0 +1,56 @@ +package com.aiyun.code.record.service; + +import com.aiyun.code.record.service.dto.DeveloperDTO; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.Optional; + +/** + * Service Interface for managing {@link com.aiyun.code.record.domain.Developer}. + */ +public interface DeveloperService { + + /** + * Save a developer. + * + * @param developerDTO the entity to save. + * @return the persisted entity. + */ + DeveloperDTO save(DeveloperDTO developerDTO); + + /** + * Get all the developers. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page findAll(Pageable pageable); + + + /** + * Get the "id" developer. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" developer. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the developer corresponding to the query. + * + * @param query the query of the search. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page search(String query, Pageable pageable); +} diff --git a/src/main/java/com/aiyun/code/record/service/ProjectService.java b/src/main/java/com/aiyun/code/record/service/ProjectService.java new file mode 100644 index 0000000..d389edd --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/ProjectService.java @@ -0,0 +1,56 @@ +package com.aiyun.code.record.service; + +import com.aiyun.code.record.service.dto.ProjectDTO; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.Optional; + +/** + * Service Interface for managing {@link com.aiyun.code.record.domain.Project}. + */ +public interface ProjectService { + + /** + * Save a project. + * + * @param projectDTO the entity to save. + * @return the persisted entity. + */ + ProjectDTO save(ProjectDTO projectDTO); + + /** + * Get all the projects. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page findAll(Pageable pageable); + + + /** + * Get the "id" project. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" project. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the project corresponding to the query. + * + * @param query the query of the search. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page search(String query, Pageable pageable); +} diff --git a/src/main/java/com/aiyun/code/record/service/SubmitRecordService.java b/src/main/java/com/aiyun/code/record/service/SubmitRecordService.java new file mode 100644 index 0000000..88e8ff7 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/SubmitRecordService.java @@ -0,0 +1,56 @@ +package com.aiyun.code.record.service; + +import com.aiyun.code.record.service.dto.SubmitRecordDTO; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.Optional; + +/** + * Service Interface for managing {@link com.aiyun.code.record.domain.SubmitRecord}. + */ +public interface SubmitRecordService { + + /** + * Save a submitRecord. + * + * @param submitRecordDTO the entity to save. + * @return the persisted entity. + */ + SubmitRecordDTO save(SubmitRecordDTO submitRecordDTO); + + /** + * Get all the submitRecords. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page findAll(Pageable pageable); + + + /** + * Get the "id" submitRecord. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" submitRecord. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the submitRecord corresponding to the query. + * + * @param query the query of the search. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page search(String query, Pageable pageable); +} diff --git a/src/main/java/com/aiyun/code/record/service/dto/DeveloperDTO.java b/src/main/java/com/aiyun/code/record/service/dto/DeveloperDTO.java new file mode 100644 index 0000000..fc457ab --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/dto/DeveloperDTO.java @@ -0,0 +1,69 @@ +package com.aiyun.code.record.service.dto; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link com.aiyun.code.record.domain.Developer} entity. + */ +@ApiModel(description = "开发人员") +public class DeveloperDTO implements Serializable { + + private Long id; + + /** + * 开发人员姓名 + */ + @NotNull + @Size(min = 0, max = 12) + @ApiModelProperty(value = "开发人员姓名", required = true) + private String name; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + DeveloperDTO developerDTO = (DeveloperDTO) o; + if (developerDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), developerDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "DeveloperDTO{" + + "id=" + getId() + + ", name='" + getName() + "'" + + "}"; + } +} diff --git a/src/main/java/com/aiyun/code/record/service/dto/ProjectDTO.java b/src/main/java/com/aiyun/code/record/service/dto/ProjectDTO.java new file mode 100644 index 0000000..5b4f772 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/dto/ProjectDTO.java @@ -0,0 +1,103 @@ +package com.aiyun.code.record.service.dto; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import java.io.Serializable; +import java.util.Objects; +import javax.persistence.Lob; + +/** + * A DTO for the {@link com.aiyun.code.record.domain.Project} entity. + */ +@ApiModel(description = "项目") +public class ProjectDTO implements Serializable { + + private Long id; + + /** + * 项目名称 + */ + @NotNull + @Size(min = 0, max = 12) + @ApiModelProperty(value = "项目名称", required = true) + private String name; + + /** + * 项目编号 + */ + @NotNull + @Size(min = 0, max = 64) + @ApiModelProperty(value = "项目编号", required = true) + private String code; + + /** + * 备注 + */ + @ApiModelProperty(value = "备注") + @Lob + private String desc; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + ProjectDTO projectDTO = (ProjectDTO) o; + if (projectDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), projectDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "ProjectDTO{" + + "id=" + getId() + + ", name='" + getName() + "'" + + ", code='" + getCode() + "'" + + ", desc='" + getDesc() + "'" + + "}"; + } +} diff --git a/src/main/java/com/aiyun/code/record/service/dto/SubmitRecordDTO.java b/src/main/java/com/aiyun/code/record/service/dto/SubmitRecordDTO.java new file mode 100644 index 0000000..c24f796 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/dto/SubmitRecordDTO.java @@ -0,0 +1,129 @@ +package com.aiyun.code.record.service.dto; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.time.LocalDate; +import javax.validation.constraints.*; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link com.aiyun.code.record.domain.SubmitRecord} entity. + */ +@ApiModel(description = "提交记录") +public class SubmitRecordDTO implements Serializable { + + private Long id; + + /** + * 记录时间 + */ + @NotNull + @ApiModelProperty(value = "记录时间", required = true) + private LocalDate recordDate; + + /** + * 代码行数 + */ + @NotNull + @ApiModelProperty(value = "代码行数", required = true) + private Integer cnt; + + + private Long developerId; + + private String developerName; + + private Long projectId; + + private String projectName; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public LocalDate getRecordDate() { + return recordDate; + } + + public void setRecordDate(LocalDate recordDate) { + this.recordDate = recordDate; + } + + public Integer getCnt() { + return cnt; + } + + public void setCnt(Integer cnt) { + this.cnt = cnt; + } + + public Long getDeveloperId() { + return developerId; + } + + public void setDeveloperId(Long developerId) { + this.developerId = developerId; + } + + public String getDeveloperName() { + return developerName; + } + + public void setDeveloperName(String developerName) { + this.developerName = developerName; + } + + public Long getProjectId() { + return projectId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + SubmitRecordDTO submitRecordDTO = (SubmitRecordDTO) o; + if (submitRecordDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), submitRecordDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "SubmitRecordDTO{" + + "id=" + getId() + + ", recordDate='" + getRecordDate() + "'" + + ", cnt=" + getCnt() + + ", developer=" + getDeveloperId() + + ", developer='" + getDeveloperName() + "'" + + ", project=" + getProjectId() + + ", project='" + getProjectName() + "'" + + "}"; + } +} diff --git a/src/main/java/com/aiyun/code/record/service/impl/DeveloperServiceImpl.java b/src/main/java/com/aiyun/code/record/service/impl/DeveloperServiceImpl.java new file mode 100644 index 0000000..4b400bf --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/impl/DeveloperServiceImpl.java @@ -0,0 +1,113 @@ +package com.aiyun.code.record.service.impl; + +import com.aiyun.code.record.service.DeveloperService; +import com.aiyun.code.record.domain.Developer; +import com.aiyun.code.record.repository.DeveloperRepository; +import com.aiyun.code.record.repository.search.DeveloperSearchRepository; +import com.aiyun.code.record.service.dto.DeveloperDTO; +import com.aiyun.code.record.service.mapper.DeveloperMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link Developer}. + */ +@Service +@Transactional +public class DeveloperServiceImpl implements DeveloperService { + + private final Logger log = LoggerFactory.getLogger(DeveloperServiceImpl.class); + + private final DeveloperRepository developerRepository; + + private final DeveloperMapper developerMapper; + + private final DeveloperSearchRepository developerSearchRepository; + + public DeveloperServiceImpl(DeveloperRepository developerRepository, DeveloperMapper developerMapper, DeveloperSearchRepository developerSearchRepository) { + this.developerRepository = developerRepository; + this.developerMapper = developerMapper; + this.developerSearchRepository = developerSearchRepository; + } + + /** + * Save a developer. + * + * @param developerDTO the entity to save. + * @return the persisted entity. + */ + @Override + public DeveloperDTO save(DeveloperDTO developerDTO) { + log.debug("Request to save Developer : {}", developerDTO); + Developer developer = developerMapper.toEntity(developerDTO); + developer = developerRepository.save(developer); + DeveloperDTO result = developerMapper.toDto(developer); + developerSearchRepository.save(developer); + return result; + } + + /** + * Get all the developers. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + log.debug("Request to get all Developers"); + return developerRepository.findAll(pageable) + .map(developerMapper::toDto); + } + + + /** + * Get one developer by id. + * + * @param id the id of the entity. + * @return the entity. + */ + @Override + @Transactional(readOnly = true) + public Optional findOne(Long id) { + log.debug("Request to get Developer : {}", id); + return developerRepository.findById(id) + .map(developerMapper::toDto); + } + + /** + * Delete the developer by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete Developer : {}", id); + developerRepository.deleteById(id); + developerSearchRepository.deleteById(id); + } + + /** + * Search for the developer corresponding to the query. + * + * @param query the query of the search. + * @param pageable the pagination information. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public Page search(String query, Pageable pageable) { + log.debug("Request to search for a page of Developers for query {}", query); + return developerSearchRepository.search(queryStringQuery(query), pageable) + .map(developerMapper::toDto); + } +} diff --git a/src/main/java/com/aiyun/code/record/service/impl/ProjectServiceImpl.java b/src/main/java/com/aiyun/code/record/service/impl/ProjectServiceImpl.java new file mode 100644 index 0000000..cdfa8ae --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/impl/ProjectServiceImpl.java @@ -0,0 +1,113 @@ +package com.aiyun.code.record.service.impl; + +import com.aiyun.code.record.service.ProjectService; +import com.aiyun.code.record.domain.Project; +import com.aiyun.code.record.repository.ProjectRepository; +import com.aiyun.code.record.repository.search.ProjectSearchRepository; +import com.aiyun.code.record.service.dto.ProjectDTO; +import com.aiyun.code.record.service.mapper.ProjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link Project}. + */ +@Service +@Transactional +public class ProjectServiceImpl implements ProjectService { + + private final Logger log = LoggerFactory.getLogger(ProjectServiceImpl.class); + + private final ProjectRepository projectRepository; + + private final ProjectMapper projectMapper; + + private final ProjectSearchRepository projectSearchRepository; + + public ProjectServiceImpl(ProjectRepository projectRepository, ProjectMapper projectMapper, ProjectSearchRepository projectSearchRepository) { + this.projectRepository = projectRepository; + this.projectMapper = projectMapper; + this.projectSearchRepository = projectSearchRepository; + } + + /** + * Save a project. + * + * @param projectDTO the entity to save. + * @return the persisted entity. + */ + @Override + public ProjectDTO save(ProjectDTO projectDTO) { + log.debug("Request to save Project : {}", projectDTO); + Project project = projectMapper.toEntity(projectDTO); + project = projectRepository.save(project); + ProjectDTO result = projectMapper.toDto(project); + projectSearchRepository.save(project); + return result; + } + + /** + * Get all the projects. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + log.debug("Request to get all Projects"); + return projectRepository.findAll(pageable) + .map(projectMapper::toDto); + } + + + /** + * Get one project by id. + * + * @param id the id of the entity. + * @return the entity. + */ + @Override + @Transactional(readOnly = true) + public Optional findOne(Long id) { + log.debug("Request to get Project : {}", id); + return projectRepository.findById(id) + .map(projectMapper::toDto); + } + + /** + * Delete the project by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete Project : {}", id); + projectRepository.deleteById(id); + projectSearchRepository.deleteById(id); + } + + /** + * Search for the project corresponding to the query. + * + * @param query the query of the search. + * @param pageable the pagination information. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public Page search(String query, Pageable pageable) { + log.debug("Request to search for a page of Projects for query {}", query); + return projectSearchRepository.search(queryStringQuery(query), pageable) + .map(projectMapper::toDto); + } +} diff --git a/src/main/java/com/aiyun/code/record/service/impl/SubmitRecordServiceImpl.java b/src/main/java/com/aiyun/code/record/service/impl/SubmitRecordServiceImpl.java new file mode 100644 index 0000000..1d5efd5 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/impl/SubmitRecordServiceImpl.java @@ -0,0 +1,113 @@ +package com.aiyun.code.record.service.impl; + +import com.aiyun.code.record.service.SubmitRecordService; +import com.aiyun.code.record.domain.SubmitRecord; +import com.aiyun.code.record.repository.SubmitRecordRepository; +import com.aiyun.code.record.repository.search.SubmitRecordSearchRepository; +import com.aiyun.code.record.service.dto.SubmitRecordDTO; +import com.aiyun.code.record.service.mapper.SubmitRecordMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link SubmitRecord}. + */ +@Service +@Transactional +public class SubmitRecordServiceImpl implements SubmitRecordService { + + private final Logger log = LoggerFactory.getLogger(SubmitRecordServiceImpl.class); + + private final SubmitRecordRepository submitRecordRepository; + + private final SubmitRecordMapper submitRecordMapper; + + private final SubmitRecordSearchRepository submitRecordSearchRepository; + + public SubmitRecordServiceImpl(SubmitRecordRepository submitRecordRepository, SubmitRecordMapper submitRecordMapper, SubmitRecordSearchRepository submitRecordSearchRepository) { + this.submitRecordRepository = submitRecordRepository; + this.submitRecordMapper = submitRecordMapper; + this.submitRecordSearchRepository = submitRecordSearchRepository; + } + + /** + * Save a submitRecord. + * + * @param submitRecordDTO the entity to save. + * @return the persisted entity. + */ + @Override + public SubmitRecordDTO save(SubmitRecordDTO submitRecordDTO) { + log.debug("Request to save SubmitRecord : {}", submitRecordDTO); + SubmitRecord submitRecord = submitRecordMapper.toEntity(submitRecordDTO); + submitRecord = submitRecordRepository.save(submitRecord); + SubmitRecordDTO result = submitRecordMapper.toDto(submitRecord); + submitRecordSearchRepository.save(submitRecord); + return result; + } + + /** + * Get all the submitRecords. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + log.debug("Request to get all SubmitRecords"); + return submitRecordRepository.findAll(pageable) + .map(submitRecordMapper::toDto); + } + + + /** + * Get one submitRecord by id. + * + * @param id the id of the entity. + * @return the entity. + */ + @Override + @Transactional(readOnly = true) + public Optional findOne(Long id) { + log.debug("Request to get SubmitRecord : {}", id); + return submitRecordRepository.findById(id) + .map(submitRecordMapper::toDto); + } + + /** + * Delete the submitRecord by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete SubmitRecord : {}", id); + submitRecordRepository.deleteById(id); + submitRecordSearchRepository.deleteById(id); + } + + /** + * Search for the submitRecord corresponding to the query. + * + * @param query the query of the search. + * @param pageable the pagination information. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public Page search(String query, Pageable pageable) { + log.debug("Request to search for a page of SubmitRecords for query {}", query); + return submitRecordSearchRepository.search(queryStringQuery(query), pageable) + .map(submitRecordMapper::toDto); + } +} diff --git a/src/main/java/com/aiyun/code/record/service/mapper/DeveloperMapper.java b/src/main/java/com/aiyun/code/record/service/mapper/DeveloperMapper.java new file mode 100644 index 0000000..4bf135c --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/mapper/DeveloperMapper.java @@ -0,0 +1,24 @@ +package com.aiyun.code.record.service.mapper; + +import com.aiyun.code.record.domain.*; +import com.aiyun.code.record.service.dto.DeveloperDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Developer} and its DTO {@link DeveloperDTO}. + */ +@Mapper(componentModel = "spring", uses = {}) +public interface DeveloperMapper extends EntityMapper { + + + + default Developer fromId(Long id) { + if (id == null) { + return null; + } + Developer developer = new Developer(); + developer.setId(id); + return developer; + } +} diff --git a/src/main/java/com/aiyun/code/record/service/mapper/EntityMapper.java b/src/main/java/com/aiyun/code/record/service/mapper/EntityMapper.java new file mode 100644 index 0000000..448de34 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/mapper/EntityMapper.java @@ -0,0 +1,21 @@ +package com.aiyun.code.record.service.mapper; + +import java.util.List; + +/** + * Contract for a generic dto to entity mapper. + * + * @param - DTO type parameter. + * @param - Entity type parameter. + */ + +public interface EntityMapper { + + E toEntity(D dto); + + D toDto(E entity); + + List toEntity(List dtoList); + + List toDto(List entityList); +} diff --git a/src/main/java/com/aiyun/code/record/service/mapper/ProjectMapper.java b/src/main/java/com/aiyun/code/record/service/mapper/ProjectMapper.java new file mode 100644 index 0000000..fc05bf5 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/mapper/ProjectMapper.java @@ -0,0 +1,24 @@ +package com.aiyun.code.record.service.mapper; + +import com.aiyun.code.record.domain.*; +import com.aiyun.code.record.service.dto.ProjectDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Project} and its DTO {@link ProjectDTO}. + */ +@Mapper(componentModel = "spring", uses = {}) +public interface ProjectMapper extends EntityMapper { + + + + default Project fromId(Long id) { + if (id == null) { + return null; + } + Project project = new Project(); + project.setId(id); + return project; + } +} diff --git a/src/main/java/com/aiyun/code/record/service/mapper/SubmitRecordMapper.java b/src/main/java/com/aiyun/code/record/service/mapper/SubmitRecordMapper.java new file mode 100644 index 0000000..2adc906 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/service/mapper/SubmitRecordMapper.java @@ -0,0 +1,32 @@ +package com.aiyun.code.record.service.mapper; + +import com.aiyun.code.record.domain.*; +import com.aiyun.code.record.service.dto.SubmitRecordDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link SubmitRecord} and its DTO {@link SubmitRecordDTO}. + */ +@Mapper(componentModel = "spring", uses = {DeveloperMapper.class, ProjectMapper.class}) +public interface SubmitRecordMapper extends EntityMapper { + + @Mapping(source = "developer.id", target = "developerId") + @Mapping(source = "developer.name", target = "developerName") + @Mapping(source = "project.id", target = "projectId") + @Mapping(source = "project.name", target = "projectName") + SubmitRecordDTO toDto(SubmitRecord submitRecord); + + @Mapping(source = "developerId", target = "developer") + @Mapping(source = "projectId", target = "project") + SubmitRecord toEntity(SubmitRecordDTO submitRecordDTO); + + default SubmitRecord fromId(Long id) { + if (id == null) { + return null; + } + SubmitRecord submitRecord = new SubmitRecord(); + submitRecord.setId(id); + return submitRecord; + } +} diff --git a/src/main/java/com/aiyun/code/record/web/rest/DeveloperResource.java b/src/main/java/com/aiyun/code/record/web/rest/DeveloperResource.java new file mode 100644 index 0000000..87f8fe9 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/web/rest/DeveloperResource.java @@ -0,0 +1,148 @@ +package com.aiyun.code.record.web.rest; + +import com.aiyun.code.record.service.DeveloperService; +import com.aiyun.code.record.web.rest.errors.BadRequestAlertException; +import com.aiyun.code.record.service.dto.DeveloperDTO; + +import io.github.jhipster.web.util.HeaderUtil; +import io.github.jhipster.web.util.PaginationUtil; +import io.github.jhipster.web.util.ResponseUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link com.aiyun.code.record.domain.Developer}. + */ +@RestController +@RequestMapping("/api") +public class DeveloperResource { + + private final Logger log = LoggerFactory.getLogger(DeveloperResource.class); + + private static final String ENTITY_NAME = "developer"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final DeveloperService developerService; + + public DeveloperResource(DeveloperService developerService) { + this.developerService = developerService; + } + + /** + * {@code POST /developers} : Create a new developer. + * + * @param developerDTO the developerDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new developerDTO, or with status {@code 400 (Bad Request)} if the developer has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/developers") + public ResponseEntity createDeveloper(@Valid @RequestBody DeveloperDTO developerDTO) throws URISyntaxException { + log.debug("REST request to save Developer : {}", developerDTO); + if (developerDTO.getId() != null) { + throw new BadRequestAlertException("A new developer cannot already have an ID", ENTITY_NAME, "idexists"); + } + DeveloperDTO result = developerService.save(developerDTO); + return ResponseEntity.created(new URI("/api/developers/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /developers} : Updates an existing developer. + * + * @param developerDTO the developerDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated developerDTO, + * or with status {@code 400 (Bad Request)} if the developerDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the developerDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/developers") + public ResponseEntity updateDeveloper(@Valid @RequestBody DeveloperDTO developerDTO) throws URISyntaxException { + log.debug("REST request to update Developer : {}", developerDTO); + if (developerDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + DeveloperDTO result = developerService.save(developerDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, developerDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /developers} : get all the developers. + * + + * @param pageable the pagination information. + + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of developers in body. + */ + @GetMapping("/developers") + public ResponseEntity> getAllDevelopers(Pageable pageable) { + log.debug("REST request to get a page of Developers"); + Page page = developerService.findAll(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * {@code GET /developers/:id} : get the "id" developer. + * + * @param id the id of the developerDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the developerDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/developers/{id}") + public ResponseEntity getDeveloper(@PathVariable Long id) { + log.debug("REST request to get Developer : {}", id); + Optional developerDTO = developerService.findOne(id); + return ResponseUtil.wrapOrNotFound(developerDTO); + } + + /** + * {@code DELETE /developers/:id} : delete the "id" developer. + * + * @param id the id of the developerDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/developers/{id}") + public ResponseEntity deleteDeveloper(@PathVariable Long id) { + log.debug("REST request to delete Developer : {}", id); + developerService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/developers?query=:query} : search for the developer corresponding + * to the query. + * + * @param query the query of the developer search. + * @param pageable the pagination information. + * @return the result of the search. + */ + @GetMapping("/_search/developers") + public ResponseEntity> searchDevelopers(@RequestParam String query, Pageable pageable) { + log.debug("REST request to search for a page of Developers for query {}", query); + Page page = developerService.search(query, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } +} diff --git a/src/main/java/com/aiyun/code/record/web/rest/ProjectResource.java b/src/main/java/com/aiyun/code/record/web/rest/ProjectResource.java new file mode 100644 index 0000000..5337f4a --- /dev/null +++ b/src/main/java/com/aiyun/code/record/web/rest/ProjectResource.java @@ -0,0 +1,148 @@ +package com.aiyun.code.record.web.rest; + +import com.aiyun.code.record.service.ProjectService; +import com.aiyun.code.record.web.rest.errors.BadRequestAlertException; +import com.aiyun.code.record.service.dto.ProjectDTO; + +import io.github.jhipster.web.util.HeaderUtil; +import io.github.jhipster.web.util.PaginationUtil; +import io.github.jhipster.web.util.ResponseUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link com.aiyun.code.record.domain.Project}. + */ +@RestController +@RequestMapping("/api") +public class ProjectResource { + + private final Logger log = LoggerFactory.getLogger(ProjectResource.class); + + private static final String ENTITY_NAME = "project"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final ProjectService projectService; + + public ProjectResource(ProjectService projectService) { + this.projectService = projectService; + } + + /** + * {@code POST /projects} : Create a new project. + * + * @param projectDTO the projectDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new projectDTO, or with status {@code 400 (Bad Request)} if the project has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/projects") + public ResponseEntity createProject(@Valid @RequestBody ProjectDTO projectDTO) throws URISyntaxException { + log.debug("REST request to save Project : {}", projectDTO); + if (projectDTO.getId() != null) { + throw new BadRequestAlertException("A new project cannot already have an ID", ENTITY_NAME, "idexists"); + } + ProjectDTO result = projectService.save(projectDTO); + return ResponseEntity.created(new URI("/api/projects/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /projects} : Updates an existing project. + * + * @param projectDTO the projectDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated projectDTO, + * or with status {@code 400 (Bad Request)} if the projectDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the projectDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/projects") + public ResponseEntity updateProject(@Valid @RequestBody ProjectDTO projectDTO) throws URISyntaxException { + log.debug("REST request to update Project : {}", projectDTO); + if (projectDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + ProjectDTO result = projectService.save(projectDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, projectDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /projects} : get all the projects. + * + + * @param pageable the pagination information. + + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of projects in body. + */ + @GetMapping("/projects") + public ResponseEntity> getAllProjects(Pageable pageable) { + log.debug("REST request to get a page of Projects"); + Page page = projectService.findAll(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * {@code GET /projects/:id} : get the "id" project. + * + * @param id the id of the projectDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the projectDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/projects/{id}") + public ResponseEntity getProject(@PathVariable Long id) { + log.debug("REST request to get Project : {}", id); + Optional projectDTO = projectService.findOne(id); + return ResponseUtil.wrapOrNotFound(projectDTO); + } + + /** + * {@code DELETE /projects/:id} : delete the "id" project. + * + * @param id the id of the projectDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/projects/{id}") + public ResponseEntity deleteProject(@PathVariable Long id) { + log.debug("REST request to delete Project : {}", id); + projectService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/projects?query=:query} : search for the project corresponding + * to the query. + * + * @param query the query of the project search. + * @param pageable the pagination information. + * @return the result of the search. + */ + @GetMapping("/_search/projects") + public ResponseEntity> searchProjects(@RequestParam String query, Pageable pageable) { + log.debug("REST request to search for a page of Projects for query {}", query); + Page page = projectService.search(query, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } +} diff --git a/src/main/java/com/aiyun/code/record/web/rest/SubmitRecordResource.java b/src/main/java/com/aiyun/code/record/web/rest/SubmitRecordResource.java new file mode 100644 index 0000000..e84de46 --- /dev/null +++ b/src/main/java/com/aiyun/code/record/web/rest/SubmitRecordResource.java @@ -0,0 +1,148 @@ +package com.aiyun.code.record.web.rest; + +import com.aiyun.code.record.service.SubmitRecordService; +import com.aiyun.code.record.web.rest.errors.BadRequestAlertException; +import com.aiyun.code.record.service.dto.SubmitRecordDTO; + +import io.github.jhipster.web.util.HeaderUtil; +import io.github.jhipster.web.util.PaginationUtil; +import io.github.jhipster.web.util.ResponseUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link com.aiyun.code.record.domain.SubmitRecord}. + */ +@RestController +@RequestMapping("/api") +public class SubmitRecordResource { + + private final Logger log = LoggerFactory.getLogger(SubmitRecordResource.class); + + private static final String ENTITY_NAME = "submitRecord"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final SubmitRecordService submitRecordService; + + public SubmitRecordResource(SubmitRecordService submitRecordService) { + this.submitRecordService = submitRecordService; + } + + /** + * {@code POST /submit-records} : Create a new submitRecord. + * + * @param submitRecordDTO the submitRecordDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new submitRecordDTO, or with status {@code 400 (Bad Request)} if the submitRecord has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/submit-records") + public ResponseEntity createSubmitRecord(@Valid @RequestBody SubmitRecordDTO submitRecordDTO) throws URISyntaxException { + log.debug("REST request to save SubmitRecord : {}", submitRecordDTO); + if (submitRecordDTO.getId() != null) { + throw new BadRequestAlertException("A new submitRecord cannot already have an ID", ENTITY_NAME, "idexists"); + } + SubmitRecordDTO result = submitRecordService.save(submitRecordDTO); + return ResponseEntity.created(new URI("/api/submit-records/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /submit-records} : Updates an existing submitRecord. + * + * @param submitRecordDTO the submitRecordDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated submitRecordDTO, + * or with status {@code 400 (Bad Request)} if the submitRecordDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the submitRecordDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/submit-records") + public ResponseEntity updateSubmitRecord(@Valid @RequestBody SubmitRecordDTO submitRecordDTO) throws URISyntaxException { + log.debug("REST request to update SubmitRecord : {}", submitRecordDTO); + if (submitRecordDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + SubmitRecordDTO result = submitRecordService.save(submitRecordDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, submitRecordDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /submit-records} : get all the submitRecords. + * + + * @param pageable the pagination information. + + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of submitRecords in body. + */ + @GetMapping("/submit-records") + public ResponseEntity> getAllSubmitRecords(Pageable pageable) { + log.debug("REST request to get a page of SubmitRecords"); + Page page = submitRecordService.findAll(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * {@code GET /submit-records/:id} : get the "id" submitRecord. + * + * @param id the id of the submitRecordDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the submitRecordDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/submit-records/{id}") + public ResponseEntity getSubmitRecord(@PathVariable Long id) { + log.debug("REST request to get SubmitRecord : {}", id); + Optional submitRecordDTO = submitRecordService.findOne(id); + return ResponseUtil.wrapOrNotFound(submitRecordDTO); + } + + /** + * {@code DELETE /submit-records/:id} : delete the "id" submitRecord. + * + * @param id the id of the submitRecordDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/submit-records/{id}") + public ResponseEntity deleteSubmitRecord(@PathVariable Long id) { + log.debug("REST request to delete SubmitRecord : {}", id); + submitRecordService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/submit-records?query=:query} : search for the submitRecord corresponding + * to the query. + * + * @param query the query of the submitRecord search. + * @param pageable the pagination information. + * @return the result of the search. + */ + @GetMapping("/_search/submit-records") + public ResponseEntity> searchSubmitRecords(@RequestParam String query, Pageable pageable) { + log.debug("REST request to search for a page of SubmitRecords for query {}", query); + Page page = submitRecordService.search(query, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } +} diff --git a/src/main/resources/config/liquibase/changelog/20191019020826_added_entity_Project.xml b/src/main/resources/config/liquibase/changelog/20191019020826_added_entity_Project.xml new file mode 100644 index 0000000..1447960 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20191019020826_added_entity_Project.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20191019020827_added_entity_Developer.xml b/src/main/resources/config/liquibase/changelog/20191019020827_added_entity_Developer.xml new file mode 100644 index 0000000..1a5a9da --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20191019020827_added_entity_Developer.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20191019020828_added_entity_SubmitRecord.xml b/src/main/resources/config/liquibase/changelog/20191019020828_added_entity_SubmitRecord.xml new file mode 100644 index 0000000..a6d7aa9 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20191019020828_added_entity_SubmitRecord.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20191019020828_added_entity_constraints_SubmitRecord.xml b/src/main/resources/config/liquibase/changelog/20191019020828_added_entity_constraints_SubmitRecord.xml new file mode 100644 index 0000000..c0111f9 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20191019020828_added_entity_constraints_SubmitRecord.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + 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 0000000..2ab1093 Binary files /dev/null and b/src/main/resources/config/liquibase/fake-data/blob/hipster.png differ 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/developer.csv b/src/main/resources/config/liquibase/fake-data/developer.csv new file mode 100644 index 0000000..4190882 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/developer.csv @@ -0,0 +1,11 @@ +id;name +1;Industrial +2;connect Mark +3;capacitor ar +4;sky blue Tas +5;compress Sou +6;compelling m +7;bifurcated s +8;Small +9;deliverables +10;overriding diff --git a/src/main/resources/config/liquibase/fake-data/project.csv b/src/main/resources/config/liquibase/fake-data/project.csv new file mode 100644 index 0000000..563c9de --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/project.csv @@ -0,0 +1,11 @@ +id;name;code;jhi_desc +1;mobile Fish;Home Loan Account Table Computer;../fake-data/blob/hipster.txt +2;Trace;Savings Account alarm;../fake-data/blob/hipster.txt +3;Tasty Metal ;red Chips Soap;../fake-data/blob/hipster.txt +4;Home Loan Ac;web-readiness;../fake-data/blob/hipster.txt +5;Namibia;Steel zero administration;../fake-data/blob/hipster.txt +6;Multi-channe;grey Cambridgeshire;../fake-data/blob/hipster.txt +7;Canyon HDD;Table Small Frozen Sausages Planner;../fake-data/blob/hipster.txt +8;envisioneer ;infomediaries;../fake-data/blob/hipster.txt +9;Investment A;Games Regional Digitized;../fake-data/blob/hipster.txt +10;copy converg;Mayotte;../fake-data/blob/hipster.txt diff --git a/src/main/resources/config/liquibase/fake-data/submit_record.csv b/src/main/resources/config/liquibase/fake-data/submit_record.csv new file mode 100644 index 0000000..1b9cd23 --- /dev/null +++ b/src/main/resources/config/liquibase/fake-data/submit_record.csv @@ -0,0 +1,11 @@ +id;record_date;cnt +1;2019-10-18;71134 +2;2019-10-18;79017 +3;2019-10-18;60595 +4;2019-10-19;92630 +5;2019-10-18;65107 +6;2019-10-18;91495 +7;2019-10-18;85003 +8;2019-10-18;44945 +9;2019-10-18;9541 +10;2019-10-19;37081 diff --git a/src/main/resources/config/liquibase/master.xml b/src/main/resources/config/liquibase/master.xml index d3a3842..6b058e2 100644 --- a/src/main/resources/config/liquibase/master.xml +++ b/src/main/resources/config/liquibase/master.xml @@ -14,6 +14,10 @@ + + + + diff --git a/src/main/webapp/app/entities/developer/developer-delete-dialog.component.html b/src/main/webapp/app/entities/developer/developer-delete-dialog.component.html new file mode 100644 index 0000000..1037ee9 --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/developer/developer-delete-dialog.component.ts b/src/main/webapp/app/entities/developer/developer-delete-dialog.component.ts new file mode 100644 index 0000000..69904bc --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer-delete-dialog.component.ts @@ -0,0 +1,65 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; + +import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; +import { JhiEventManager } from 'ng-jhipster'; + +import { IDeveloper } from 'app/shared/model/developer.model'; +import { DeveloperService } from './developer.service'; + +@Component({ + selector: 'jhi-developer-delete-dialog', + templateUrl: './developer-delete-dialog.component.html' +}) +export class DeveloperDeleteDialogComponent { + developer: IDeveloper; + + constructor(protected developerService: DeveloperService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.developerService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'developerListModification', + content: 'Deleted an developer' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-developer-delete-popup', + template: '' +}) +export class DeveloperDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ developer }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(DeveloperDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.developer = developer; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/developer', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/developer', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/developer/developer-detail.component.html b/src/main/webapp/app/entities/developer/developer-detail.component.html new file mode 100644 index 0000000..f34213c --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer-detail.component.html @@ -0,0 +1,27 @@ +
+
+
+

Developer {{developer.id}}

+
+ +
+
Name
+
+ {{developer.name}} +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/developer/developer-detail.component.ts b/src/main/webapp/app/entities/developer/developer-detail.component.ts new file mode 100644 index 0000000..0622baf --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { IDeveloper } from 'app/shared/model/developer.model'; + +@Component({ + selector: 'jhi-developer-detail', + templateUrl: './developer-detail.component.html' +}) +export class DeveloperDetailComponent implements OnInit { + developer: IDeveloper; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ developer }) => { + this.developer = developer; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/developer/developer-update.component.html b/src/main/webapp/app/entities/developer/developer-update.component.html new file mode 100644 index 0000000..cfd68b4 --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer-update.component.html @@ -0,0 +1,43 @@ +
+
+
+

Create or edit a Developer

+
+ +
+ + +
+
+ + +
+ + This field is required. + + + This field is required to be at least 0 characters. + + + This field cannot be longer than 12 characters. + +
+
+ +
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/developer/developer-update.component.ts b/src/main/webapp/app/entities/developer/developer-update.component.ts new file mode 100644 index 0000000..ad1c6de --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer-update.component.ts @@ -0,0 +1,73 @@ +import { Component, OnInit } from '@angular/core'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { IDeveloper, Developer } from 'app/shared/model/developer.model'; +import { DeveloperService } from './developer.service'; + +@Component({ + selector: 'jhi-developer-update', + templateUrl: './developer-update.component.html' +}) +export class DeveloperUpdateComponent implements OnInit { + isSaving: boolean; + + editForm = this.fb.group({ + id: [], + name: [null, [Validators.required, Validators.minLength(0), Validators.maxLength(12)]] + }); + + constructor(protected developerService: DeveloperService, protected activatedRoute: ActivatedRoute, private fb: FormBuilder) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ developer }) => { + this.updateForm(developer); + }); + } + + updateForm(developer: IDeveloper) { + this.editForm.patchValue({ + id: developer.id, + name: developer.name + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const developer = this.createFromForm(); + if (developer.id !== undefined) { + this.subscribeToSaveResponse(this.developerService.update(developer)); + } else { + this.subscribeToSaveResponse(this.developerService.create(developer)); + } + } + + private createFromForm(): IDeveloper { + return { + ...new Developer(), + id: this.editForm.get(['id']).value, + name: this.editForm.get(['name']).value + }; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe(() => this.onSaveSuccess(), () => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } +} diff --git a/src/main/webapp/app/entities/developer/developer.component.html b/src/main/webapp/app/entities/developer/developer.component.html new file mode 100644 index 0000000..45a085f --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer.component.html @@ -0,0 +1,81 @@ +
+

+ Developers + +

+ + +
+
+
+
+ + + +
+
+
+
+
+
+ No developers found +
+
+ + + + + + + + + + + + + + + +
ID Name
{{developer.id}}{{developer.name}} +
+ + + +
+
+
+
+
+ +
+
+ +
+
+
diff --git a/src/main/webapp/app/entities/developer/developer.component.ts b/src/main/webapp/app/entities/developer/developer.component.ts new file mode 100644 index 0000000..99e325b --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer.component.ts @@ -0,0 +1,159 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Router } from '@angular/router'; +import { Subscription } from 'rxjs'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiParseLinks } from 'ng-jhipster'; + +import { IDeveloper } from 'app/shared/model/developer.model'; +import { AccountService } from 'app/core/auth/account.service'; + +import { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants'; +import { DeveloperService } from './developer.service'; + +@Component({ + selector: 'jhi-developer', + templateUrl: './developer.component.html' +}) +export class DeveloperComponent implements OnInit, OnDestroy { + currentAccount: any; + developers: IDeveloper[]; + error: any; + success: any; + eventSubscriber: Subscription; + currentSearch: string; + routeData: any; + links: any; + totalItems: any; + itemsPerPage: any; + page: any; + predicate: any; + previousPage: any; + reverse: any; + + constructor( + protected developerService: DeveloperService, + protected parseLinks: JhiParseLinks, + protected accountService: AccountService, + protected activatedRoute: ActivatedRoute, + protected router: Router, + protected eventManager: JhiEventManager + ) { + this.itemsPerPage = ITEMS_PER_PAGE; + this.routeData = this.activatedRoute.data.subscribe(data => { + this.page = data.pagingParams.page; + this.previousPage = data.pagingParams.page; + this.reverse = data.pagingParams.ascending; + this.predicate = data.pagingParams.predicate; + }); + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.queryParams['search'] + ? this.activatedRoute.snapshot.queryParams['search'] + : ''; + } + + loadAll() { + if (this.currentSearch) { + this.developerService + .search({ + page: this.page - 1, + query: this.currentSearch, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe((res: HttpResponse) => this.paginateDevelopers(res.body, res.headers)); + return; + } + this.developerService + .query({ + page: this.page - 1, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe((res: HttpResponse) => this.paginateDevelopers(res.body, res.headers)); + } + + loadPage(page: number) { + if (page !== this.previousPage) { + this.previousPage = page; + this.transition(); + } + } + + transition() { + this.router.navigate(['/developer'], { + queryParams: { + page: this.page, + size: this.itemsPerPage, + search: this.currentSearch, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + }); + this.loadAll(); + } + + clear() { + this.page = 0; + this.currentSearch = ''; + this.router.navigate([ + '/developer', + { + page: this.page, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + ]); + this.loadAll(); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.page = 0; + this.currentSearch = query; + this.router.navigate([ + '/developer', + { + search: this.currentSearch, + page: this.page, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + ]); + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().subscribe(account => { + this.currentAccount = account; + }); + this.registerChangeInDevelopers(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IDeveloper) { + return item.id; + } + + registerChangeInDevelopers() { + this.eventSubscriber = this.eventManager.subscribe('developerListModification', response => this.loadAll()); + } + + sort() { + const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')]; + if (this.predicate !== 'id') { + result.push('id'); + } + return result; + } + + protected paginateDevelopers(data: IDeveloper[], headers: HttpHeaders) { + this.links = this.parseLinks.parse(headers.get('link')); + this.totalItems = parseInt(headers.get('X-Total-Count'), 10); + this.developers = data; + } +} diff --git a/src/main/webapp/app/entities/developer/developer.module.ts b/src/main/webapp/app/entities/developer/developer.module.ts new file mode 100644 index 0000000..227776d --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer.module.ts @@ -0,0 +1,24 @@ +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { CodeRecordApplicationSharedModule } from 'app/shared/shared.module'; +import { DeveloperComponent } from './developer.component'; +import { DeveloperDetailComponent } from './developer-detail.component'; +import { DeveloperUpdateComponent } from './developer-update.component'; +import { DeveloperDeletePopupComponent, DeveloperDeleteDialogComponent } from './developer-delete-dialog.component'; +import { developerRoute, developerPopupRoute } from './developer.route'; + +const ENTITY_STATES = [...developerRoute, ...developerPopupRoute]; + +@NgModule({ + imports: [CodeRecordApplicationSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + DeveloperComponent, + DeveloperDetailComponent, + DeveloperUpdateComponent, + DeveloperDeleteDialogComponent, + DeveloperDeletePopupComponent + ], + entryComponents: [DeveloperDeleteDialogComponent] +}) +export class CodeRecordApplicationDeveloperModule {} diff --git a/src/main/webapp/app/entities/developer/developer.route.ts b/src/main/webapp/app/entities/developer/developer.route.ts new file mode 100644 index 0000000..08e7a37 --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer.route.ts @@ -0,0 +1,98 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { JhiResolvePagingParams } from 'ng-jhipster'; +import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Developer } from 'app/shared/model/developer.model'; +import { DeveloperService } from './developer.service'; +import { DeveloperComponent } from './developer.component'; +import { DeveloperDetailComponent } from './developer-detail.component'; +import { DeveloperUpdateComponent } from './developer-update.component'; +import { DeveloperDeletePopupComponent } from './developer-delete-dialog.component'; +import { IDeveloper } from 'app/shared/model/developer.model'; + +@Injectable({ providedIn: 'root' }) +export class DeveloperResolve implements Resolve { + constructor(private service: DeveloperService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id']; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((developer: HttpResponse) => developer.body) + ); + } + return of(new Developer()); + } +} + +export const developerRoute: Routes = [ + { + path: '', + component: DeveloperComponent, + resolve: { + pagingParams: JhiResolvePagingParams + }, + data: { + authorities: ['ROLE_USER'], + defaultSort: 'id,asc', + pageTitle: 'codeRecordApplicationApp.developer.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: DeveloperDetailComponent, + resolve: { + developer: DeveloperResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.developer.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: DeveloperUpdateComponent, + resolve: { + developer: DeveloperResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.developer.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: DeveloperUpdateComponent, + resolve: { + developer: DeveloperResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.developer.home.title' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const developerPopupRoute: Routes = [ + { + path: ':id/delete', + component: DeveloperDeletePopupComponent, + resolve: { + developer: DeveloperResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.developer.home.title' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/developer/developer.service.ts b/src/main/webapp/app/entities/developer/developer.service.ts new file mode 100644 index 0000000..d1bbc5a --- /dev/null +++ b/src/main/webapp/app/entities/developer/developer.service.ts @@ -0,0 +1,44 @@ +import { Injectable } from '@angular/core'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; + +import { SERVER_API_URL } from 'app/app.constants'; +import { createRequestOption } from 'app/shared/util/request-util'; +import { IDeveloper } from 'app/shared/model/developer.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class DeveloperService { + public resourceUrl = SERVER_API_URL + 'api/developers'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/developers'; + + constructor(protected http: HttpClient) {} + + create(developer: IDeveloper): Observable { + return this.http.post(this.resourceUrl, developer, { observe: 'response' }); + } + + update(developer: IDeveloper): Observable { + return this.http.put(this.resourceUrl, developer, { observe: 'response' }); + } + + find(id: number): Observable { + return this.http.get(`${this.resourceUrl}/${id}`, { observe: 'response' }); + } + + query(req?: any): Observable { + const options = createRequestOption(req); + return this.http.get(this.resourceUrl, { params: options, observe: 'response' }); + } + + delete(id: number): Observable> { + return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); + } + + search(req?: any): Observable { + const options = createRequestOption(req); + return this.http.get(this.resourceSearchUrl, { params: options, observe: 'response' }); + } +} diff --git a/src/main/webapp/app/entities/entity.module.ts b/src/main/webapp/app/entities/entity.module.ts index 0cbebb9..3bda595 100644 --- a/src/main/webapp/app/entities/entity.module.ts +++ b/src/main/webapp/app/entities/entity.module.ts @@ -4,6 +4,18 @@ import { RouterModule } from '@angular/router'; @NgModule({ imports: [ RouterModule.forChild([ + { + path: 'project', + loadChildren: () => import('./project/project.module').then(m => m.CodeRecordApplicationProjectModule) + }, + { + path: 'developer', + loadChildren: () => import('./developer/developer.module').then(m => m.CodeRecordApplicationDeveloperModule) + }, + { + path: 'submit-record', + loadChildren: () => import('./submit-record/submit-record.module').then(m => m.CodeRecordApplicationSubmitRecordModule) + } /* jhipster-needle-add-entity-route - JHipster will add entity modules routes here */ ]) ] diff --git a/src/main/webapp/app/entities/project/project-delete-dialog.component.html b/src/main/webapp/app/entities/project/project-delete-dialog.component.html new file mode 100644 index 0000000..c43b54c --- /dev/null +++ b/src/main/webapp/app/entities/project/project-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/project/project-delete-dialog.component.ts b/src/main/webapp/app/entities/project/project-delete-dialog.component.ts new file mode 100644 index 0000000..5a042c0 --- /dev/null +++ b/src/main/webapp/app/entities/project/project-delete-dialog.component.ts @@ -0,0 +1,65 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; + +import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; +import { JhiEventManager } from 'ng-jhipster'; + +import { IProject } from 'app/shared/model/project.model'; +import { ProjectService } from './project.service'; + +@Component({ + selector: 'jhi-project-delete-dialog', + templateUrl: './project-delete-dialog.component.html' +}) +export class ProjectDeleteDialogComponent { + project: IProject; + + constructor(protected projectService: ProjectService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.projectService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'projectListModification', + content: 'Deleted an project' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-project-delete-popup', + template: '' +}) +export class ProjectDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ project }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(ProjectDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.project = project; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/project', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/project', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/project/project-detail.component.html b/src/main/webapp/app/entities/project/project-detail.component.html new file mode 100644 index 0000000..b4966db --- /dev/null +++ b/src/main/webapp/app/entities/project/project-detail.component.html @@ -0,0 +1,35 @@ +
+
+
+

Project {{project.id}}

+
+ +
+
Name
+
+ {{project.name}} +
+
Code
+
+ {{project.code}} +
+
Desc
+
+ {{project.desc}} +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/project/project-detail.component.ts b/src/main/webapp/app/entities/project/project-detail.component.ts new file mode 100644 index 0000000..d712f90 --- /dev/null +++ b/src/main/webapp/app/entities/project/project-detail.component.ts @@ -0,0 +1,32 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { JhiDataUtils } from 'ng-jhipster'; + +import { IProject } from 'app/shared/model/project.model'; + +@Component({ + selector: 'jhi-project-detail', + templateUrl: './project-detail.component.html' +}) +export class ProjectDetailComponent implements OnInit { + project: IProject; + + constructor(protected dataUtils: JhiDataUtils, protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ project }) => { + this.project = project; + }); + } + + byteSize(field) { + return this.dataUtils.byteSize(field); + } + + openFile(contentType, field) { + return this.dataUtils.openFile(contentType, field); + } + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/project/project-update.component.html b/src/main/webapp/app/entities/project/project-update.component.html new file mode 100644 index 0000000..65dd8dd --- /dev/null +++ b/src/main/webapp/app/entities/project/project-update.component.html @@ -0,0 +1,67 @@ +
+
+
+

Create or edit a Project

+
+ +
+ + +
+
+ + +
+ + This field is required. + + + This field is required to be at least 0 characters. + + + This field cannot be longer than 12 characters. + +
+
+
+ + +
+ + This field is required. + + + This field is required to be at least 0 characters. + + + This field cannot be longer than 64 characters. + +
+
+
+ + +
+ +
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/project/project-update.component.ts b/src/main/webapp/app/entities/project/project-update.component.ts new file mode 100644 index 0000000..273ff82 --- /dev/null +++ b/src/main/webapp/app/entities/project/project-update.component.ts @@ -0,0 +1,122 @@ +import { Component, OnInit } from '@angular/core'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { JhiAlertService, JhiDataUtils } from 'ng-jhipster'; +import { IProject, Project } from 'app/shared/model/project.model'; +import { ProjectService } from './project.service'; + +@Component({ + selector: 'jhi-project-update', + templateUrl: './project-update.component.html' +}) +export class ProjectUpdateComponent implements OnInit { + isSaving: boolean; + + editForm = this.fb.group({ + id: [], + name: [null, [Validators.required, Validators.minLength(0), Validators.maxLength(12)]], + code: [null, [Validators.required, Validators.minLength(0), Validators.maxLength(64)]], + desc: [] + }); + + constructor( + protected dataUtils: JhiDataUtils, + protected jhiAlertService: JhiAlertService, + protected projectService: ProjectService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ project }) => { + this.updateForm(project); + }); + } + + updateForm(project: IProject) { + this.editForm.patchValue({ + id: project.id, + name: project.name, + code: project.code, + desc: project.desc + }); + } + + byteSize(field) { + return this.dataUtils.byteSize(field); + } + + openFile(contentType, field) { + return this.dataUtils.openFile(contentType, field); + } + + setFileData(event, field: string, isImage) { + return new Promise((resolve, reject) => { + if (event && event.target && event.target.files && event.target.files[0]) { + const file: File = event.target.files[0]; + if (isImage && !file.type.startsWith('image/')) { + reject(`File was expected to be an image but was found to be ${file.type}`); + } else { + const filedContentType: string = field + 'ContentType'; + this.dataUtils.toBase64(file, base64Data => { + this.editForm.patchValue({ + [field]: base64Data, + [filedContentType]: file.type + }); + }); + } + } else { + reject(`Base64 data was not set as file could not be extracted from passed parameter: ${event}`); + } + }).then( + // eslint-disable-next-line no-console + () => console.log('blob added'), // success + this.onError + ); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const project = this.createFromForm(); + if (project.id !== undefined) { + this.subscribeToSaveResponse(this.projectService.update(project)); + } else { + this.subscribeToSaveResponse(this.projectService.create(project)); + } + } + + private createFromForm(): IProject { + return { + ...new Project(), + id: this.editForm.get(['id']).value, + name: this.editForm.get(['name']).value, + code: this.editForm.get(['code']).value, + desc: this.editForm.get(['desc']).value + }; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe(() => this.onSaveSuccess(), () => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/project/project.component.html b/src/main/webapp/app/entities/project/project.component.html new file mode 100644 index 0000000..acfa40a --- /dev/null +++ b/src/main/webapp/app/entities/project/project.component.html @@ -0,0 +1,85 @@ +
+

+ Projects + +

+ + +
+
+
+
+ + + +
+
+
+
+
+
+ No projects found +
+
+ + + + + + + + + + + + + + + + + + + +
ID Name Code Desc
{{project.id}}{{project.name}}{{project.code}}{{project.desc}} +
+ + + +
+
+
+
+
+ +
+
+ +
+
+
diff --git a/src/main/webapp/app/entities/project/project.component.ts b/src/main/webapp/app/entities/project/project.component.ts new file mode 100644 index 0000000..c7182b6 --- /dev/null +++ b/src/main/webapp/app/entities/project/project.component.ts @@ -0,0 +1,168 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Router } from '@angular/router'; +import { Subscription } from 'rxjs'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiParseLinks, JhiDataUtils } from 'ng-jhipster'; + +import { IProject } from 'app/shared/model/project.model'; +import { AccountService } from 'app/core/auth/account.service'; + +import { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants'; +import { ProjectService } from './project.service'; + +@Component({ + selector: 'jhi-project', + templateUrl: './project.component.html' +}) +export class ProjectComponent implements OnInit, OnDestroy { + currentAccount: any; + projects: IProject[]; + error: any; + success: any; + eventSubscriber: Subscription; + currentSearch: string; + routeData: any; + links: any; + totalItems: any; + itemsPerPage: any; + page: any; + predicate: any; + previousPage: any; + reverse: any; + + constructor( + protected projectService: ProjectService, + protected parseLinks: JhiParseLinks, + protected accountService: AccountService, + protected activatedRoute: ActivatedRoute, + protected dataUtils: JhiDataUtils, + protected router: Router, + protected eventManager: JhiEventManager + ) { + this.itemsPerPage = ITEMS_PER_PAGE; + this.routeData = this.activatedRoute.data.subscribe(data => { + this.page = data.pagingParams.page; + this.previousPage = data.pagingParams.page; + this.reverse = data.pagingParams.ascending; + this.predicate = data.pagingParams.predicate; + }); + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.queryParams['search'] + ? this.activatedRoute.snapshot.queryParams['search'] + : ''; + } + + loadAll() { + if (this.currentSearch) { + this.projectService + .search({ + page: this.page - 1, + query: this.currentSearch, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe((res: HttpResponse) => this.paginateProjects(res.body, res.headers)); + return; + } + this.projectService + .query({ + page: this.page - 1, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe((res: HttpResponse) => this.paginateProjects(res.body, res.headers)); + } + + loadPage(page: number) { + if (page !== this.previousPage) { + this.previousPage = page; + this.transition(); + } + } + + transition() { + this.router.navigate(['/project'], { + queryParams: { + page: this.page, + size: this.itemsPerPage, + search: this.currentSearch, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + }); + this.loadAll(); + } + + clear() { + this.page = 0; + this.currentSearch = ''; + this.router.navigate([ + '/project', + { + page: this.page, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + ]); + this.loadAll(); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.page = 0; + this.currentSearch = query; + this.router.navigate([ + '/project', + { + search: this.currentSearch, + page: this.page, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + ]); + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().subscribe(account => { + this.currentAccount = account; + }); + this.registerChangeInProjects(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IProject) { + return item.id; + } + + byteSize(field) { + return this.dataUtils.byteSize(field); + } + + openFile(contentType, field) { + return this.dataUtils.openFile(contentType, field); + } + + registerChangeInProjects() { + this.eventSubscriber = this.eventManager.subscribe('projectListModification', response => this.loadAll()); + } + + sort() { + const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')]; + if (this.predicate !== 'id') { + result.push('id'); + } + return result; + } + + protected paginateProjects(data: IProject[], headers: HttpHeaders) { + this.links = this.parseLinks.parse(headers.get('link')); + this.totalItems = parseInt(headers.get('X-Total-Count'), 10); + this.projects = data; + } +} diff --git a/src/main/webapp/app/entities/project/project.module.ts b/src/main/webapp/app/entities/project/project.module.ts new file mode 100644 index 0000000..869110f --- /dev/null +++ b/src/main/webapp/app/entities/project/project.module.ts @@ -0,0 +1,24 @@ +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { CodeRecordApplicationSharedModule } from 'app/shared/shared.module'; +import { ProjectComponent } from './project.component'; +import { ProjectDetailComponent } from './project-detail.component'; +import { ProjectUpdateComponent } from './project-update.component'; +import { ProjectDeletePopupComponent, ProjectDeleteDialogComponent } from './project-delete-dialog.component'; +import { projectRoute, projectPopupRoute } from './project.route'; + +const ENTITY_STATES = [...projectRoute, ...projectPopupRoute]; + +@NgModule({ + imports: [CodeRecordApplicationSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + ProjectComponent, + ProjectDetailComponent, + ProjectUpdateComponent, + ProjectDeleteDialogComponent, + ProjectDeletePopupComponent + ], + entryComponents: [ProjectDeleteDialogComponent] +}) +export class CodeRecordApplicationProjectModule {} diff --git a/src/main/webapp/app/entities/project/project.route.ts b/src/main/webapp/app/entities/project/project.route.ts new file mode 100644 index 0000000..f0f736e --- /dev/null +++ b/src/main/webapp/app/entities/project/project.route.ts @@ -0,0 +1,98 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { JhiResolvePagingParams } from 'ng-jhipster'; +import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Project } from 'app/shared/model/project.model'; +import { ProjectService } from './project.service'; +import { ProjectComponent } from './project.component'; +import { ProjectDetailComponent } from './project-detail.component'; +import { ProjectUpdateComponent } from './project-update.component'; +import { ProjectDeletePopupComponent } from './project-delete-dialog.component'; +import { IProject } from 'app/shared/model/project.model'; + +@Injectable({ providedIn: 'root' }) +export class ProjectResolve implements Resolve { + constructor(private service: ProjectService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id']; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((project: HttpResponse) => project.body) + ); + } + return of(new Project()); + } +} + +export const projectRoute: Routes = [ + { + path: '', + component: ProjectComponent, + resolve: { + pagingParams: JhiResolvePagingParams + }, + data: { + authorities: ['ROLE_USER'], + defaultSort: 'id,asc', + pageTitle: 'codeRecordApplicationApp.project.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: ProjectDetailComponent, + resolve: { + project: ProjectResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.project.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: ProjectUpdateComponent, + resolve: { + project: ProjectResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.project.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: ProjectUpdateComponent, + resolve: { + project: ProjectResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.project.home.title' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const projectPopupRoute: Routes = [ + { + path: ':id/delete', + component: ProjectDeletePopupComponent, + resolve: { + project: ProjectResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.project.home.title' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/project/project.service.ts b/src/main/webapp/app/entities/project/project.service.ts new file mode 100644 index 0000000..395125c --- /dev/null +++ b/src/main/webapp/app/entities/project/project.service.ts @@ -0,0 +1,44 @@ +import { Injectable } from '@angular/core'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; + +import { SERVER_API_URL } from 'app/app.constants'; +import { createRequestOption } from 'app/shared/util/request-util'; +import { IProject } from 'app/shared/model/project.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class ProjectService { + public resourceUrl = SERVER_API_URL + 'api/projects'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/projects'; + + constructor(protected http: HttpClient) {} + + create(project: IProject): Observable { + return this.http.post(this.resourceUrl, project, { observe: 'response' }); + } + + update(project: IProject): Observable { + return this.http.put(this.resourceUrl, project, { observe: 'response' }); + } + + find(id: number): Observable { + return this.http.get(`${this.resourceUrl}/${id}`, { observe: 'response' }); + } + + query(req?: any): Observable { + const options = createRequestOption(req); + return this.http.get(this.resourceUrl, { params: options, observe: 'response' }); + } + + delete(id: number): Observable> { + return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); + } + + search(req?: any): Observable { + const options = createRequestOption(req); + return this.http.get(this.resourceSearchUrl, { params: options, observe: 'response' }); + } +} diff --git a/src/main/webapp/app/entities/submit-record/submit-record-delete-dialog.component.html b/src/main/webapp/app/entities/submit-record/submit-record-delete-dialog.component.html new file mode 100644 index 0000000..e10b7b6 --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/submit-record/submit-record-delete-dialog.component.ts b/src/main/webapp/app/entities/submit-record/submit-record-delete-dialog.component.ts new file mode 100644 index 0000000..78f2a71 --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record-delete-dialog.component.ts @@ -0,0 +1,69 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; + +import { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; +import { JhiEventManager } from 'ng-jhipster'; + +import { ISubmitRecord } from 'app/shared/model/submit-record.model'; +import { SubmitRecordService } from './submit-record.service'; + +@Component({ + selector: 'jhi-submit-record-delete-dialog', + templateUrl: './submit-record-delete-dialog.component.html' +}) +export class SubmitRecordDeleteDialogComponent { + submitRecord: ISubmitRecord; + + constructor( + protected submitRecordService: SubmitRecordService, + public activeModal: NgbActiveModal, + protected eventManager: JhiEventManager + ) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.submitRecordService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'submitRecordListModification', + content: 'Deleted an submitRecord' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-submit-record-delete-popup', + template: '' +}) +export class SubmitRecordDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ submitRecord }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(SubmitRecordDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.submitRecord = submitRecord; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/submit-record', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/submit-record', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/submit-record/submit-record-detail.component.html b/src/main/webapp/app/entities/submit-record/submit-record-detail.component.html new file mode 100644 index 0000000..fafae69 --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record-detail.component.html @@ -0,0 +1,43 @@ +
+
+
+

Submit Record {{submitRecord.id}}

+
+ +
+
Record Date
+
+ {{submitRecord.recordDate}} +
+
Cnt
+
+ {{submitRecord.cnt}} +
+
Developer
+
+ +
+
Project
+
+ +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/submit-record/submit-record-detail.component.ts b/src/main/webapp/app/entities/submit-record/submit-record-detail.component.ts new file mode 100644 index 0000000..e18676e --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { ISubmitRecord } from 'app/shared/model/submit-record.model'; + +@Component({ + selector: 'jhi-submit-record-detail', + templateUrl: './submit-record-detail.component.html' +}) +export class SubmitRecordDetailComponent implements OnInit { + submitRecord: ISubmitRecord; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ submitRecord }) => { + this.submitRecord = submitRecord; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/submit-record/submit-record-update.component.html b/src/main/webapp/app/entities/submit-record/submit-record-update.component.html new file mode 100644 index 0000000..d11430d --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record-update.component.html @@ -0,0 +1,68 @@ +
+
+
+

Create or edit a Submit Record

+
+ +
+ + +
+
+ +
+ + + + +
+
+ + This field is required. + +
+
+
+ + +
+ + This field is required. + + + This field should be a number. + +
+
+ +
+ + +
+
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/submit-record/submit-record-update.component.ts b/src/main/webapp/app/entities/submit-record/submit-record-update.component.ts new file mode 100644 index 0000000..7da1da9 --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record-update.component.ts @@ -0,0 +1,126 @@ +import { Component, OnInit } from '@angular/core'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import * as moment from 'moment'; +import { JhiAlertService } from 'ng-jhipster'; +import { ISubmitRecord, SubmitRecord } from 'app/shared/model/submit-record.model'; +import { SubmitRecordService } from './submit-record.service'; +import { IDeveloper } from 'app/shared/model/developer.model'; +import { DeveloperService } from 'app/entities/developer/developer.service'; +import { IProject } from 'app/shared/model/project.model'; +import { ProjectService } from 'app/entities/project/project.service'; + +@Component({ + selector: 'jhi-submit-record-update', + templateUrl: './submit-record-update.component.html' +}) +export class SubmitRecordUpdateComponent implements OnInit { + isSaving: boolean; + + developers: IDeveloper[]; + + projects: IProject[]; + recordDateDp: any; + + editForm = this.fb.group({ + id: [], + recordDate: [null, [Validators.required]], + cnt: [null, [Validators.required]], + developerId: [], + projectId: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected submitRecordService: SubmitRecordService, + protected developerService: DeveloperService, + protected projectService: ProjectService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ submitRecord }) => { + this.updateForm(submitRecord); + }); + this.developerService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: IDeveloper[]) => (this.developers = res), (res: HttpErrorResponse) => this.onError(res.message)); + this.projectService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: IProject[]) => (this.projects = res), (res: HttpErrorResponse) => this.onError(res.message)); + } + + updateForm(submitRecord: ISubmitRecord) { + this.editForm.patchValue({ + id: submitRecord.id, + recordDate: submitRecord.recordDate, + cnt: submitRecord.cnt, + developerId: submitRecord.developerId, + projectId: submitRecord.projectId + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const submitRecord = this.createFromForm(); + if (submitRecord.id !== undefined) { + this.subscribeToSaveResponse(this.submitRecordService.update(submitRecord)); + } else { + this.subscribeToSaveResponse(this.submitRecordService.create(submitRecord)); + } + } + + private createFromForm(): ISubmitRecord { + return { + ...new SubmitRecord(), + id: this.editForm.get(['id']).value, + recordDate: this.editForm.get(['recordDate']).value, + cnt: this.editForm.get(['cnt']).value, + developerId: this.editForm.get(['developerId']).value, + projectId: this.editForm.get(['projectId']).value + }; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe(() => this.onSaveSuccess(), () => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackDeveloperById(index: number, item: IDeveloper) { + return item.id; + } + + trackProjectById(index: number, item: IProject) { + return item.id; + } +} diff --git a/src/main/webapp/app/entities/submit-record/submit-record.component.html b/src/main/webapp/app/entities/submit-record/submit-record.component.html new file mode 100644 index 0000000..43c0c4b --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record.component.html @@ -0,0 +1,95 @@ +
+

+ Submit Records + +

+ + +
+
+
+
+ + + +
+
+
+
+
+
+ No submitRecords found +
+
+ + + + + + + + + + + + + + + + + + + + + +
ID Record Date Cnt Developer Project
{{submitRecord.id}}{{submitRecord.recordDate | date:'mediumDate'}}{{submitRecord.cnt}} + + + + +
+ + + +
+
+
+
+
+ +
+
+ +
+
+
diff --git a/src/main/webapp/app/entities/submit-record/submit-record.component.ts b/src/main/webapp/app/entities/submit-record/submit-record.component.ts new file mode 100644 index 0000000..521a88b --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record.component.ts @@ -0,0 +1,159 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Router } from '@angular/router'; +import { Subscription } from 'rxjs'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiParseLinks } from 'ng-jhipster'; + +import { ISubmitRecord } from 'app/shared/model/submit-record.model'; +import { AccountService } from 'app/core/auth/account.service'; + +import { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants'; +import { SubmitRecordService } from './submit-record.service'; + +@Component({ + selector: 'jhi-submit-record', + templateUrl: './submit-record.component.html' +}) +export class SubmitRecordComponent implements OnInit, OnDestroy { + currentAccount: any; + submitRecords: ISubmitRecord[]; + error: any; + success: any; + eventSubscriber: Subscription; + currentSearch: string; + routeData: any; + links: any; + totalItems: any; + itemsPerPage: any; + page: any; + predicate: any; + previousPage: any; + reverse: any; + + constructor( + protected submitRecordService: SubmitRecordService, + protected parseLinks: JhiParseLinks, + protected accountService: AccountService, + protected activatedRoute: ActivatedRoute, + protected router: Router, + protected eventManager: JhiEventManager + ) { + this.itemsPerPage = ITEMS_PER_PAGE; + this.routeData = this.activatedRoute.data.subscribe(data => { + this.page = data.pagingParams.page; + this.previousPage = data.pagingParams.page; + this.reverse = data.pagingParams.ascending; + this.predicate = data.pagingParams.predicate; + }); + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.queryParams['search'] + ? this.activatedRoute.snapshot.queryParams['search'] + : ''; + } + + loadAll() { + if (this.currentSearch) { + this.submitRecordService + .search({ + page: this.page - 1, + query: this.currentSearch, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe((res: HttpResponse) => this.paginateSubmitRecords(res.body, res.headers)); + return; + } + this.submitRecordService + .query({ + page: this.page - 1, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe((res: HttpResponse) => this.paginateSubmitRecords(res.body, res.headers)); + } + + loadPage(page: number) { + if (page !== this.previousPage) { + this.previousPage = page; + this.transition(); + } + } + + transition() { + this.router.navigate(['/submit-record'], { + queryParams: { + page: this.page, + size: this.itemsPerPage, + search: this.currentSearch, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + }); + this.loadAll(); + } + + clear() { + this.page = 0; + this.currentSearch = ''; + this.router.navigate([ + '/submit-record', + { + page: this.page, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + ]); + this.loadAll(); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.page = 0; + this.currentSearch = query; + this.router.navigate([ + '/submit-record', + { + search: this.currentSearch, + page: this.page, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + ]); + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().subscribe(account => { + this.currentAccount = account; + }); + this.registerChangeInSubmitRecords(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: ISubmitRecord) { + return item.id; + } + + registerChangeInSubmitRecords() { + this.eventSubscriber = this.eventManager.subscribe('submitRecordListModification', response => this.loadAll()); + } + + sort() { + const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')]; + if (this.predicate !== 'id') { + result.push('id'); + } + return result; + } + + protected paginateSubmitRecords(data: ISubmitRecord[], headers: HttpHeaders) { + this.links = this.parseLinks.parse(headers.get('link')); + this.totalItems = parseInt(headers.get('X-Total-Count'), 10); + this.submitRecords = data; + } +} diff --git a/src/main/webapp/app/entities/submit-record/submit-record.module.ts b/src/main/webapp/app/entities/submit-record/submit-record.module.ts new file mode 100644 index 0000000..9009f23 --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record.module.ts @@ -0,0 +1,24 @@ +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { CodeRecordApplicationSharedModule } from 'app/shared/shared.module'; +import { SubmitRecordComponent } from './submit-record.component'; +import { SubmitRecordDetailComponent } from './submit-record-detail.component'; +import { SubmitRecordUpdateComponent } from './submit-record-update.component'; +import { SubmitRecordDeletePopupComponent, SubmitRecordDeleteDialogComponent } from './submit-record-delete-dialog.component'; +import { submitRecordRoute, submitRecordPopupRoute } from './submit-record.route'; + +const ENTITY_STATES = [...submitRecordRoute, ...submitRecordPopupRoute]; + +@NgModule({ + imports: [CodeRecordApplicationSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + SubmitRecordComponent, + SubmitRecordDetailComponent, + SubmitRecordUpdateComponent, + SubmitRecordDeleteDialogComponent, + SubmitRecordDeletePopupComponent + ], + entryComponents: [SubmitRecordDeleteDialogComponent] +}) +export class CodeRecordApplicationSubmitRecordModule {} diff --git a/src/main/webapp/app/entities/submit-record/submit-record.route.ts b/src/main/webapp/app/entities/submit-record/submit-record.route.ts new file mode 100644 index 0000000..612b36d --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record.route.ts @@ -0,0 +1,98 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { JhiResolvePagingParams } from 'ng-jhipster'; +import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { SubmitRecord } from 'app/shared/model/submit-record.model'; +import { SubmitRecordService } from './submit-record.service'; +import { SubmitRecordComponent } from './submit-record.component'; +import { SubmitRecordDetailComponent } from './submit-record-detail.component'; +import { SubmitRecordUpdateComponent } from './submit-record-update.component'; +import { SubmitRecordDeletePopupComponent } from './submit-record-delete-dialog.component'; +import { ISubmitRecord } from 'app/shared/model/submit-record.model'; + +@Injectable({ providedIn: 'root' }) +export class SubmitRecordResolve implements Resolve { + constructor(private service: SubmitRecordService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id']; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((submitRecord: HttpResponse) => submitRecord.body) + ); + } + return of(new SubmitRecord()); + } +} + +export const submitRecordRoute: Routes = [ + { + path: '', + component: SubmitRecordComponent, + resolve: { + pagingParams: JhiResolvePagingParams + }, + data: { + authorities: ['ROLE_USER'], + defaultSort: 'id,asc', + pageTitle: 'codeRecordApplicationApp.submitRecord.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: SubmitRecordDetailComponent, + resolve: { + submitRecord: SubmitRecordResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.submitRecord.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: SubmitRecordUpdateComponent, + resolve: { + submitRecord: SubmitRecordResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.submitRecord.home.title' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: SubmitRecordUpdateComponent, + resolve: { + submitRecord: SubmitRecordResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.submitRecord.home.title' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const submitRecordPopupRoute: Routes = [ + { + path: ':id/delete', + component: SubmitRecordDeletePopupComponent, + resolve: { + submitRecord: SubmitRecordResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'codeRecordApplicationApp.submitRecord.home.title' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/submit-record/submit-record.service.ts b/src/main/webapp/app/entities/submit-record/submit-record.service.ts new file mode 100644 index 0000000..6c02193 --- /dev/null +++ b/src/main/webapp/app/entities/submit-record/submit-record.service.ts @@ -0,0 +1,83 @@ +import { Injectable } from '@angular/core'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import * as moment from 'moment'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { DATE_FORMAT } from 'app/shared/constants/input.constants'; +import { map } from 'rxjs/operators'; + +import { SERVER_API_URL } from 'app/app.constants'; +import { createRequestOption } from 'app/shared/util/request-util'; +import { ISubmitRecord } from 'app/shared/model/submit-record.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class SubmitRecordService { + public resourceUrl = SERVER_API_URL + 'api/submit-records'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/submit-records'; + + constructor(protected http: HttpClient) {} + + create(submitRecord: ISubmitRecord): Observable { + const copy = this.convertDateFromClient(submitRecord); + return this.http + .post(this.resourceUrl, copy, { observe: 'response' }) + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); + } + + update(submitRecord: ISubmitRecord): Observable { + const copy = this.convertDateFromClient(submitRecord); + return this.http + .put(this.resourceUrl, copy, { observe: 'response' }) + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); + } + + find(id: number): Observable { + return this.http + .get(`${this.resourceUrl}/${id}`, { observe: 'response' }) + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); + } + + query(req?: any): Observable { + const options = createRequestOption(req); + return this.http + .get(this.resourceUrl, { params: options, observe: 'response' }) + .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res))); + } + + delete(id: number): Observable> { + return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); + } + + search(req?: any): Observable { + const options = createRequestOption(req); + return this.http + .get(this.resourceSearchUrl, { params: options, observe: 'response' }) + .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res))); + } + + protected convertDateFromClient(submitRecord: ISubmitRecord): ISubmitRecord { + const copy: ISubmitRecord = Object.assign({}, submitRecord, { + recordDate: submitRecord.recordDate != null && submitRecord.recordDate.isValid() ? submitRecord.recordDate.format(DATE_FORMAT) : null + }); + return copy; + } + + protected convertDateFromServer(res: EntityResponseType): EntityResponseType { + if (res.body) { + res.body.recordDate = res.body.recordDate != null ? moment(res.body.recordDate) : null; + } + return res; + } + + protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType { + if (res.body) { + res.body.forEach((submitRecord: ISubmitRecord) => { + submitRecord.recordDate = submitRecord.recordDate != null ? moment(submitRecord.recordDate) : null; + }); + } + return res; + } +} diff --git a/src/main/webapp/app/layouts/navbar/navbar.component.html b/src/main/webapp/app/layouts/navbar/navbar.component.html index 41104dd..d0a6ffd 100644 --- a/src/main/webapp/app/layouts/navbar/navbar.component.html +++ b/src/main/webapp/app/layouts/navbar/navbar.component.html @@ -27,6 +27,24 @@ diff --git a/src/main/webapp/app/shared/model/developer.model.ts b/src/main/webapp/app/shared/model/developer.model.ts new file mode 100644 index 0000000..96d9b61 --- /dev/null +++ b/src/main/webapp/app/shared/model/developer.model.ts @@ -0,0 +1,8 @@ +export interface IDeveloper { + id?: number; + name?: string; +} + +export class Developer implements IDeveloper { + constructor(public id?: number, public name?: string) {} +} diff --git a/src/main/webapp/app/shared/model/project.model.ts b/src/main/webapp/app/shared/model/project.model.ts new file mode 100644 index 0000000..89046e6 --- /dev/null +++ b/src/main/webapp/app/shared/model/project.model.ts @@ -0,0 +1,10 @@ +export interface IProject { + id?: number; + name?: string; + code?: string; + desc?: any; +} + +export class Project implements IProject { + constructor(public id?: number, public name?: string, public code?: string, public desc?: any) {} +} diff --git a/src/main/webapp/app/shared/model/submit-record.model.ts b/src/main/webapp/app/shared/model/submit-record.model.ts new file mode 100644 index 0000000..80bb95f --- /dev/null +++ b/src/main/webapp/app/shared/model/submit-record.model.ts @@ -0,0 +1,23 @@ +import { Moment } from 'moment'; + +export interface ISubmitRecord { + id?: number; + recordDate?: Moment; + cnt?: number; + developerName?: string; + developerId?: number; + projectName?: string; + projectId?: number; +} + +export class SubmitRecord implements ISubmitRecord { + constructor( + public id?: number, + public recordDate?: Moment, + public cnt?: number, + public developerName?: string, + public developerId?: number, + public projectName?: string, + public projectId?: number + ) {} +} diff --git a/src/main/webapp/i18n/en/developer.json b/src/main/webapp/i18n/en/developer.json new file mode 100644 index 0000000..e1421c5 --- /dev/null +++ b/src/main/webapp/i18n/en/developer.json @@ -0,0 +1,26 @@ +{ + "codeRecordApplicationApp": { + "developer": { + "home": { + "title": "Developers", + "createLabel": "Create a new Developer", + "createOrEditLabel": "Create or edit a Developer", + "search": "Search for Developer", + "notFound": "No Developers found" + }, + "created": "A new Developer is created with identifier {{ param }}", + "updated": "A Developer is updated with identifier {{ param }}", + "deleted": "A Developer is deleted with identifier {{ param }}", + "delete": { + "question": "Are you sure you want to delete Developer {{ id }}?" + }, + "detail": { + "title": "Developer" + }, + "name": "Name", + "help": { + "name": "开发人员姓名" + } + } + } +} diff --git a/src/main/webapp/i18n/en/global.json b/src/main/webapp/i18n/en/global.json index f91a3fd..a5e3591 100644 --- a/src/main/webapp/i18n/en/global.json +++ b/src/main/webapp/i18n/en/global.json @@ -7,6 +7,9 @@ "jhipster-needle-menu-add-element": "JHipster will add additional menu entries here (do not translate!)", "entities": { "main": "Entities", + "project": "Project", + "developer": "Developer", + "submitRecord": "Submit Record", "jhipster-needle-menu-add-entry": "JHipster will add additional entities here (do not translate!)" }, "account": { diff --git a/src/main/webapp/i18n/en/project.json b/src/main/webapp/i18n/en/project.json new file mode 100644 index 0000000..c3a1c89 --- /dev/null +++ b/src/main/webapp/i18n/en/project.json @@ -0,0 +1,30 @@ +{ + "codeRecordApplicationApp": { + "project": { + "home": { + "title": "Projects", + "createLabel": "Create a new Project", + "createOrEditLabel": "Create or edit a Project", + "search": "Search for Project", + "notFound": "No Projects found" + }, + "created": "A new Project is created with identifier {{ param }}", + "updated": "A Project is updated with identifier {{ param }}", + "deleted": "A Project is deleted with identifier {{ param }}", + "delete": { + "question": "Are you sure you want to delete Project {{ id }}?" + }, + "detail": { + "title": "Project" + }, + "name": "Name", + "code": "Code", + "desc": "Desc", + "help": { + "name": "项目名称", + "code": "项目编号", + "desc": "备注" + } + } + } +} diff --git a/src/main/webapp/i18n/en/submitRecord.json b/src/main/webapp/i18n/en/submitRecord.json new file mode 100644 index 0000000..9967a45 --- /dev/null +++ b/src/main/webapp/i18n/en/submitRecord.json @@ -0,0 +1,30 @@ +{ + "codeRecordApplicationApp": { + "submitRecord": { + "home": { + "title": "Submit Records", + "createLabel": "Create a new Submit Record", + "createOrEditLabel": "Create or edit a Submit Record", + "search": "Search for Submit Record", + "notFound": "No Submit Records found" + }, + "created": "A new Submit Record is created with identifier {{ param }}", + "updated": "A Submit Record is updated with identifier {{ param }}", + "deleted": "A Submit Record is deleted with identifier {{ param }}", + "delete": { + "question": "Are you sure you want to delete Submit Record {{ id }}?" + }, + "detail": { + "title": "Submit Record" + }, + "recordDate": "Record Date", + "cnt": "Cnt", + "developer": "Developer", + "project": "Project", + "help": { + "recordDate": "记录时间", + "cnt": "代码行数" + } + } + } +} diff --git a/src/main/webapp/i18n/zh-cn/developer.json b/src/main/webapp/i18n/zh-cn/developer.json new file mode 100644 index 0000000..9034e9c --- /dev/null +++ b/src/main/webapp/i18n/zh-cn/developer.json @@ -0,0 +1,26 @@ +{ + "codeRecordApplicationApp": { + "developer": { + "home": { + "title": "Developers", + "createLabel": "创建新 Developer", + "createOrEditLabel": "创建或编辑 Developer", + "search": "查找 Developer", + "notFound": "No Developers found" + }, + "created": "Developer {{ param }} 创建成功", + "updated": "Developer {{ param }} 更新成功", + "deleted": "Developer {{ param }} 删除成功", + "delete": { + "question": "你确定要删除 Developer {{ id }} 吗?" + }, + "detail": { + "title": "Developer" + }, + "name": "Name", + "help": { + "name": "开发人员姓名" + } + } + } +} diff --git a/src/main/webapp/i18n/zh-cn/global.json b/src/main/webapp/i18n/zh-cn/global.json index 4ea2708..e0a25d9 100644 --- a/src/main/webapp/i18n/zh-cn/global.json +++ b/src/main/webapp/i18n/zh-cn/global.json @@ -7,6 +7,9 @@ "jhipster-needle-menu-add-element": "JHipster will add additional menu entries here (do not translate!)", "entities": { "main": "数据", + "project": "Project", + "developer": "Developer", + "submitRecord": "Submit Record", "jhipster-needle-menu-add-entry": "JHipster will add additional entities here (do not translate!)" }, "account": { diff --git a/src/main/webapp/i18n/zh-cn/project.json b/src/main/webapp/i18n/zh-cn/project.json new file mode 100644 index 0000000..114e0de --- /dev/null +++ b/src/main/webapp/i18n/zh-cn/project.json @@ -0,0 +1,30 @@ +{ + "codeRecordApplicationApp": { + "project": { + "home": { + "title": "Projects", + "createLabel": "创建新 Project", + "createOrEditLabel": "创建或编辑 Project", + "search": "查找 Project", + "notFound": "No Projects found" + }, + "created": "Project {{ param }} 创建成功", + "updated": "Project {{ param }} 更新成功", + "deleted": "Project {{ param }} 删除成功", + "delete": { + "question": "你确定要删除 Project {{ id }} 吗?" + }, + "detail": { + "title": "Project" + }, + "name": "Name", + "code": "Code", + "desc": "Desc", + "help": { + "name": "项目名称", + "code": "项目编号", + "desc": "备注" + } + } + } +} diff --git a/src/main/webapp/i18n/zh-cn/submitRecord.json b/src/main/webapp/i18n/zh-cn/submitRecord.json new file mode 100644 index 0000000..e841722 --- /dev/null +++ b/src/main/webapp/i18n/zh-cn/submitRecord.json @@ -0,0 +1,30 @@ +{ + "codeRecordApplicationApp": { + "submitRecord": { + "home": { + "title": "Submit Records", + "createLabel": "创建新 Submit Record", + "createOrEditLabel": "创建或编辑 Submit Record", + "search": "查找 Submit Record", + "notFound": "No Submit Records found" + }, + "created": "Submit Record {{ param }} 创建成功", + "updated": "Submit Record {{ param }} 更新成功", + "deleted": "Submit Record {{ param }} 删除成功", + "delete": { + "question": "你确定要删除 Submit Record {{ id }} 吗?" + }, + "detail": { + "title": "Submit Record" + }, + "recordDate": "Record Date", + "cnt": "Cnt", + "developer": "Developer", + "project": "Project", + "help": { + "recordDate": "记录时间", + "cnt": "代码行数" + } + } + } +} diff --git a/src/test/java/com/aiyun/code/record/repository/search/DeveloperSearchRepositoryMockConfiguration.java b/src/test/java/com/aiyun/code/record/repository/search/DeveloperSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..173f368 --- /dev/null +++ b/src/test/java/com/aiyun/code/record/repository/search/DeveloperSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package com.aiyun.code.record.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link DeveloperSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class DeveloperSearchRepositoryMockConfiguration { + + @MockBean + private DeveloperSearchRepository mockDeveloperSearchRepository; + +} diff --git a/src/test/java/com/aiyun/code/record/repository/search/ProjectSearchRepositoryMockConfiguration.java b/src/test/java/com/aiyun/code/record/repository/search/ProjectSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..0f7ff8b --- /dev/null +++ b/src/test/java/com/aiyun/code/record/repository/search/ProjectSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package com.aiyun.code.record.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link ProjectSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class ProjectSearchRepositoryMockConfiguration { + + @MockBean + private ProjectSearchRepository mockProjectSearchRepository; + +} diff --git a/src/test/java/com/aiyun/code/record/repository/search/SubmitRecordSearchRepositoryMockConfiguration.java b/src/test/java/com/aiyun/code/record/repository/search/SubmitRecordSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..521567f --- /dev/null +++ b/src/test/java/com/aiyun/code/record/repository/search/SubmitRecordSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package com.aiyun.code.record.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link SubmitRecordSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class SubmitRecordSearchRepositoryMockConfiguration { + + @MockBean + private SubmitRecordSearchRepository mockSubmitRecordSearchRepository; + +} diff --git a/src/test/java/com/aiyun/code/record/web/rest/DeveloperResourceIT.java b/src/test/java/com/aiyun/code/record/web/rest/DeveloperResourceIT.java new file mode 100644 index 0000000..add4aa1 --- /dev/null +++ b/src/test/java/com/aiyun/code/record/web/rest/DeveloperResourceIT.java @@ -0,0 +1,351 @@ +package com.aiyun.code.record.web.rest; + +import com.aiyun.code.record.CodeRecordApplicationApp; +import com.aiyun.code.record.domain.Developer; +import com.aiyun.code.record.repository.DeveloperRepository; +import com.aiyun.code.record.repository.search.DeveloperSearchRepository; +import com.aiyun.code.record.service.DeveloperService; +import com.aiyun.code.record.service.dto.DeveloperDTO; +import com.aiyun.code.record.service.mapper.DeveloperMapper; +import com.aiyun.code.record.web.rest.errors.ExceptionTranslator; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Validator; + +import javax.persistence.EntityManager; +import java.util.Collections; +import java.util.List; + +import static com.aiyun.code.record.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Integration tests for the {@link DeveloperResource} REST controller. + */ +@SpringBootTest(classes = CodeRecordApplicationApp.class) +public class DeveloperResourceIT { + + private static final String DEFAULT_NAME = "AAAAAAAAAA"; + private static final String UPDATED_NAME = "BBBBBBBBBB"; + + @Autowired + private DeveloperRepository developerRepository; + + @Autowired + private DeveloperMapper developerMapper; + + @Autowired + private DeveloperService developerService; + + /** + * This repository is mocked in the com.aiyun.code.record.repository.search test package. + * + * @see com.aiyun.code.record.repository.search.DeveloperSearchRepositoryMockConfiguration + */ + @Autowired + private DeveloperSearchRepository mockDeveloperSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restDeveloperMockMvc; + + private Developer developer; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final DeveloperResource developerResource = new DeveloperResource(developerService); + this.restDeveloperMockMvc = MockMvcBuilders.standaloneSetup(developerResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator).build(); + } + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Developer createEntity(EntityManager em) { + Developer developer = new Developer() + .name(DEFAULT_NAME); + return developer; + } + /** + * 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 Developer createUpdatedEntity(EntityManager em) { + Developer developer = new Developer() + .name(UPDATED_NAME); + return developer; + } + + @BeforeEach + public void initTest() { + developer = createEntity(em); + } + + @Test + @Transactional + public void createDeveloper() throws Exception { + int databaseSizeBeforeCreate = developerRepository.findAll().size(); + + // Create the Developer + DeveloperDTO developerDTO = developerMapper.toDto(developer); + restDeveloperMockMvc.perform(post("/api/developers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(developerDTO))) + .andExpect(status().isCreated()); + + // Validate the Developer in the database + List developerList = developerRepository.findAll(); + assertThat(developerList).hasSize(databaseSizeBeforeCreate + 1); + Developer testDeveloper = developerList.get(developerList.size() - 1); + assertThat(testDeveloper.getName()).isEqualTo(DEFAULT_NAME); + + // Validate the Developer in Elasticsearch + verify(mockDeveloperSearchRepository, times(1)).save(testDeveloper); + } + + @Test + @Transactional + public void createDeveloperWithExistingId() throws Exception { + int databaseSizeBeforeCreate = developerRepository.findAll().size(); + + // Create the Developer with an existing ID + developer.setId(1L); + DeveloperDTO developerDTO = developerMapper.toDto(developer); + + // An entity with an existing ID cannot be created, so this API call must fail + restDeveloperMockMvc.perform(post("/api/developers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(developerDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Developer in the database + List developerList = developerRepository.findAll(); + assertThat(developerList).hasSize(databaseSizeBeforeCreate); + + // Validate the Developer in Elasticsearch + verify(mockDeveloperSearchRepository, times(0)).save(developer); + } + + + @Test + @Transactional + public void checkNameIsRequired() throws Exception { + int databaseSizeBeforeTest = developerRepository.findAll().size(); + // set the field null + developer.setName(null); + + // Create the Developer, which fails. + DeveloperDTO developerDTO = developerMapper.toDto(developer); + + restDeveloperMockMvc.perform(post("/api/developers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(developerDTO))) + .andExpect(status().isBadRequest()); + + List developerList = developerRepository.findAll(); + assertThat(developerList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void getAllDevelopers() throws Exception { + // Initialize the database + developerRepository.saveAndFlush(developer); + + // Get all the developerList + restDeveloperMockMvc.perform(get("/api/developers?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(developer.getId().intValue()))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))); + } + + @Test + @Transactional + public void getDeveloper() throws Exception { + // Initialize the database + developerRepository.saveAndFlush(developer); + + // Get the developer + restDeveloperMockMvc.perform(get("/api/developers/{id}", developer.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(developer.getId().intValue())) + .andExpect(jsonPath("$.name").value(DEFAULT_NAME)); + } + + @Test + @Transactional + public void getNonExistingDeveloper() throws Exception { + // Get the developer + restDeveloperMockMvc.perform(get("/api/developers/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateDeveloper() throws Exception { + // Initialize the database + developerRepository.saveAndFlush(developer); + + int databaseSizeBeforeUpdate = developerRepository.findAll().size(); + + // Update the developer + Developer updatedDeveloper = developerRepository.findById(developer.getId()).get(); + // Disconnect from session so that the updates on updatedDeveloper are not directly saved in db + em.detach(updatedDeveloper); + updatedDeveloper + .name(UPDATED_NAME); + DeveloperDTO developerDTO = developerMapper.toDto(updatedDeveloper); + + restDeveloperMockMvc.perform(put("/api/developers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(developerDTO))) + .andExpect(status().isOk()); + + // Validate the Developer in the database + List developerList = developerRepository.findAll(); + assertThat(developerList).hasSize(databaseSizeBeforeUpdate); + Developer testDeveloper = developerList.get(developerList.size() - 1); + assertThat(testDeveloper.getName()).isEqualTo(UPDATED_NAME); + + // Validate the Developer in Elasticsearch + verify(mockDeveloperSearchRepository, times(1)).save(testDeveloper); + } + + @Test + @Transactional + public void updateNonExistingDeveloper() throws Exception { + int databaseSizeBeforeUpdate = developerRepository.findAll().size(); + + // Create the Developer + DeveloperDTO developerDTO = developerMapper.toDto(developer); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restDeveloperMockMvc.perform(put("/api/developers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(developerDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Developer in the database + List developerList = developerRepository.findAll(); + assertThat(developerList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Developer in Elasticsearch + verify(mockDeveloperSearchRepository, times(0)).save(developer); + } + + @Test + @Transactional + public void deleteDeveloper() throws Exception { + // Initialize the database + developerRepository.saveAndFlush(developer); + + int databaseSizeBeforeDelete = developerRepository.findAll().size(); + + // Delete the developer + restDeveloperMockMvc.perform(delete("/api/developers/{id}", developer.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + List developerList = developerRepository.findAll(); + assertThat(developerList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Developer in Elasticsearch + verify(mockDeveloperSearchRepository, times(1)).deleteById(developer.getId()); + } + + @Test + @Transactional + public void searchDeveloper() throws Exception { + // Initialize the database + developerRepository.saveAndFlush(developer); + when(mockDeveloperSearchRepository.search(queryStringQuery("id:" + developer.getId()), PageRequest.of(0, 20))) + .thenReturn(new PageImpl<>(Collections.singletonList(developer), PageRequest.of(0, 1), 1)); + // Search the developer + restDeveloperMockMvc.perform(get("/api/_search/developers?query=id:" + developer.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(developer.getId().intValue()))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Developer.class); + Developer developer1 = new Developer(); + developer1.setId(1L); + Developer developer2 = new Developer(); + developer2.setId(developer1.getId()); + assertThat(developer1).isEqualTo(developer2); + developer2.setId(2L); + assertThat(developer1).isNotEqualTo(developer2); + developer1.setId(null); + assertThat(developer1).isNotEqualTo(developer2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(DeveloperDTO.class); + DeveloperDTO developerDTO1 = new DeveloperDTO(); + developerDTO1.setId(1L); + DeveloperDTO developerDTO2 = new DeveloperDTO(); + assertThat(developerDTO1).isNotEqualTo(developerDTO2); + developerDTO2.setId(developerDTO1.getId()); + assertThat(developerDTO1).isEqualTo(developerDTO2); + developerDTO2.setId(2L); + assertThat(developerDTO1).isNotEqualTo(developerDTO2); + developerDTO1.setId(null); + assertThat(developerDTO1).isNotEqualTo(developerDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(developerMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(developerMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/com/aiyun/code/record/web/rest/ProjectResourceIT.java b/src/test/java/com/aiyun/code/record/web/rest/ProjectResourceIT.java new file mode 100644 index 0000000..3c9ebff --- /dev/null +++ b/src/test/java/com/aiyun/code/record/web/rest/ProjectResourceIT.java @@ -0,0 +1,393 @@ +package com.aiyun.code.record.web.rest; + +import com.aiyun.code.record.CodeRecordApplicationApp; +import com.aiyun.code.record.domain.Project; +import com.aiyun.code.record.repository.ProjectRepository; +import com.aiyun.code.record.repository.search.ProjectSearchRepository; +import com.aiyun.code.record.service.ProjectService; +import com.aiyun.code.record.service.dto.ProjectDTO; +import com.aiyun.code.record.service.mapper.ProjectMapper; +import com.aiyun.code.record.web.rest.errors.ExceptionTranslator; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Base64Utils; +import org.springframework.validation.Validator; + +import javax.persistence.EntityManager; +import java.util.Collections; +import java.util.List; + +import static com.aiyun.code.record.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Integration tests for the {@link ProjectResource} REST controller. + */ +@SpringBootTest(classes = CodeRecordApplicationApp.class) +public class ProjectResourceIT { + + private static final String DEFAULT_NAME = "AAAAAAAAAA"; + private static final String UPDATED_NAME = "BBBBBBBBBB"; + + private static final String DEFAULT_CODE = "AAAAAAAAAA"; + private static final String UPDATED_CODE = "BBBBBBBBBB"; + + private static final String DEFAULT_DESC = "AAAAAAAAAA"; + private static final String UPDATED_DESC = "BBBBBBBBBB"; + + @Autowired + private ProjectRepository projectRepository; + + @Autowired + private ProjectMapper projectMapper; + + @Autowired + private ProjectService projectService; + + /** + * This repository is mocked in the com.aiyun.code.record.repository.search test package. + * + * @see com.aiyun.code.record.repository.search.ProjectSearchRepositoryMockConfiguration + */ + @Autowired + private ProjectSearchRepository mockProjectSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restProjectMockMvc; + + private Project project; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final ProjectResource projectResource = new ProjectResource(projectService); + this.restProjectMockMvc = MockMvcBuilders.standaloneSetup(projectResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator).build(); + } + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static Project createEntity(EntityManager em) { + Project project = new Project() + .name(DEFAULT_NAME) + .code(DEFAULT_CODE) + .desc(DEFAULT_DESC); + return project; + } + /** + * 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 Project createUpdatedEntity(EntityManager em) { + Project project = new Project() + .name(UPDATED_NAME) + .code(UPDATED_CODE) + .desc(UPDATED_DESC); + return project; + } + + @BeforeEach + public void initTest() { + project = createEntity(em); + } + + @Test + @Transactional + public void createProject() throws Exception { + int databaseSizeBeforeCreate = projectRepository.findAll().size(); + + // Create the Project + ProjectDTO projectDTO = projectMapper.toDto(project); + restProjectMockMvc.perform(post("/api/projects") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(projectDTO))) + .andExpect(status().isCreated()); + + // Validate the Project in the database + List projectList = projectRepository.findAll(); + assertThat(projectList).hasSize(databaseSizeBeforeCreate + 1); + Project testProject = projectList.get(projectList.size() - 1); + assertThat(testProject.getName()).isEqualTo(DEFAULT_NAME); + assertThat(testProject.getCode()).isEqualTo(DEFAULT_CODE); + assertThat(testProject.getDesc()).isEqualTo(DEFAULT_DESC); + + // Validate the Project in Elasticsearch + verify(mockProjectSearchRepository, times(1)).save(testProject); + } + + @Test + @Transactional + public void createProjectWithExistingId() throws Exception { + int databaseSizeBeforeCreate = projectRepository.findAll().size(); + + // Create the Project with an existing ID + project.setId(1L); + ProjectDTO projectDTO = projectMapper.toDto(project); + + // An entity with an existing ID cannot be created, so this API call must fail + restProjectMockMvc.perform(post("/api/projects") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(projectDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Project in the database + List projectList = projectRepository.findAll(); + assertThat(projectList).hasSize(databaseSizeBeforeCreate); + + // Validate the Project in Elasticsearch + verify(mockProjectSearchRepository, times(0)).save(project); + } + + + @Test + @Transactional + public void checkNameIsRequired() throws Exception { + int databaseSizeBeforeTest = projectRepository.findAll().size(); + // set the field null + project.setName(null); + + // Create the Project, which fails. + ProjectDTO projectDTO = projectMapper.toDto(project); + + restProjectMockMvc.perform(post("/api/projects") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(projectDTO))) + .andExpect(status().isBadRequest()); + + List projectList = projectRepository.findAll(); + assertThat(projectList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void checkCodeIsRequired() throws Exception { + int databaseSizeBeforeTest = projectRepository.findAll().size(); + // set the field null + project.setCode(null); + + // Create the Project, which fails. + ProjectDTO projectDTO = projectMapper.toDto(project); + + restProjectMockMvc.perform(post("/api/projects") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(projectDTO))) + .andExpect(status().isBadRequest()); + + List projectList = projectRepository.findAll(); + assertThat(projectList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void getAllProjects() throws Exception { + // Initialize the database + projectRepository.saveAndFlush(project); + + // Get all the projectList + restProjectMockMvc.perform(get("/api/projects?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(project.getId().intValue()))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) + .andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE))) + .andExpect(jsonPath("$.[*].desc").value(hasItem(DEFAULT_DESC.toString()))); + } + + @Test + @Transactional + public void getProject() throws Exception { + // Initialize the database + projectRepository.saveAndFlush(project); + + // Get the project + restProjectMockMvc.perform(get("/api/projects/{id}", project.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(project.getId().intValue())) + .andExpect(jsonPath("$.name").value(DEFAULT_NAME)) + .andExpect(jsonPath("$.code").value(DEFAULT_CODE)) + .andExpect(jsonPath("$.desc").value(DEFAULT_DESC.toString())); + } + + @Test + @Transactional + public void getNonExistingProject() throws Exception { + // Get the project + restProjectMockMvc.perform(get("/api/projects/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateProject() throws Exception { + // Initialize the database + projectRepository.saveAndFlush(project); + + int databaseSizeBeforeUpdate = projectRepository.findAll().size(); + + // Update the project + Project updatedProject = projectRepository.findById(project.getId()).get(); + // Disconnect from session so that the updates on updatedProject are not directly saved in db + em.detach(updatedProject); + updatedProject + .name(UPDATED_NAME) + .code(UPDATED_CODE) + .desc(UPDATED_DESC); + ProjectDTO projectDTO = projectMapper.toDto(updatedProject); + + restProjectMockMvc.perform(put("/api/projects") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(projectDTO))) + .andExpect(status().isOk()); + + // Validate the Project in the database + List projectList = projectRepository.findAll(); + assertThat(projectList).hasSize(databaseSizeBeforeUpdate); + Project testProject = projectList.get(projectList.size() - 1); + assertThat(testProject.getName()).isEqualTo(UPDATED_NAME); + assertThat(testProject.getCode()).isEqualTo(UPDATED_CODE); + assertThat(testProject.getDesc()).isEqualTo(UPDATED_DESC); + + // Validate the Project in Elasticsearch + verify(mockProjectSearchRepository, times(1)).save(testProject); + } + + @Test + @Transactional + public void updateNonExistingProject() throws Exception { + int databaseSizeBeforeUpdate = projectRepository.findAll().size(); + + // Create the Project + ProjectDTO projectDTO = projectMapper.toDto(project); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restProjectMockMvc.perform(put("/api/projects") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(projectDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Project in the database + List projectList = projectRepository.findAll(); + assertThat(projectList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Project in Elasticsearch + verify(mockProjectSearchRepository, times(0)).save(project); + } + + @Test + @Transactional + public void deleteProject() throws Exception { + // Initialize the database + projectRepository.saveAndFlush(project); + + int databaseSizeBeforeDelete = projectRepository.findAll().size(); + + // Delete the project + restProjectMockMvc.perform(delete("/api/projects/{id}", project.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + List projectList = projectRepository.findAll(); + assertThat(projectList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Project in Elasticsearch + verify(mockProjectSearchRepository, times(1)).deleteById(project.getId()); + } + + @Test + @Transactional + public void searchProject() throws Exception { + // Initialize the database + projectRepository.saveAndFlush(project); + when(mockProjectSearchRepository.search(queryStringQuery("id:" + project.getId()), PageRequest.of(0, 20))) + .thenReturn(new PageImpl<>(Collections.singletonList(project), PageRequest.of(0, 1), 1)); + // Search the project + restProjectMockMvc.perform(get("/api/_search/projects?query=id:" + project.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(project.getId().intValue()))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) + .andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE))) + .andExpect(jsonPath("$.[*].desc").value(hasItem(DEFAULT_DESC.toString()))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Project.class); + Project project1 = new Project(); + project1.setId(1L); + Project project2 = new Project(); + project2.setId(project1.getId()); + assertThat(project1).isEqualTo(project2); + project2.setId(2L); + assertThat(project1).isNotEqualTo(project2); + project1.setId(null); + assertThat(project1).isNotEqualTo(project2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(ProjectDTO.class); + ProjectDTO projectDTO1 = new ProjectDTO(); + projectDTO1.setId(1L); + ProjectDTO projectDTO2 = new ProjectDTO(); + assertThat(projectDTO1).isNotEqualTo(projectDTO2); + projectDTO2.setId(projectDTO1.getId()); + assertThat(projectDTO1).isEqualTo(projectDTO2); + projectDTO2.setId(2L); + assertThat(projectDTO1).isNotEqualTo(projectDTO2); + projectDTO1.setId(null); + assertThat(projectDTO1).isNotEqualTo(projectDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(projectMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(projectMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/com/aiyun/code/record/web/rest/SubmitRecordResourceIT.java b/src/test/java/com/aiyun/code/record/web/rest/SubmitRecordResourceIT.java new file mode 100644 index 0000000..0be7255 --- /dev/null +++ b/src/test/java/com/aiyun/code/record/web/rest/SubmitRecordResourceIT.java @@ -0,0 +1,383 @@ +package com.aiyun.code.record.web.rest; + +import com.aiyun.code.record.CodeRecordApplicationApp; +import com.aiyun.code.record.domain.SubmitRecord; +import com.aiyun.code.record.repository.SubmitRecordRepository; +import com.aiyun.code.record.repository.search.SubmitRecordSearchRepository; +import com.aiyun.code.record.service.SubmitRecordService; +import com.aiyun.code.record.service.dto.SubmitRecordDTO; +import com.aiyun.code.record.service.mapper.SubmitRecordMapper; +import com.aiyun.code.record.web.rest.errors.ExceptionTranslator; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Validator; + +import javax.persistence.EntityManager; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.Collections; +import java.util.List; + +import static com.aiyun.code.record.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +/** + * Integration tests for the {@link SubmitRecordResource} REST controller. + */ +@SpringBootTest(classes = CodeRecordApplicationApp.class) +public class SubmitRecordResourceIT { + + private static final LocalDate DEFAULT_RECORD_DATE = LocalDate.ofEpochDay(0L); + private static final LocalDate UPDATED_RECORD_DATE = LocalDate.now(ZoneId.systemDefault()); + + private static final Integer DEFAULT_CNT = 1; + private static final Integer UPDATED_CNT = 2; + + @Autowired + private SubmitRecordRepository submitRecordRepository; + + @Autowired + private SubmitRecordMapper submitRecordMapper; + + @Autowired + private SubmitRecordService submitRecordService; + + /** + * This repository is mocked in the com.aiyun.code.record.repository.search test package. + * + * @see com.aiyun.code.record.repository.search.SubmitRecordSearchRepositoryMockConfiguration + */ + @Autowired + private SubmitRecordSearchRepository mockSubmitRecordSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restSubmitRecordMockMvc; + + private SubmitRecord submitRecord; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final SubmitRecordResource submitRecordResource = new SubmitRecordResource(submitRecordService); + this.restSubmitRecordMockMvc = MockMvcBuilders.standaloneSetup(submitRecordResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator).build(); + } + + /** + * Create an entity for this test. + * + * This is a static method, as tests for other entities might also need it, + * if they test an entity which requires the current entity. + */ + public static SubmitRecord createEntity(EntityManager em) { + SubmitRecord submitRecord = new SubmitRecord() + .recordDate(DEFAULT_RECORD_DATE) + .cnt(DEFAULT_CNT); + return submitRecord; + } + /** + * 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 SubmitRecord createUpdatedEntity(EntityManager em) { + SubmitRecord submitRecord = new SubmitRecord() + .recordDate(UPDATED_RECORD_DATE) + .cnt(UPDATED_CNT); + return submitRecord; + } + + @BeforeEach + public void initTest() { + submitRecord = createEntity(em); + } + + @Test + @Transactional + public void createSubmitRecord() throws Exception { + int databaseSizeBeforeCreate = submitRecordRepository.findAll().size(); + + // Create the SubmitRecord + SubmitRecordDTO submitRecordDTO = submitRecordMapper.toDto(submitRecord); + restSubmitRecordMockMvc.perform(post("/api/submit-records") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(submitRecordDTO))) + .andExpect(status().isCreated()); + + // Validate the SubmitRecord in the database + List submitRecordList = submitRecordRepository.findAll(); + assertThat(submitRecordList).hasSize(databaseSizeBeforeCreate + 1); + SubmitRecord testSubmitRecord = submitRecordList.get(submitRecordList.size() - 1); + assertThat(testSubmitRecord.getRecordDate()).isEqualTo(DEFAULT_RECORD_DATE); + assertThat(testSubmitRecord.getCnt()).isEqualTo(DEFAULT_CNT); + + // Validate the SubmitRecord in Elasticsearch + verify(mockSubmitRecordSearchRepository, times(1)).save(testSubmitRecord); + } + + @Test + @Transactional + public void createSubmitRecordWithExistingId() throws Exception { + int databaseSizeBeforeCreate = submitRecordRepository.findAll().size(); + + // Create the SubmitRecord with an existing ID + submitRecord.setId(1L); + SubmitRecordDTO submitRecordDTO = submitRecordMapper.toDto(submitRecord); + + // An entity with an existing ID cannot be created, so this API call must fail + restSubmitRecordMockMvc.perform(post("/api/submit-records") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(submitRecordDTO))) + .andExpect(status().isBadRequest()); + + // Validate the SubmitRecord in the database + List submitRecordList = submitRecordRepository.findAll(); + assertThat(submitRecordList).hasSize(databaseSizeBeforeCreate); + + // Validate the SubmitRecord in Elasticsearch + verify(mockSubmitRecordSearchRepository, times(0)).save(submitRecord); + } + + + @Test + @Transactional + public void checkRecordDateIsRequired() throws Exception { + int databaseSizeBeforeTest = submitRecordRepository.findAll().size(); + // set the field null + submitRecord.setRecordDate(null); + + // Create the SubmitRecord, which fails. + SubmitRecordDTO submitRecordDTO = submitRecordMapper.toDto(submitRecord); + + restSubmitRecordMockMvc.perform(post("/api/submit-records") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(submitRecordDTO))) + .andExpect(status().isBadRequest()); + + List submitRecordList = submitRecordRepository.findAll(); + assertThat(submitRecordList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void checkCntIsRequired() throws Exception { + int databaseSizeBeforeTest = submitRecordRepository.findAll().size(); + // set the field null + submitRecord.setCnt(null); + + // Create the SubmitRecord, which fails. + SubmitRecordDTO submitRecordDTO = submitRecordMapper.toDto(submitRecord); + + restSubmitRecordMockMvc.perform(post("/api/submit-records") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(submitRecordDTO))) + .andExpect(status().isBadRequest()); + + List submitRecordList = submitRecordRepository.findAll(); + assertThat(submitRecordList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void getAllSubmitRecords() throws Exception { + // Initialize the database + submitRecordRepository.saveAndFlush(submitRecord); + + // Get all the submitRecordList + restSubmitRecordMockMvc.perform(get("/api/submit-records?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(submitRecord.getId().intValue()))) + .andExpect(jsonPath("$.[*].recordDate").value(hasItem(DEFAULT_RECORD_DATE.toString()))) + .andExpect(jsonPath("$.[*].cnt").value(hasItem(DEFAULT_CNT))); + } + + @Test + @Transactional + public void getSubmitRecord() throws Exception { + // Initialize the database + submitRecordRepository.saveAndFlush(submitRecord); + + // Get the submitRecord + restSubmitRecordMockMvc.perform(get("/api/submit-records/{id}", submitRecord.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(submitRecord.getId().intValue())) + .andExpect(jsonPath("$.recordDate").value(DEFAULT_RECORD_DATE.toString())) + .andExpect(jsonPath("$.cnt").value(DEFAULT_CNT)); + } + + @Test + @Transactional + public void getNonExistingSubmitRecord() throws Exception { + // Get the submitRecord + restSubmitRecordMockMvc.perform(get("/api/submit-records/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateSubmitRecord() throws Exception { + // Initialize the database + submitRecordRepository.saveAndFlush(submitRecord); + + int databaseSizeBeforeUpdate = submitRecordRepository.findAll().size(); + + // Update the submitRecord + SubmitRecord updatedSubmitRecord = submitRecordRepository.findById(submitRecord.getId()).get(); + // Disconnect from session so that the updates on updatedSubmitRecord are not directly saved in db + em.detach(updatedSubmitRecord); + updatedSubmitRecord + .recordDate(UPDATED_RECORD_DATE) + .cnt(UPDATED_CNT); + SubmitRecordDTO submitRecordDTO = submitRecordMapper.toDto(updatedSubmitRecord); + + restSubmitRecordMockMvc.perform(put("/api/submit-records") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(submitRecordDTO))) + .andExpect(status().isOk()); + + // Validate the SubmitRecord in the database + List submitRecordList = submitRecordRepository.findAll(); + assertThat(submitRecordList).hasSize(databaseSizeBeforeUpdate); + SubmitRecord testSubmitRecord = submitRecordList.get(submitRecordList.size() - 1); + assertThat(testSubmitRecord.getRecordDate()).isEqualTo(UPDATED_RECORD_DATE); + assertThat(testSubmitRecord.getCnt()).isEqualTo(UPDATED_CNT); + + // Validate the SubmitRecord in Elasticsearch + verify(mockSubmitRecordSearchRepository, times(1)).save(testSubmitRecord); + } + + @Test + @Transactional + public void updateNonExistingSubmitRecord() throws Exception { + int databaseSizeBeforeUpdate = submitRecordRepository.findAll().size(); + + // Create the SubmitRecord + SubmitRecordDTO submitRecordDTO = submitRecordMapper.toDto(submitRecord); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restSubmitRecordMockMvc.perform(put("/api/submit-records") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(submitRecordDTO))) + .andExpect(status().isBadRequest()); + + // Validate the SubmitRecord in the database + List submitRecordList = submitRecordRepository.findAll(); + assertThat(submitRecordList).hasSize(databaseSizeBeforeUpdate); + + // Validate the SubmitRecord in Elasticsearch + verify(mockSubmitRecordSearchRepository, times(0)).save(submitRecord); + } + + @Test + @Transactional + public void deleteSubmitRecord() throws Exception { + // Initialize the database + submitRecordRepository.saveAndFlush(submitRecord); + + int databaseSizeBeforeDelete = submitRecordRepository.findAll().size(); + + // Delete the submitRecord + restSubmitRecordMockMvc.perform(delete("/api/submit-records/{id}", submitRecord.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database contains one less item + List submitRecordList = submitRecordRepository.findAll(); + assertThat(submitRecordList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the SubmitRecord in Elasticsearch + verify(mockSubmitRecordSearchRepository, times(1)).deleteById(submitRecord.getId()); + } + + @Test + @Transactional + public void searchSubmitRecord() throws Exception { + // Initialize the database + submitRecordRepository.saveAndFlush(submitRecord); + when(mockSubmitRecordSearchRepository.search(queryStringQuery("id:" + submitRecord.getId()), PageRequest.of(0, 20))) + .thenReturn(new PageImpl<>(Collections.singletonList(submitRecord), PageRequest.of(0, 1), 1)); + // Search the submitRecord + restSubmitRecordMockMvc.perform(get("/api/_search/submit-records?query=id:" + submitRecord.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(submitRecord.getId().intValue()))) + .andExpect(jsonPath("$.[*].recordDate").value(hasItem(DEFAULT_RECORD_DATE.toString()))) + .andExpect(jsonPath("$.[*].cnt").value(hasItem(DEFAULT_CNT))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(SubmitRecord.class); + SubmitRecord submitRecord1 = new SubmitRecord(); + submitRecord1.setId(1L); + SubmitRecord submitRecord2 = new SubmitRecord(); + submitRecord2.setId(submitRecord1.getId()); + assertThat(submitRecord1).isEqualTo(submitRecord2); + submitRecord2.setId(2L); + assertThat(submitRecord1).isNotEqualTo(submitRecord2); + submitRecord1.setId(null); + assertThat(submitRecord1).isNotEqualTo(submitRecord2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(SubmitRecordDTO.class); + SubmitRecordDTO submitRecordDTO1 = new SubmitRecordDTO(); + submitRecordDTO1.setId(1L); + SubmitRecordDTO submitRecordDTO2 = new SubmitRecordDTO(); + assertThat(submitRecordDTO1).isNotEqualTo(submitRecordDTO2); + submitRecordDTO2.setId(submitRecordDTO1.getId()); + assertThat(submitRecordDTO1).isEqualTo(submitRecordDTO2); + submitRecordDTO2.setId(2L); + assertThat(submitRecordDTO1).isNotEqualTo(submitRecordDTO2); + submitRecordDTO1.setId(null); + assertThat(submitRecordDTO1).isNotEqualTo(submitRecordDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(submitRecordMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(submitRecordMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/javascript/spec/app/entities/developer/developer-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/developer/developer-delete-dialog.component.spec.ts new file mode 100644 index 0000000..8e547c7 --- /dev/null +++ b/src/test/javascript/spec/app/entities/developer/developer-delete-dialog.component.spec.ts @@ -0,0 +1,51 @@ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { DeveloperDeleteDialogComponent } from 'app/entities/developer/developer-delete-dialog.component'; +import { DeveloperService } from 'app/entities/developer/developer.service'; + +describe('Component Tests', () => { + describe('Developer Management Delete Component', () => { + let comp: DeveloperDeleteDialogComponent; + let fixture: ComponentFixture; + let service: DeveloperService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [DeveloperDeleteDialogComponent] + }) + .overrideTemplate(DeveloperDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(DeveloperDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(DeveloperService); + mockEventManager = fixture.debugElement.injector.get(JhiEventManager); + mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); + }); + + describe('confirmDelete', () => { + it('Should call delete service on confirmDelete', inject( + [], + fakeAsync(() => { + // GIVEN + spyOn(service, 'delete').and.returnValue(of({})); + + // WHEN + comp.confirmDelete(123); + tick(); + + // THEN + expect(service.delete).toHaveBeenCalledWith(123); + expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); + expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); + }) + )); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/developer/developer-detail.component.spec.ts b/src/test/javascript/spec/app/entities/developer/developer-detail.component.spec.ts new file mode 100644 index 0000000..0cb71d6 --- /dev/null +++ b/src/test/javascript/spec/app/entities/developer/developer-detail.component.spec.ts @@ -0,0 +1,39 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { DeveloperDetailComponent } from 'app/entities/developer/developer-detail.component'; +import { Developer } from 'app/shared/model/developer.model'; + +describe('Component Tests', () => { + describe('Developer Management Detail Component', () => { + let comp: DeveloperDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ developer: new Developer(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [DeveloperDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(DeveloperDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(DeveloperDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.developer).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/developer/developer-update.component.spec.ts b/src/test/javascript/spec/app/entities/developer/developer-update.component.spec.ts new file mode 100644 index 0000000..efb258c --- /dev/null +++ b/src/test/javascript/spec/app/entities/developer/developer-update.component.spec.ts @@ -0,0 +1,61 @@ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { of } from 'rxjs'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { DeveloperUpdateComponent } from 'app/entities/developer/developer-update.component'; +import { DeveloperService } from 'app/entities/developer/developer.service'; +import { Developer } from 'app/shared/model/developer.model'; + +describe('Component Tests', () => { + describe('Developer Management Update Component', () => { + let comp: DeveloperUpdateComponent; + let fixture: ComponentFixture; + let service: DeveloperService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [DeveloperUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(DeveloperUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(DeveloperUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(DeveloperService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Developer(123); + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.updateForm(entity); + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new Developer(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.updateForm(entity); + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/developer/developer.component.spec.ts b/src/test/javascript/spec/app/entities/developer/developer.component.spec.ts new file mode 100644 index 0000000..38467b7 --- /dev/null +++ b/src/test/javascript/spec/app/entities/developer/developer.component.spec.ts @@ -0,0 +1,137 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Data } from '@angular/router'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { DeveloperComponent } from 'app/entities/developer/developer.component'; +import { DeveloperService } from 'app/entities/developer/developer.service'; +import { Developer } from 'app/shared/model/developer.model'; + +describe('Component Tests', () => { + describe('Developer Management Component', () => { + let comp: DeveloperComponent; + let fixture: ComponentFixture; + let service: DeveloperService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [DeveloperComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => + fn({ + pagingParams: { + predicate: 'id', + reverse: false, + page: 0 + } + }) + } + } + } + ] + }) + .overrideTemplate(DeveloperComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(DeveloperComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(DeveloperService); + }); + + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new Developer(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.developers[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should load a page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new Developer(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.developers[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should not load a page is the page is the same as the previous page', () => { + spyOn(service, 'query').and.callThrough(); + + // WHEN + comp.loadPage(0); + + // THEN + expect(service.query).toHaveBeenCalledTimes(0); + }); + + it('should re-initialize the page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new Developer(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + comp.clear(); + + // THEN + expect(comp.page).toEqual(0); + expect(service.query).toHaveBeenCalledTimes(2); + expect(comp.developers[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + it('should calculate the sort attribute for an id', () => { + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['id,desc']); + }); + + it('should calculate the sort attribute for a non-id attribute', () => { + // GIVEN + comp.predicate = 'name'; + + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['name,desc', 'id']); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/developer/developer.service.spec.ts b/src/test/javascript/spec/app/entities/developer/developer.service.spec.ts new file mode 100644 index 0000000..848c36f --- /dev/null +++ b/src/test/javascript/spec/app/entities/developer/developer.service.spec.ts @@ -0,0 +1,108 @@ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { take, map } from 'rxjs/operators'; +import { DeveloperService } from 'app/entities/developer/developer.service'; +import { IDeveloper, Developer } from 'app/shared/model/developer.model'; + +describe('Service Tests', () => { + describe('Developer Service', () => { + let injector: TestBed; + let service: DeveloperService; + let httpMock: HttpTestingController; + let elemDefault: IDeveloper; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(DeveloperService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Developer(0, 'AAAAAAA'); + }); + + describe('Service methods', () => { + it('should find an element', () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: elemDefault }); + }); + + it('should create a Developer', () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Developer(null)) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: expected }); + }); + + it('should update a Developer', () => { + const returnedFromService = Object.assign( + { + name: 'BBBBBB' + }, + elemDefault + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: expected }); + }); + + it('should return a list of Developer', () => { + const returnedFromService = Object.assign( + { + name: 'BBBBBB' + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .query(expected) + .pipe( + take(1), + map(resp => resp.body) + ) + .subscribe(body => (expectedResult = body)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([returnedFromService]); + httpMock.verify(); + expect(expectedResult).toContainEqual(expected); + }); + + it('should delete a Developer', () => { + service.delete(123).subscribe(resp => (expectedResult = resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + expect(expectedResult); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/project/project-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/project/project-delete-dialog.component.spec.ts new file mode 100644 index 0000000..970c759 --- /dev/null +++ b/src/test/javascript/spec/app/entities/project/project-delete-dialog.component.spec.ts @@ -0,0 +1,51 @@ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { ProjectDeleteDialogComponent } from 'app/entities/project/project-delete-dialog.component'; +import { ProjectService } from 'app/entities/project/project.service'; + +describe('Component Tests', () => { + describe('Project Management Delete Component', () => { + let comp: ProjectDeleteDialogComponent; + let fixture: ComponentFixture; + let service: ProjectService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [ProjectDeleteDialogComponent] + }) + .overrideTemplate(ProjectDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(ProjectDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(ProjectService); + mockEventManager = fixture.debugElement.injector.get(JhiEventManager); + mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); + }); + + describe('confirmDelete', () => { + it('Should call delete service on confirmDelete', inject( + [], + fakeAsync(() => { + // GIVEN + spyOn(service, 'delete').and.returnValue(of({})); + + // WHEN + comp.confirmDelete(123); + tick(); + + // THEN + expect(service.delete).toHaveBeenCalledWith(123); + expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); + expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); + }) + )); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/project/project-detail.component.spec.ts b/src/test/javascript/spec/app/entities/project/project-detail.component.spec.ts new file mode 100644 index 0000000..9d46f8f --- /dev/null +++ b/src/test/javascript/spec/app/entities/project/project-detail.component.spec.ts @@ -0,0 +1,39 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { ProjectDetailComponent } from 'app/entities/project/project-detail.component'; +import { Project } from 'app/shared/model/project.model'; + +describe('Component Tests', () => { + describe('Project Management Detail Component', () => { + let comp: ProjectDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ project: new Project(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [ProjectDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(ProjectDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(ProjectDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.project).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/project/project-update.component.spec.ts b/src/test/javascript/spec/app/entities/project/project-update.component.spec.ts new file mode 100644 index 0000000..b43550d --- /dev/null +++ b/src/test/javascript/spec/app/entities/project/project-update.component.spec.ts @@ -0,0 +1,61 @@ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { of } from 'rxjs'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { ProjectUpdateComponent } from 'app/entities/project/project-update.component'; +import { ProjectService } from 'app/entities/project/project.service'; +import { Project } from 'app/shared/model/project.model'; + +describe('Component Tests', () => { + describe('Project Management Update Component', () => { + let comp: ProjectUpdateComponent; + let fixture: ComponentFixture; + let service: ProjectService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [ProjectUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(ProjectUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ProjectUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(ProjectService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Project(123); + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.updateForm(entity); + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new Project(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.updateForm(entity); + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/project/project.component.spec.ts b/src/test/javascript/spec/app/entities/project/project.component.spec.ts new file mode 100644 index 0000000..802fc1d --- /dev/null +++ b/src/test/javascript/spec/app/entities/project/project.component.spec.ts @@ -0,0 +1,137 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Data } from '@angular/router'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { ProjectComponent } from 'app/entities/project/project.component'; +import { ProjectService } from 'app/entities/project/project.service'; +import { Project } from 'app/shared/model/project.model'; + +describe('Component Tests', () => { + describe('Project Management Component', () => { + let comp: ProjectComponent; + let fixture: ComponentFixture; + let service: ProjectService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [ProjectComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => + fn({ + pagingParams: { + predicate: 'id', + reverse: false, + page: 0 + } + }) + } + } + } + ] + }) + .overrideTemplate(ProjectComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ProjectComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(ProjectService); + }); + + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new Project(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.projects[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should load a page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new Project(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.projects[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should not load a page is the page is the same as the previous page', () => { + spyOn(service, 'query').and.callThrough(); + + // WHEN + comp.loadPage(0); + + // THEN + expect(service.query).toHaveBeenCalledTimes(0); + }); + + it('should re-initialize the page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new Project(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + comp.clear(); + + // THEN + expect(comp.page).toEqual(0); + expect(service.query).toHaveBeenCalledTimes(2); + expect(comp.projects[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + it('should calculate the sort attribute for an id', () => { + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['id,desc']); + }); + + it('should calculate the sort attribute for a non-id attribute', () => { + // GIVEN + comp.predicate = 'name'; + + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['name,desc', 'id']); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/project/project.service.spec.ts b/src/test/javascript/spec/app/entities/project/project.service.spec.ts new file mode 100644 index 0000000..72e786c --- /dev/null +++ b/src/test/javascript/spec/app/entities/project/project.service.spec.ts @@ -0,0 +1,112 @@ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { take, map } from 'rxjs/operators'; +import { ProjectService } from 'app/entities/project/project.service'; +import { IProject, Project } from 'app/shared/model/project.model'; + +describe('Service Tests', () => { + describe('Project Service', () => { + let injector: TestBed; + let service: ProjectService; + let httpMock: HttpTestingController; + let elemDefault: IProject; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(ProjectService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Project(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA'); + }); + + describe('Service methods', () => { + it('should find an element', () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: elemDefault }); + }); + + it('should create a Project', () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Project(null)) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: expected }); + }); + + it('should update a Project', () => { + const returnedFromService = Object.assign( + { + name: 'BBBBBB', + code: 'BBBBBB', + desc: 'BBBBBB' + }, + elemDefault + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: expected }); + }); + + it('should return a list of Project', () => { + const returnedFromService = Object.assign( + { + name: 'BBBBBB', + code: 'BBBBBB', + desc: 'BBBBBB' + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .query(expected) + .pipe( + take(1), + map(resp => resp.body) + ) + .subscribe(body => (expectedResult = body)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([returnedFromService]); + httpMock.verify(); + expect(expectedResult).toContainEqual(expected); + }); + + it('should delete a Project', () => { + service.delete(123).subscribe(resp => (expectedResult = resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + expect(expectedResult); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/submit-record/submit-record-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/submit-record/submit-record-delete-dialog.component.spec.ts new file mode 100644 index 0000000..e57e613 --- /dev/null +++ b/src/test/javascript/spec/app/entities/submit-record/submit-record-delete-dialog.component.spec.ts @@ -0,0 +1,51 @@ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { SubmitRecordDeleteDialogComponent } from 'app/entities/submit-record/submit-record-delete-dialog.component'; +import { SubmitRecordService } from 'app/entities/submit-record/submit-record.service'; + +describe('Component Tests', () => { + describe('SubmitRecord Management Delete Component', () => { + let comp: SubmitRecordDeleteDialogComponent; + let fixture: ComponentFixture; + let service: SubmitRecordService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [SubmitRecordDeleteDialogComponent] + }) + .overrideTemplate(SubmitRecordDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(SubmitRecordDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(SubmitRecordService); + mockEventManager = fixture.debugElement.injector.get(JhiEventManager); + mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); + }); + + describe('confirmDelete', () => { + it('Should call delete service on confirmDelete', inject( + [], + fakeAsync(() => { + // GIVEN + spyOn(service, 'delete').and.returnValue(of({})); + + // WHEN + comp.confirmDelete(123); + tick(); + + // THEN + expect(service.delete).toHaveBeenCalledWith(123); + expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); + expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); + }) + )); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/submit-record/submit-record-detail.component.spec.ts b/src/test/javascript/spec/app/entities/submit-record/submit-record-detail.component.spec.ts new file mode 100644 index 0000000..92ab3ee --- /dev/null +++ b/src/test/javascript/spec/app/entities/submit-record/submit-record-detail.component.spec.ts @@ -0,0 +1,39 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { SubmitRecordDetailComponent } from 'app/entities/submit-record/submit-record-detail.component'; +import { SubmitRecord } from 'app/shared/model/submit-record.model'; + +describe('Component Tests', () => { + describe('SubmitRecord Management Detail Component', () => { + let comp: SubmitRecordDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ submitRecord: new SubmitRecord(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [SubmitRecordDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(SubmitRecordDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(SubmitRecordDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.submitRecord).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/submit-record/submit-record-update.component.spec.ts b/src/test/javascript/spec/app/entities/submit-record/submit-record-update.component.spec.ts new file mode 100644 index 0000000..c3d9542 --- /dev/null +++ b/src/test/javascript/spec/app/entities/submit-record/submit-record-update.component.spec.ts @@ -0,0 +1,61 @@ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { of } from 'rxjs'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { SubmitRecordUpdateComponent } from 'app/entities/submit-record/submit-record-update.component'; +import { SubmitRecordService } from 'app/entities/submit-record/submit-record.service'; +import { SubmitRecord } from 'app/shared/model/submit-record.model'; + +describe('Component Tests', () => { + describe('SubmitRecord Management Update Component', () => { + let comp: SubmitRecordUpdateComponent; + let fixture: ComponentFixture; + let service: SubmitRecordService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [SubmitRecordUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(SubmitRecordUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(SubmitRecordUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(SubmitRecordService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new SubmitRecord(123); + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.updateForm(entity); + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new SubmitRecord(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.updateForm(entity); + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/submit-record/submit-record.component.spec.ts b/src/test/javascript/spec/app/entities/submit-record/submit-record.component.spec.ts new file mode 100644 index 0000000..cccf78d --- /dev/null +++ b/src/test/javascript/spec/app/entities/submit-record/submit-record.component.spec.ts @@ -0,0 +1,137 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Data } from '@angular/router'; + +import { CodeRecordApplicationTestModule } from '../../../test.module'; +import { SubmitRecordComponent } from 'app/entities/submit-record/submit-record.component'; +import { SubmitRecordService } from 'app/entities/submit-record/submit-record.service'; +import { SubmitRecord } from 'app/shared/model/submit-record.model'; + +describe('Component Tests', () => { + describe('SubmitRecord Management Component', () => { + let comp: SubmitRecordComponent; + let fixture: ComponentFixture; + let service: SubmitRecordService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [CodeRecordApplicationTestModule], + declarations: [SubmitRecordComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => + fn({ + pagingParams: { + predicate: 'id', + reverse: false, + page: 0 + } + }) + } + } + } + ] + }) + .overrideTemplate(SubmitRecordComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(SubmitRecordComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(SubmitRecordService); + }); + + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new SubmitRecord(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.submitRecords[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should load a page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new SubmitRecord(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.submitRecords[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should not load a page is the page is the same as the previous page', () => { + spyOn(service, 'query').and.callThrough(); + + // WHEN + comp.loadPage(0); + + // THEN + expect(service.query).toHaveBeenCalledTimes(0); + }); + + it('should re-initialize the page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new SubmitRecord(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + comp.clear(); + + // THEN + expect(comp.page).toEqual(0); + expect(service.query).toHaveBeenCalledTimes(2); + expect(comp.submitRecords[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + it('should calculate the sort attribute for an id', () => { + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['id,desc']); + }); + + it('should calculate the sort attribute for a non-id attribute', () => { + // GIVEN + comp.predicate = 'name'; + + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['name,desc', 'id']); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/submit-record/submit-record.service.spec.ts b/src/test/javascript/spec/app/entities/submit-record/submit-record.service.spec.ts new file mode 100644 index 0000000..3ea7af8 --- /dev/null +++ b/src/test/javascript/spec/app/entities/submit-record/submit-record.service.spec.ts @@ -0,0 +1,135 @@ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { take, map } from 'rxjs/operators'; +import * as moment from 'moment'; +import { DATE_FORMAT } from 'app/shared/constants/input.constants'; +import { SubmitRecordService } from 'app/entities/submit-record/submit-record.service'; +import { ISubmitRecord, SubmitRecord } from 'app/shared/model/submit-record.model'; + +describe('Service Tests', () => { + describe('SubmitRecord Service', () => { + let injector: TestBed; + let service: SubmitRecordService; + let httpMock: HttpTestingController; + let elemDefault: ISubmitRecord; + let expectedResult; + let currentDate: moment.Moment; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(SubmitRecordService); + httpMock = injector.get(HttpTestingController); + currentDate = moment(); + + elemDefault = new SubmitRecord(0, currentDate, 0); + }); + + describe('Service methods', () => { + it('should find an element', () => { + const returnedFromService = Object.assign( + { + recordDate: currentDate.format(DATE_FORMAT) + }, + elemDefault + ); + service + .find(123) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: elemDefault }); + }); + + it('should create a SubmitRecord', () => { + const returnedFromService = Object.assign( + { + id: 0, + recordDate: currentDate.format(DATE_FORMAT) + }, + elemDefault + ); + const expected = Object.assign( + { + recordDate: currentDate + }, + returnedFromService + ); + service + .create(new SubmitRecord(null)) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: expected }); + }); + + it('should update a SubmitRecord', () => { + const returnedFromService = Object.assign( + { + recordDate: currentDate.format(DATE_FORMAT), + cnt: 1 + }, + elemDefault + ); + + const expected = Object.assign( + { + recordDate: currentDate + }, + returnedFromService + ); + service + .update(expected) + .pipe(take(1)) + .subscribe(resp => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(returnedFromService); + expect(expectedResult).toMatchObject({ body: expected }); + }); + + it('should return a list of SubmitRecord', () => { + const returnedFromService = Object.assign( + { + recordDate: currentDate.format(DATE_FORMAT), + cnt: 1 + }, + elemDefault + ); + const expected = Object.assign( + { + recordDate: currentDate + }, + returnedFromService + ); + service + .query(expected) + .pipe( + take(1), + map(resp => resp.body) + ) + .subscribe(body => (expectedResult = body)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([returnedFromService]); + httpMock.verify(); + expect(expectedResult).toContainEqual(expected); + }); + + it('should delete a SubmitRecord', () => { + service.delete(123).subscribe(resp => (expectedResult = resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + expect(expectedResult); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); + }); +});