From 58aaa650e88a178df66a386717a31e26f871c011 Mon Sep 17 00:00:00 2001 From: JHipster Bot Date: Wed, 19 Jun 2019 19:22:28 +0000 Subject: [PATCH 1/2] Add JDL Model `zdar` See https://start.jhipster.tech/jdl-studio/#!/view/e42e2704-0140-4449-8131-0cce595b3409 --- zdar.jh | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 zdar.jh diff --git a/zdar.jh b/zdar.jh new file mode 100644 index 0000000..a0f1c8d --- /dev/null +++ b/zdar.jh @@ -0,0 +1,114 @@ +entity Region { + regionName String +} + +entity Country { + countryName String +} + +// an ignored comment +/** not an ignored comment */ +entity Location { + streetAddress String, + postalCode String, + city String, + stateProvince String +} + +entity Department { + departmentName String required +} + +/** + * Task entity. + * @author The JHipster team. + */ +entity Task { + title String, + description String +} + +/** + * The Employee entity. + */ +entity Employee { + /** + * The firstname attribute. + */ + firstName String, + lastName String, + email String, + phoneNumber String, + hireDate Instant, + salary Long, + commissionPct Long +} + +entity Job { + jobTitle String, + minSalary Long, + maxSalary Long +} + +entity JobHistory { + startDate Instant, + endDate Instant, + language Language +} + +enum Language { + FRENCH, ENGLISH, SPANISH +} + +relationship OneToOne { + Country{region} to Region +} + +relationship OneToOne { + Location{country} to Country +} + +relationship OneToOne { + Department{location} to Location +} + +relationship ManyToMany { + Job{task(title)} to Task{job} +} + +// defining multiple OneToMany relationships with comments +relationship OneToMany { + Employee{job} to Job, + /** + * A relationship + */ + Department{employee} to + /** + * Another side of the same relationship + */ + Employee +} + +relationship ManyToOne { + Employee{manager} to Employee +} + +// defining multiple oneToOne relationships +relationship OneToOne { + JobHistory{job} to Job, + JobHistory{department} to Department, + JobHistory{employee} to Employee +} + +// Set pagination options +paginate JobHistory, Employee with infinite-scroll +paginate Job with pagination + +// Use Data Transfert Objects (DTO) +dto * with mapstruct + +// Set service options to all except few +service all with serviceImpl except Employee, Job + +// Set an angular suffix +// angularSuffix * with mySuffix From fb7d3fc20577a32dd36e99e36451512e229697a0 Mon Sep 17 00:00:00 2001 From: JHipster Bot Date: Wed, 19 Jun 2019 19:22:37 +0000 Subject: [PATCH 2/2] Generate entities from JDL Model `zdar` See https://start.jhipster.tech/jdl-studio/#!/view/e42e2704-0140-4449-8131-0cce595b3409 --- .jhipster/Country.json | 28 ++ .jhipster/Department.json | 38 ++ .jhipster/Employee.json | 65 +++ .jhipster/Job.json | 42 ++ .jhipster/JobHistory.json | 53 +++ .jhipster/Location.json | 41 ++ .jhipster/Region.json | 19 + .jhipster/Task.json | 33 ++ src/main/java/org/zdar/domain/Country.java | 90 ++++ src/main/java/org/zdar/domain/Department.java | 125 ++++++ src/main/java/org/zdar/domain/Employee.java | 244 +++++++++++ src/main/java/org/zdar/domain/Job.java | 158 +++++++ src/main/java/org/zdar/domain/JobHistory.java | 162 +++++++ src/main/java/org/zdar/domain/Location.java | 141 ++++++ src/main/java/org/zdar/domain/Region.java | 73 ++++ src/main/java/org/zdar/domain/Task.java | 123 ++++++ .../org/zdar/domain/enumeration/Language.java | 8 + .../zdar/repository/CountryRepository.java | 15 + .../zdar/repository/DepartmentRepository.java | 15 + .../zdar/repository/EmployeeRepository.java | 15 + .../zdar/repository/JobHistoryRepository.java | 15 + .../org/zdar/repository/JobRepository.java | 29 ++ .../zdar/repository/LocationRepository.java | 15 + .../org/zdar/repository/RegionRepository.java | 15 + .../org/zdar/repository/TaskRepository.java | 15 + .../search/CountrySearchRepository.java | 10 + .../search/DepartmentSearchRepository.java | 10 + .../search/EmployeeSearchRepository.java | 10 + .../search/JobHistorySearchRepository.java | 10 + .../search/JobSearchRepository.java | 10 + .../search/LocationSearchRepository.java | 10 + .../search/RegionSearchRepository.java | 10 + .../search/TaskSearchRepository.java | 10 + .../java/org/zdar/service/CountryService.java | 52 +++ .../org/zdar/service/DepartmentService.java | 52 +++ .../org/zdar/service/EmployeeService.java | 107 +++++ .../org/zdar/service/JobHistoryService.java | 56 +++ .../java/org/zdar/service/JobService.java | 116 +++++ .../org/zdar/service/LocationService.java | 52 +++ .../java/org/zdar/service/RegionService.java | 52 +++ .../java/org/zdar/service/TaskService.java | 52 +++ .../java/org/zdar/service/dto/CountryDTO.java | 70 +++ .../org/zdar/service/dto/DepartmentDTO.java | 77 ++++ .../org/zdar/service/dto/EmployeeDTO.java | 155 +++++++ .../java/org/zdar/service/dto/JobDTO.java | 104 +++++ .../org/zdar/service/dto/JobHistoryDTO.java | 116 +++++ .../org/zdar/service/dto/LocationDTO.java | 105 +++++ .../java/org/zdar/service/dto/RegionDTO.java | 59 +++ .../java/org/zdar/service/dto/TaskDTO.java | 72 ++++ .../zdar/service/impl/CountryServiceImpl.java | 116 +++++ .../service/impl/DepartmentServiceImpl.java | 116 +++++ .../service/impl/JobHistoryServiceImpl.java | 113 +++++ .../service/impl/LocationServiceImpl.java | 116 +++++ .../zdar/service/impl/RegionServiceImpl.java | 116 +++++ .../zdar/service/impl/TaskServiceImpl.java | 116 +++++ .../zdar/service/mapper/CountryMapper.java | 28 ++ .../zdar/service/mapper/DepartmentMapper.java | 30 ++ .../zdar/service/mapper/EmployeeMapper.java | 32 ++ .../org/zdar/service/mapper/EntityMapper.java | 21 + .../zdar/service/mapper/JobHistoryMapper.java | 32 ++ .../org/zdar/service/mapper/JobMapper.java | 29 ++ .../zdar/service/mapper/LocationMapper.java | 28 ++ .../org/zdar/service/mapper/RegionMapper.java | 24 ++ .../org/zdar/service/mapper/TaskMapper.java | 27 ++ .../org/zdar/web/rest/CountryResource.java | 134 ++++++ .../org/zdar/web/rest/DepartmentResource.java | 135 ++++++ .../org/zdar/web/rest/EmployeeResource.java | 147 +++++++ .../org/zdar/web/rest/JobHistoryResource.java | 147 +++++++ .../java/org/zdar/web/rest/JobResource.java | 153 +++++++ .../org/zdar/web/rest/LocationResource.java | 134 ++++++ .../org/zdar/web/rest/RegionResource.java | 134 ++++++ .../java/org/zdar/web/rest/TaskResource.java | 134 ++++++ .../20190619192229_added_entity_Region.xml | 49 +++ .../20190619192230_added_entity_Country.xml | 51 +++ ...92230_added_entity_constraints_Country.xml | 18 + .../20190619192231_added_entity_Location.xml | 66 +++ ...2231_added_entity_constraints_Location.xml | 18 + ...20190619192232_added_entity_Department.xml | 51 +++ ...32_added_entity_constraints_Department.xml | 18 + .../20190619192233_added_entity_Task.xml | 54 +++ .../20190619192234_added_entity_Employee.xml | 88 ++++ ...2234_added_entity_constraints_Employee.xml | 24 ++ .../20190619192235_added_entity_Job.xml | 74 ++++ ...619192235_added_entity_constraints_Job.xml | 30 ++ ...20190619192236_added_entity_JobHistory.xml | 67 +++ ...36_added_entity_constraints_JobHistory.xml | 30 ++ .../config/liquibase/data/country.csv | 11 + .../config/liquibase/data/department.csv | 11 + .../config/liquibase/data/employee.csv | 11 + .../resources/config/liquibase/data/job.csv | 11 + .../config/liquibase/data/job_history.csv | 11 + .../config/liquibase/data/location.csv | 11 + .../config/liquibase/data/region.csv | 11 + .../resources/config/liquibase/data/task.csv | 11 + .../resources/config/liquibase/master.xml | 14 + .../country-delete-dialog.component.html | 19 + .../country-delete-dialog.component.ts | 65 +++ .../country/country-detail.component.html | 33 ++ .../country/country-detail.component.ts | 24 ++ .../country/country-update.component.html | 36 ++ .../country/country-update.component.ts | 119 ++++++ .../entities/country/country.component.html | 78 ++++ .../app/entities/country/country.component.ts | 97 +++++ .../app/entities/country/country.module.ts | 29 ++ .../app/entities/country/country.route.ts | 93 ++++ .../app/entities/country/country.service.ts | 44 ++ src/main/webapp/app/entities/country/index.ts | 6 + .../department-delete-dialog.component.html | 19 + .../department-delete-dialog.component.ts | 69 +++ .../department-detail.component.html | 33 ++ .../department/department-detail.component.ts | 24 ++ .../department-update.component.html | 42 ++ .../department/department-update.component.ts | 119 ++++++ .../department/department.component.html | 78 ++++ .../department/department.component.ts | 97 +++++ .../entities/department/department.module.ts | 29 ++ .../entities/department/department.route.ts | 93 ++++ .../entities/department/department.service.ts | 44 ++ .../webapp/app/entities/department/index.ts | 6 + .../employee-delete-dialog.component.html | 19 + .../employee-delete-dialog.component.ts | 65 +++ .../employee/employee-detail.component.html | 63 +++ .../employee/employee-detail.component.ts | 24 ++ .../employee/employee-update.component.html | 74 ++++ .../employee/employee-update.component.ts | 137 ++++++ .../entities/employee/employee.component.html | 96 +++++ .../entities/employee/employee.component.ts | 154 +++++++ .../app/entities/employee/employee.module.ts | 29 ++ .../app/entities/employee/employee.route.ts | 93 ++++ .../app/entities/employee/employee.service.ts | 82 ++++ .../webapp/app/entities/employee/index.ts | 6 + src/main/webapp/app/entities/entity.module.ts | 32 ++ .../webapp/app/entities/job-history/index.ts | 6 + .../job-history-delete-dialog.component.html | 19 + .../job-history-delete-dialog.component.ts | 69 +++ .../job-history-detail.component.html | 53 +++ .../job-history-detail.component.ts | 24 ++ .../job-history-update.component.html | 65 +++ .../job-history-update.component.ts | 199 +++++++++ .../job-history/job-history.component.html | 94 ++++ .../job-history/job-history.component.ts | 154 +++++++ .../job-history/job-history.module.ts | 29 ++ .../entities/job-history/job-history.route.ts | 93 ++++ .../job-history/job-history.service.ts | 85 ++++ src/main/webapp/app/entities/job/index.ts | 6 + .../job/job-delete-dialog.component.html | 19 + .../job/job-delete-dialog.component.ts | 65 +++ .../entities/job/job-detail.component.html | 47 ++ .../app/entities/job/job-detail.component.ts | 24 ++ .../entities/job/job-update.component.html | 52 +++ .../app/entities/job/job-update.component.ts | 137 ++++++ .../app/entities/job/job.component.html | 90 ++++ .../webapp/app/entities/job/job.component.ts | 167 ++++++++ .../webapp/app/entities/job/job.module.ts | 23 + src/main/webapp/app/entities/job/job.route.ts | 98 +++++ .../webapp/app/entities/job/job.service.ts | 44 ++ .../webapp/app/entities/location/index.ts | 6 + .../location-delete-dialog.component.html | 19 + .../location-delete-dialog.component.ts | 65 +++ .../location/location-detail.component.html | 45 ++ .../location/location-detail.component.ts | 24 ++ .../location/location-update.component.html | 51 +++ .../location/location-update.component.ts | 128 ++++++ .../entities/location/location.component.html | 84 ++++ .../entities/location/location.component.ts | 97 +++++ .../app/entities/location/location.module.ts | 29 ++ .../app/entities/location/location.route.ts | 93 ++++ .../app/entities/location/location.service.ts | 44 ++ src/main/webapp/app/entities/region/index.ts | 6 + .../region-delete-dialog.component.html | 19 + .../region/region-delete-dialog.component.ts | 65 +++ .../region/region-detail.component.html | 27 ++ .../region/region-detail.component.ts | 24 ++ .../region/region-update.component.html | 29 ++ .../region/region-update.component.ts | 72 ++++ .../app/entities/region/region.component.html | 72 ++++ .../app/entities/region/region.component.ts | 97 +++++ .../app/entities/region/region.module.ts | 23 + .../app/entities/region/region.route.ts | 93 ++++ .../app/entities/region/region.service.ts | 44 ++ src/main/webapp/app/entities/task/index.ts | 6 + .../task/task-delete-dialog.component.html | 19 + .../task/task-delete-dialog.component.ts | 65 +++ .../entities/task/task-detail.component.html | 31 ++ .../entities/task/task-detail.component.ts | 24 ++ .../entities/task/task-update.component.html | 34 ++ .../entities/task/task-update.component.ts | 112 +++++ .../app/entities/task/task.component.html | 74 ++++ .../app/entities/task/task.component.ts | 97 +++++ .../webapp/app/entities/task/task.module.ts | 23 + .../webapp/app/entities/task/task.route.ts | 93 ++++ .../webapp/app/entities/task/task.service.ts | 44 ++ .../app/layouts/navbar/navbar.component.html | 48 +++ .../webapp/app/shared/model/country.model.ts | 9 + .../app/shared/model/department.model.ts | 12 + .../webapp/app/shared/model/employee.model.ts | 32 ++ .../app/shared/model/job-history.model.ts | 29 ++ src/main/webapp/app/shared/model/job.model.ts | 21 + .../webapp/app/shared/model/location.model.ts | 19 + .../webapp/app/shared/model/region.model.ts | 8 + .../webapp/app/shared/model/task.model.ts | 12 + ...ntrySearchRepositoryMockConfiguration.java | 16 + ...mentSearchRepositoryMockConfiguration.java | 16 + ...oyeeSearchRepositoryMockConfiguration.java | 16 + ...torySearchRepositoryMockConfiguration.java | 16 + .../JobSearchRepositoryMockConfiguration.java | 16 + ...tionSearchRepositoryMockConfiguration.java | 16 + ...gionSearchRepositoryMockConfiguration.java | 16 + ...TaskSearchRepositoryMockConfiguration.java | 16 + .../org/zdar/web/rest/CountryResourceIT.java | 330 +++++++++++++++ .../zdar/web/rest/DepartmentResourceIT.java | 349 +++++++++++++++ .../org/zdar/web/rest/EmployeeResourceIT.java | 400 ++++++++++++++++++ .../zdar/web/rest/JobHistoryResourceIT.java | 357 ++++++++++++++++ .../java/org/zdar/web/rest/JobResourceIT.java | 395 +++++++++++++++++ .../org/zdar/web/rest/LocationResourceIT.java | 363 ++++++++++++++++ .../org/zdar/web/rest/RegionResourceIT.java | 330 +++++++++++++++ .../org/zdar/web/rest/TaskResourceIT.java | 341 +++++++++++++++ .../entities/country/country.page-object.ts | 87 ++++ .../e2e/entities/country/country.spec.ts | 64 +++ .../department/department.page-object.ts | 87 ++++ .../entities/department/department.spec.ts | 67 +++ .../entities/employee/employee.page-object.ts | 161 +++++++ .../e2e/entities/employee/employee.spec.ts | 83 ++++ .../job-history/job-history.page-object.ts | 152 +++++++ .../entities/job-history/job-history.spec.ts | 78 ++++ .../e2e/entities/job/job.page-object.ts | 125 ++++++ .../javascript/e2e/entities/job/job.spec.ts | 72 ++++ .../entities/location/location.page-object.ts | 114 +++++ .../e2e/entities/location/location.spec.ts | 79 ++++ .../e2e/entities/region/region.page-object.ts | 67 +++ .../e2e/entities/region/region.spec.ts | 64 +++ .../e2e/entities/task/task.page-object.ts | 76 ++++ .../javascript/e2e/entities/task/task.spec.ts | 65 +++ .../country-delete-dialog.component.spec.ts | 52 +++ .../country/country-detail.component.spec.ts | 40 ++ .../country/country-update.component.spec.ts | 62 +++ .../country/country.component.spec.ts | 51 +++ .../entities/country/country.service.spec.ts | 111 +++++ ...department-delete-dialog.component.spec.ts | 52 +++ .../department-detail.component.spec.ts | 40 ++ .../department-update.component.spec.ts | 62 +++ .../department/department.component.spec.ts | 51 +++ .../department/department.service.spec.ts | 111 +++++ .../employee-delete-dialog.component.spec.ts | 52 +++ .../employee-detail.component.spec.ts | 40 ++ .../employee-update.component.spec.ts | 62 +++ .../employee/employee.component.spec.ts | 128 ++++++ .../employee/employee.service.spec.ts | 148 +++++++ ...ob-history-delete-dialog.component.spec.ts | 52 +++ .../job-history-detail.component.spec.ts | 40 ++ .../job-history-update.component.spec.ts | 62 +++ .../job-history/job-history.component.spec.ts | 128 ++++++ .../job-history/job-history.service.spec.ts | 145 +++++++ .../job/job-delete-dialog.component.spec.ts | 52 +++ .../entities/job/job-detail.component.spec.ts | 40 ++ .../entities/job/job-update.component.spec.ts | 62 +++ .../app/entities/job/job.component.spec.ts | 138 ++++++ .../spec/app/entities/job/job.service.spec.ts | 115 +++++ .../location-delete-dialog.component.spec.ts | 52 +++ .../location-detail.component.spec.ts | 40 ++ .../location-update.component.spec.ts | 62 +++ .../location/location.component.spec.ts | 51 +++ .../location/location.service.spec.ts | 117 +++++ .../region-delete-dialog.component.spec.ts | 52 +++ .../region/region-detail.component.spec.ts | 40 ++ .../region/region-update.component.spec.ts | 62 +++ .../entities/region/region.component.spec.ts | 51 +++ .../entities/region/region.service.spec.ts | 111 +++++ .../task/task-delete-dialog.component.spec.ts | 52 +++ .../task/task-detail.component.spec.ts | 40 ++ .../task/task-update.component.spec.ts | 62 +++ .../app/entities/task/task.component.spec.ts | 51 +++ .../app/entities/task/task.service.spec.ts | 113 +++++ 273 files changed, 18942 insertions(+) create mode 100644 .jhipster/Country.json create mode 100644 .jhipster/Department.json create mode 100644 .jhipster/Employee.json create mode 100644 .jhipster/Job.json create mode 100644 .jhipster/JobHistory.json create mode 100644 .jhipster/Location.json create mode 100644 .jhipster/Region.json create mode 100644 .jhipster/Task.json create mode 100644 src/main/java/org/zdar/domain/Country.java create mode 100644 src/main/java/org/zdar/domain/Department.java create mode 100644 src/main/java/org/zdar/domain/Employee.java create mode 100644 src/main/java/org/zdar/domain/Job.java create mode 100644 src/main/java/org/zdar/domain/JobHistory.java create mode 100644 src/main/java/org/zdar/domain/Location.java create mode 100644 src/main/java/org/zdar/domain/Region.java create mode 100644 src/main/java/org/zdar/domain/Task.java create mode 100644 src/main/java/org/zdar/domain/enumeration/Language.java create mode 100644 src/main/java/org/zdar/repository/CountryRepository.java create mode 100644 src/main/java/org/zdar/repository/DepartmentRepository.java create mode 100644 src/main/java/org/zdar/repository/EmployeeRepository.java create mode 100644 src/main/java/org/zdar/repository/JobHistoryRepository.java create mode 100644 src/main/java/org/zdar/repository/JobRepository.java create mode 100644 src/main/java/org/zdar/repository/LocationRepository.java create mode 100644 src/main/java/org/zdar/repository/RegionRepository.java create mode 100644 src/main/java/org/zdar/repository/TaskRepository.java create mode 100644 src/main/java/org/zdar/repository/search/CountrySearchRepository.java create mode 100644 src/main/java/org/zdar/repository/search/DepartmentSearchRepository.java create mode 100644 src/main/java/org/zdar/repository/search/EmployeeSearchRepository.java create mode 100644 src/main/java/org/zdar/repository/search/JobHistorySearchRepository.java create mode 100644 src/main/java/org/zdar/repository/search/JobSearchRepository.java create mode 100644 src/main/java/org/zdar/repository/search/LocationSearchRepository.java create mode 100644 src/main/java/org/zdar/repository/search/RegionSearchRepository.java create mode 100644 src/main/java/org/zdar/repository/search/TaskSearchRepository.java create mode 100644 src/main/java/org/zdar/service/CountryService.java create mode 100644 src/main/java/org/zdar/service/DepartmentService.java create mode 100644 src/main/java/org/zdar/service/EmployeeService.java create mode 100644 src/main/java/org/zdar/service/JobHistoryService.java create mode 100644 src/main/java/org/zdar/service/JobService.java create mode 100644 src/main/java/org/zdar/service/LocationService.java create mode 100644 src/main/java/org/zdar/service/RegionService.java create mode 100644 src/main/java/org/zdar/service/TaskService.java create mode 100644 src/main/java/org/zdar/service/dto/CountryDTO.java create mode 100644 src/main/java/org/zdar/service/dto/DepartmentDTO.java create mode 100644 src/main/java/org/zdar/service/dto/EmployeeDTO.java create mode 100644 src/main/java/org/zdar/service/dto/JobDTO.java create mode 100644 src/main/java/org/zdar/service/dto/JobHistoryDTO.java create mode 100644 src/main/java/org/zdar/service/dto/LocationDTO.java create mode 100644 src/main/java/org/zdar/service/dto/RegionDTO.java create mode 100644 src/main/java/org/zdar/service/dto/TaskDTO.java create mode 100644 src/main/java/org/zdar/service/impl/CountryServiceImpl.java create mode 100644 src/main/java/org/zdar/service/impl/DepartmentServiceImpl.java create mode 100644 src/main/java/org/zdar/service/impl/JobHistoryServiceImpl.java create mode 100644 src/main/java/org/zdar/service/impl/LocationServiceImpl.java create mode 100644 src/main/java/org/zdar/service/impl/RegionServiceImpl.java create mode 100644 src/main/java/org/zdar/service/impl/TaskServiceImpl.java create mode 100644 src/main/java/org/zdar/service/mapper/CountryMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/DepartmentMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/EmployeeMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/EntityMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/JobHistoryMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/JobMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/LocationMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/RegionMapper.java create mode 100644 src/main/java/org/zdar/service/mapper/TaskMapper.java create mode 100644 src/main/java/org/zdar/web/rest/CountryResource.java create mode 100644 src/main/java/org/zdar/web/rest/DepartmentResource.java create mode 100644 src/main/java/org/zdar/web/rest/EmployeeResource.java create mode 100644 src/main/java/org/zdar/web/rest/JobHistoryResource.java create mode 100644 src/main/java/org/zdar/web/rest/JobResource.java create mode 100644 src/main/java/org/zdar/web/rest/LocationResource.java create mode 100644 src/main/java/org/zdar/web/rest/RegionResource.java create mode 100644 src/main/java/org/zdar/web/rest/TaskResource.java create mode 100644 src/main/resources/config/liquibase/changelog/20190619192229_added_entity_Region.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192230_added_entity_Country.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192230_added_entity_constraints_Country.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192231_added_entity_Location.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192231_added_entity_constraints_Location.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192232_added_entity_Department.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192232_added_entity_constraints_Department.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192233_added_entity_Task.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192234_added_entity_Employee.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192234_added_entity_constraints_Employee.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192235_added_entity_Job.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192235_added_entity_constraints_Job.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192236_added_entity_JobHistory.xml create mode 100644 src/main/resources/config/liquibase/changelog/20190619192236_added_entity_constraints_JobHistory.xml create mode 100644 src/main/resources/config/liquibase/data/country.csv create mode 100644 src/main/resources/config/liquibase/data/department.csv create mode 100644 src/main/resources/config/liquibase/data/employee.csv create mode 100644 src/main/resources/config/liquibase/data/job.csv create mode 100644 src/main/resources/config/liquibase/data/job_history.csv create mode 100644 src/main/resources/config/liquibase/data/location.csv create mode 100644 src/main/resources/config/liquibase/data/region.csv create mode 100644 src/main/resources/config/liquibase/data/task.csv create mode 100644 src/main/webapp/app/entities/country/country-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/country/country-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/country/country-detail.component.html create mode 100644 src/main/webapp/app/entities/country/country-detail.component.ts create mode 100644 src/main/webapp/app/entities/country/country-update.component.html create mode 100644 src/main/webapp/app/entities/country/country-update.component.ts create mode 100644 src/main/webapp/app/entities/country/country.component.html create mode 100644 src/main/webapp/app/entities/country/country.component.ts create mode 100644 src/main/webapp/app/entities/country/country.module.ts create mode 100644 src/main/webapp/app/entities/country/country.route.ts create mode 100644 src/main/webapp/app/entities/country/country.service.ts create mode 100644 src/main/webapp/app/entities/country/index.ts create mode 100644 src/main/webapp/app/entities/department/department-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/department/department-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/department/department-detail.component.html create mode 100644 src/main/webapp/app/entities/department/department-detail.component.ts create mode 100644 src/main/webapp/app/entities/department/department-update.component.html create mode 100644 src/main/webapp/app/entities/department/department-update.component.ts create mode 100644 src/main/webapp/app/entities/department/department.component.html create mode 100644 src/main/webapp/app/entities/department/department.component.ts create mode 100644 src/main/webapp/app/entities/department/department.module.ts create mode 100644 src/main/webapp/app/entities/department/department.route.ts create mode 100644 src/main/webapp/app/entities/department/department.service.ts create mode 100644 src/main/webapp/app/entities/department/index.ts create mode 100644 src/main/webapp/app/entities/employee/employee-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/employee/employee-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/employee/employee-detail.component.html create mode 100644 src/main/webapp/app/entities/employee/employee-detail.component.ts create mode 100644 src/main/webapp/app/entities/employee/employee-update.component.html create mode 100644 src/main/webapp/app/entities/employee/employee-update.component.ts create mode 100644 src/main/webapp/app/entities/employee/employee.component.html create mode 100644 src/main/webapp/app/entities/employee/employee.component.ts create mode 100644 src/main/webapp/app/entities/employee/employee.module.ts create mode 100644 src/main/webapp/app/entities/employee/employee.route.ts create mode 100644 src/main/webapp/app/entities/employee/employee.service.ts create mode 100644 src/main/webapp/app/entities/employee/index.ts create mode 100644 src/main/webapp/app/entities/job-history/index.ts create mode 100644 src/main/webapp/app/entities/job-history/job-history-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/job-history/job-history-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/job-history/job-history-detail.component.html create mode 100644 src/main/webapp/app/entities/job-history/job-history-detail.component.ts create mode 100644 src/main/webapp/app/entities/job-history/job-history-update.component.html create mode 100644 src/main/webapp/app/entities/job-history/job-history-update.component.ts create mode 100644 src/main/webapp/app/entities/job-history/job-history.component.html create mode 100644 src/main/webapp/app/entities/job-history/job-history.component.ts create mode 100644 src/main/webapp/app/entities/job-history/job-history.module.ts create mode 100644 src/main/webapp/app/entities/job-history/job-history.route.ts create mode 100644 src/main/webapp/app/entities/job-history/job-history.service.ts create mode 100644 src/main/webapp/app/entities/job/index.ts create mode 100644 src/main/webapp/app/entities/job/job-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/job/job-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/job/job-detail.component.html create mode 100644 src/main/webapp/app/entities/job/job-detail.component.ts create mode 100644 src/main/webapp/app/entities/job/job-update.component.html create mode 100644 src/main/webapp/app/entities/job/job-update.component.ts create mode 100644 src/main/webapp/app/entities/job/job.component.html create mode 100644 src/main/webapp/app/entities/job/job.component.ts create mode 100644 src/main/webapp/app/entities/job/job.module.ts create mode 100644 src/main/webapp/app/entities/job/job.route.ts create mode 100644 src/main/webapp/app/entities/job/job.service.ts create mode 100644 src/main/webapp/app/entities/location/index.ts create mode 100644 src/main/webapp/app/entities/location/location-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/location/location-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/location/location-detail.component.html create mode 100644 src/main/webapp/app/entities/location/location-detail.component.ts create mode 100644 src/main/webapp/app/entities/location/location-update.component.html create mode 100644 src/main/webapp/app/entities/location/location-update.component.ts create mode 100644 src/main/webapp/app/entities/location/location.component.html create mode 100644 src/main/webapp/app/entities/location/location.component.ts create mode 100644 src/main/webapp/app/entities/location/location.module.ts create mode 100644 src/main/webapp/app/entities/location/location.route.ts create mode 100644 src/main/webapp/app/entities/location/location.service.ts create mode 100644 src/main/webapp/app/entities/region/index.ts create mode 100644 src/main/webapp/app/entities/region/region-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/region/region-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/region/region-detail.component.html create mode 100644 src/main/webapp/app/entities/region/region-detail.component.ts create mode 100644 src/main/webapp/app/entities/region/region-update.component.html create mode 100644 src/main/webapp/app/entities/region/region-update.component.ts create mode 100644 src/main/webapp/app/entities/region/region.component.html create mode 100644 src/main/webapp/app/entities/region/region.component.ts create mode 100644 src/main/webapp/app/entities/region/region.module.ts create mode 100644 src/main/webapp/app/entities/region/region.route.ts create mode 100644 src/main/webapp/app/entities/region/region.service.ts create mode 100644 src/main/webapp/app/entities/task/index.ts create mode 100644 src/main/webapp/app/entities/task/task-delete-dialog.component.html create mode 100644 src/main/webapp/app/entities/task/task-delete-dialog.component.ts create mode 100644 src/main/webapp/app/entities/task/task-detail.component.html create mode 100644 src/main/webapp/app/entities/task/task-detail.component.ts create mode 100644 src/main/webapp/app/entities/task/task-update.component.html create mode 100644 src/main/webapp/app/entities/task/task-update.component.ts create mode 100644 src/main/webapp/app/entities/task/task.component.html create mode 100644 src/main/webapp/app/entities/task/task.component.ts create mode 100644 src/main/webapp/app/entities/task/task.module.ts create mode 100644 src/main/webapp/app/entities/task/task.route.ts create mode 100644 src/main/webapp/app/entities/task/task.service.ts create mode 100644 src/main/webapp/app/shared/model/country.model.ts create mode 100644 src/main/webapp/app/shared/model/department.model.ts create mode 100644 src/main/webapp/app/shared/model/employee.model.ts create mode 100644 src/main/webapp/app/shared/model/job-history.model.ts create mode 100644 src/main/webapp/app/shared/model/job.model.ts create mode 100644 src/main/webapp/app/shared/model/location.model.ts create mode 100644 src/main/webapp/app/shared/model/region.model.ts create mode 100644 src/main/webapp/app/shared/model/task.model.ts create mode 100644 src/test/java/org/zdar/repository/search/CountrySearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/repository/search/DepartmentSearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/repository/search/EmployeeSearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/repository/search/JobHistorySearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/repository/search/JobSearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/repository/search/LocationSearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/repository/search/RegionSearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/repository/search/TaskSearchRepositoryMockConfiguration.java create mode 100644 src/test/java/org/zdar/web/rest/CountryResourceIT.java create mode 100644 src/test/java/org/zdar/web/rest/DepartmentResourceIT.java create mode 100644 src/test/java/org/zdar/web/rest/EmployeeResourceIT.java create mode 100644 src/test/java/org/zdar/web/rest/JobHistoryResourceIT.java create mode 100644 src/test/java/org/zdar/web/rest/JobResourceIT.java create mode 100644 src/test/java/org/zdar/web/rest/LocationResourceIT.java create mode 100644 src/test/java/org/zdar/web/rest/RegionResourceIT.java create mode 100644 src/test/java/org/zdar/web/rest/TaskResourceIT.java create mode 100644 src/test/javascript/e2e/entities/country/country.page-object.ts create mode 100644 src/test/javascript/e2e/entities/country/country.spec.ts create mode 100644 src/test/javascript/e2e/entities/department/department.page-object.ts create mode 100644 src/test/javascript/e2e/entities/department/department.spec.ts create mode 100644 src/test/javascript/e2e/entities/employee/employee.page-object.ts create mode 100644 src/test/javascript/e2e/entities/employee/employee.spec.ts create mode 100644 src/test/javascript/e2e/entities/job-history/job-history.page-object.ts create mode 100644 src/test/javascript/e2e/entities/job-history/job-history.spec.ts create mode 100644 src/test/javascript/e2e/entities/job/job.page-object.ts create mode 100644 src/test/javascript/e2e/entities/job/job.spec.ts create mode 100644 src/test/javascript/e2e/entities/location/location.page-object.ts create mode 100644 src/test/javascript/e2e/entities/location/location.spec.ts create mode 100644 src/test/javascript/e2e/entities/region/region.page-object.ts create mode 100644 src/test/javascript/e2e/entities/region/region.spec.ts create mode 100644 src/test/javascript/e2e/entities/task/task.page-object.ts create mode 100644 src/test/javascript/e2e/entities/task/task.spec.ts create mode 100644 src/test/javascript/spec/app/entities/country/country-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/country/country-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/country/country-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/country/country.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/country/country.service.spec.ts create mode 100644 src/test/javascript/spec/app/entities/department/department-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/department/department-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/department/department-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/department/department.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/department/department.service.spec.ts create mode 100644 src/test/javascript/spec/app/entities/employee/employee-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/employee/employee-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/employee/employee-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/employee/employee.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/employee/employee.service.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job-history/job-history-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job-history/job-history-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job-history/job-history-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job-history/job-history.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job-history/job-history.service.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job/job-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job/job-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job/job-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job/job.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/job/job.service.spec.ts create mode 100644 src/test/javascript/spec/app/entities/location/location-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/location/location-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/location/location-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/location/location.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/location/location.service.spec.ts create mode 100644 src/test/javascript/spec/app/entities/region/region-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/region/region-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/region/region-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/region/region.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/region/region.service.spec.ts create mode 100644 src/test/javascript/spec/app/entities/task/task-delete-dialog.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/task/task-detail.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/task/task-update.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/task/task.component.spec.ts create mode 100644 src/test/javascript/spec/app/entities/task/task.service.spec.ts diff --git a/.jhipster/Country.json b/.jhipster/Country.json new file mode 100644 index 0000000..136b28d --- /dev/null +++ b/.jhipster/Country.json @@ -0,0 +1,28 @@ +{ + "name": "Country", + "fields": [ + { + "fieldName": "countryName", + "fieldType": "String" + } + ], + "relationships": [ + { + "relationshipType": "one-to-one", + "otherEntityName": "region", + "otherEntityRelationshipName": "country", + "relationshipName": "region", + "otherEntityField": "id", + "ownerSide": true + } + ], + "changelogDate": "20190619192230", + "entityTableName": "country", + "dto": "mapstruct", + "pagination": "no", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/Department.json b/.jhipster/Department.json new file mode 100644 index 0000000..91ed02f --- /dev/null +++ b/.jhipster/Department.json @@ -0,0 +1,38 @@ +{ + "name": "Department", + "fields": [ + { + "fieldName": "departmentName", + "fieldType": "String", + "fieldValidateRules": [ + "required" + ] + } + ], + "relationships": [ + { + "relationshipType": "one-to-one", + "otherEntityName": "location", + "otherEntityRelationshipName": "department", + "relationshipName": "location", + "otherEntityField": "id", + "ownerSide": true + }, + { + "relationshipType": "one-to-many", + "otherEntityName": "employee", + "otherEntityRelationshipName": "department", + "javadoc": "A relationship", + "relationshipName": "employee" + } + ], + "changelogDate": "20190619192232", + "entityTableName": "department", + "dto": "mapstruct", + "pagination": "no", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/Employee.json b/.jhipster/Employee.json new file mode 100644 index 0000000..2a42b35 --- /dev/null +++ b/.jhipster/Employee.json @@ -0,0 +1,65 @@ +{ + "name": "Employee", + "fields": [ + { + "fieldName": "firstName", + "javadoc": "The firstname attribute.", + "fieldType": "String" + }, + { + "fieldName": "lastName", + "fieldType": "String" + }, + { + "fieldName": "email", + "fieldType": "String" + }, + { + "fieldName": "phoneNumber", + "fieldType": "String" + }, + { + "fieldName": "hireDate", + "fieldType": "Instant" + }, + { + "fieldName": "salary", + "fieldType": "Long" + }, + { + "fieldName": "commissionPct", + "fieldType": "Long" + } + ], + "relationships": [ + { + "relationshipName": "department", + "otherEntityName": "department", + "relationshipType": "many-to-one", + "otherEntityField": "id" + }, + { + "relationshipType": "one-to-many", + "otherEntityName": "job", + "otherEntityRelationshipName": "employee", + "relationshipName": "job" + }, + { + "relationshipType": "many-to-one", + "otherEntityName": "employee", + "otherEntityRelationshipName": "employee", + "relationshipName": "manager", + "otherEntityField": "id" + } + ], + "changelogDate": "20190619192234", + "javadoc": "The Employee entity.", + "entityTableName": "employee", + "dto": "mapstruct", + "pagination": "infinite-scroll", + "service": "serviceClass", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/Job.json b/.jhipster/Job.json new file mode 100644 index 0000000..3865867 --- /dev/null +++ b/.jhipster/Job.json @@ -0,0 +1,42 @@ +{ + "name": "Job", + "fields": [ + { + "fieldName": "jobTitle", + "fieldType": "String" + }, + { + "fieldName": "minSalary", + "fieldType": "Long" + }, + { + "fieldName": "maxSalary", + "fieldType": "Long" + } + ], + "relationships": [ + { + "relationshipName": "employee", + "otherEntityName": "employee", + "relationshipType": "many-to-one", + "otherEntityField": "id" + }, + { + "relationshipType": "many-to-many", + "otherEntityName": "task", + "otherEntityRelationshipName": "job", + "relationshipName": "task", + "otherEntityField": "title", + "ownerSide": true + } + ], + "changelogDate": "20190619192235", + "entityTableName": "job", + "dto": "mapstruct", + "pagination": "pagination", + "service": "serviceClass", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/JobHistory.json b/.jhipster/JobHistory.json new file mode 100644 index 0000000..079eee7 --- /dev/null +++ b/.jhipster/JobHistory.json @@ -0,0 +1,53 @@ +{ + "name": "JobHistory", + "fields": [ + { + "fieldName": "startDate", + "fieldType": "Instant" + }, + { + "fieldName": "endDate", + "fieldType": "Instant" + }, + { + "fieldName": "language", + "fieldType": "Language", + "fieldValues": "FRENCH,ENGLISH,SPANISH" + } + ], + "relationships": [ + { + "relationshipType": "one-to-one", + "otherEntityName": "job", + "otherEntityRelationshipName": "jobHistory", + "relationshipName": "job", + "otherEntityField": "id", + "ownerSide": true + }, + { + "relationshipType": "one-to-one", + "otherEntityName": "department", + "otherEntityRelationshipName": "jobHistory", + "relationshipName": "department", + "otherEntityField": "id", + "ownerSide": true + }, + { + "relationshipType": "one-to-one", + "otherEntityName": "employee", + "otherEntityRelationshipName": "jobHistory", + "relationshipName": "employee", + "otherEntityField": "id", + "ownerSide": true + } + ], + "changelogDate": "20190619192236", + "entityTableName": "job_history", + "dto": "mapstruct", + "pagination": "infinite-scroll", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/Location.json b/.jhipster/Location.json new file mode 100644 index 0000000..dce2c1b --- /dev/null +++ b/.jhipster/Location.json @@ -0,0 +1,41 @@ +{ + "name": "Location", + "fields": [ + { + "fieldName": "streetAddress", + "fieldType": "String" + }, + { + "fieldName": "postalCode", + "fieldType": "String" + }, + { + "fieldName": "city", + "fieldType": "String" + }, + { + "fieldName": "stateProvince", + "fieldType": "String" + } + ], + "relationships": [ + { + "relationshipType": "one-to-one", + "otherEntityName": "country", + "otherEntityRelationshipName": "location", + "relationshipName": "country", + "otherEntityField": "id", + "ownerSide": true + } + ], + "changelogDate": "20190619192231", + "javadoc": "not an ignored comment", + "entityTableName": "location", + "dto": "mapstruct", + "pagination": "no", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/Region.json b/.jhipster/Region.json new file mode 100644 index 0000000..365379f --- /dev/null +++ b/.jhipster/Region.json @@ -0,0 +1,19 @@ +{ + "name": "Region", + "fields": [ + { + "fieldName": "regionName", + "fieldType": "String" + } + ], + "relationships": [], + "changelogDate": "20190619192229", + "entityTableName": "region", + "dto": "mapstruct", + "pagination": "no", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/.jhipster/Task.json b/.jhipster/Task.json new file mode 100644 index 0000000..cc16f4b --- /dev/null +++ b/.jhipster/Task.json @@ -0,0 +1,33 @@ +{ + "name": "Task", + "fields": [ + { + "fieldName": "title", + "fieldType": "String" + }, + { + "fieldName": "description", + "fieldType": "String" + } + ], + "relationships": [ + { + "relationshipType": "many-to-many", + "otherEntityName": "job", + "otherEntityRelationshipName": "task", + "relationshipName": "job", + "otherEntityField": "id", + "ownerSide": false + } + ], + "changelogDate": "20190619192233", + "javadoc": "Task entity.\n@author The JHipster team.", + "entityTableName": "task", + "dto": "mapstruct", + "pagination": "no", + "service": "serviceImpl", + "jpaMetamodelFiltering": false, + "fluentMethods": true, + "clientRootFolder": "", + "applications": "*" +} \ No newline at end of file diff --git a/src/main/java/org/zdar/domain/Country.java b/src/main/java/org/zdar/domain/Country.java new file mode 100644 index 0000000..f4ee739 --- /dev/null +++ b/src/main/java/org/zdar/domain/Country.java @@ -0,0 +1,90 @@ +package org.zdar.domain; + +import javax.persistence.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; + +/** + * A Country. + */ +@Entity +@Table(name = "country") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "country") +public class Country implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + @Column(name = "country_name") + private String countryName; + + @OneToOne + @JoinColumn(unique = true) + private Region region; + + // 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 getCountryName() { + return countryName; + } + + public Country countryName(String countryName) { + this.countryName = countryName; + return this; + } + + public void setCountryName(String countryName) { + this.countryName = countryName; + } + + public Region getRegion() { + return region; + } + + public Country region(Region region) { + this.region = region; + return this; + } + + public void setRegion(Region region) { + this.region = region; + } + // 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 Country)) { + return false; + } + return id != null && id.equals(((Country) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Country{" + + "id=" + getId() + + ", countryName='" + getCountryName() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/Department.java b/src/main/java/org/zdar/domain/Department.java new file mode 100644 index 0000000..f740808 --- /dev/null +++ b/src/main/java/org/zdar/domain/Department.java @@ -0,0 +1,125 @@ +package org.zdar.domain; + +import javax.persistence.*; +import javax.validation.constraints.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +/** + * A Department. + */ +@Entity +@Table(name = "department") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "department") +public class Department implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + @NotNull + @Column(name = "department_name", nullable = false) + private String departmentName; + + @OneToOne + @JoinColumn(unique = true) + private Location location; + + /** + * A relationship + */ + @OneToMany(mappedBy = "department") + private Set employees = new HashSet<>(); + + // 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 getDepartmentName() { + return departmentName; + } + + public Department departmentName(String departmentName) { + this.departmentName = departmentName; + return this; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } + + public Location getLocation() { + return location; + } + + public Department location(Location location) { + this.location = location; + return this; + } + + public void setLocation(Location location) { + this.location = location; + } + + public Set getEmployees() { + return employees; + } + + public Department employees(Set employees) { + this.employees = employees; + return this; + } + + public Department addEmployee(Employee employee) { + this.employees.add(employee); + employee.setDepartment(this); + return this; + } + + public Department removeEmployee(Employee employee) { + this.employees.remove(employee); + employee.setDepartment(null); + return this; + } + + public void setEmployees(Set employees) { + this.employees = employees; + } + // 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 Department)) { + return false; + } + return id != null && id.equals(((Department) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Department{" + + "id=" + getId() + + ", departmentName='" + getDepartmentName() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/Employee.java b/src/main/java/org/zdar/domain/Employee.java new file mode 100644 index 0000000..acd09c5 --- /dev/null +++ b/src/main/java/org/zdar/domain/Employee.java @@ -0,0 +1,244 @@ +package org.zdar.domain; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; +import java.time.Instant; +import java.util.HashSet; +import java.util.Set; + +/** + * The Employee entity. + */ +@Entity +@Table(name = "employee") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "employee") +public class Employee implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + /** + * The firstname attribute. + */ + @Column(name = "first_name") + private String firstName; + + @Column(name = "last_name") + private String lastName; + + @Column(name = "email") + private String email; + + @Column(name = "phone_number") + private String phoneNumber; + + @Column(name = "hire_date") + private Instant hireDate; + + @Column(name = "salary") + private Long salary; + + @Column(name = "commission_pct") + private Long commissionPct; + + @ManyToOne + @JsonIgnoreProperties("employees") + private Department department; + + @OneToMany(mappedBy = "employee") + private Set jobs = new HashSet<>(); + + @ManyToOne + @JsonIgnoreProperties("employees") + private Employee manager; + + // 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 getFirstName() { + return firstName; + } + + public Employee firstName(String firstName) { + this.firstName = firstName; + return this; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public Employee lastName(String lastName) { + this.lastName = lastName; + return this; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public Employee email(String email) { + this.email = email; + return this; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public Employee phoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + return this; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public Instant getHireDate() { + return hireDate; + } + + public Employee hireDate(Instant hireDate) { + this.hireDate = hireDate; + return this; + } + + public void setHireDate(Instant hireDate) { + this.hireDate = hireDate; + } + + public Long getSalary() { + return salary; + } + + public Employee salary(Long salary) { + this.salary = salary; + return this; + } + + public void setSalary(Long salary) { + this.salary = salary; + } + + public Long getCommissionPct() { + return commissionPct; + } + + public Employee commissionPct(Long commissionPct) { + this.commissionPct = commissionPct; + return this; + } + + public void setCommissionPct(Long commissionPct) { + this.commissionPct = commissionPct; + } + + public Department getDepartment() { + return department; + } + + public Employee department(Department department) { + this.department = department; + return this; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public Set getJobs() { + return jobs; + } + + public Employee jobs(Set jobs) { + this.jobs = jobs; + return this; + } + + public Employee addJob(Job job) { + this.jobs.add(job); + job.setEmployee(this); + return this; + } + + public Employee removeJob(Job job) { + this.jobs.remove(job); + job.setEmployee(null); + return this; + } + + public void setJobs(Set jobs) { + this.jobs = jobs; + } + + public Employee getManager() { + return manager; + } + + public Employee manager(Employee employee) { + this.manager = employee; + return this; + } + + public void setManager(Employee employee) { + this.manager = employee; + } + // 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 Employee)) { + return false; + } + return id != null && id.equals(((Employee) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + getId() + + ", firstName='" + getFirstName() + "'" + + ", lastName='" + getLastName() + "'" + + ", email='" + getEmail() + "'" + + ", phoneNumber='" + getPhoneNumber() + "'" + + ", hireDate='" + getHireDate() + "'" + + ", salary=" + getSalary() + + ", commissionPct=" + getCommissionPct() + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/Job.java b/src/main/java/org/zdar/domain/Job.java new file mode 100644 index 0000000..cf0f829 --- /dev/null +++ b/src/main/java/org/zdar/domain/Job.java @@ -0,0 +1,158 @@ +package org.zdar.domain; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +/** + * A Job. + */ +@Entity +@Table(name = "job") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "job") +public class Job implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + @Column(name = "job_title") + private String jobTitle; + + @Column(name = "min_salary") + private Long minSalary; + + @Column(name = "max_salary") + private Long maxSalary; + + @ManyToOne + @JsonIgnoreProperties("jobs") + private Employee employee; + + @ManyToMany + @JoinTable(name = "job_task", + joinColumns = @JoinColumn(name = "job_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "task_id", referencedColumnName = "id")) + private Set tasks = new HashSet<>(); + + // 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 getJobTitle() { + return jobTitle; + } + + public Job jobTitle(String jobTitle) { + this.jobTitle = jobTitle; + return this; + } + + public void setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + } + + public Long getMinSalary() { + return minSalary; + } + + public Job minSalary(Long minSalary) { + this.minSalary = minSalary; + return this; + } + + public void setMinSalary(Long minSalary) { + this.minSalary = minSalary; + } + + public Long getMaxSalary() { + return maxSalary; + } + + public Job maxSalary(Long maxSalary) { + this.maxSalary = maxSalary; + return this; + } + + public void setMaxSalary(Long maxSalary) { + this.maxSalary = maxSalary; + } + + public Employee getEmployee() { + return employee; + } + + public Job employee(Employee employee) { + this.employee = employee; + return this; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public Set getTasks() { + return tasks; + } + + public Job tasks(Set tasks) { + this.tasks = tasks; + return this; + } + + public Job addTask(Task task) { + this.tasks.add(task); + task.getJobs().add(this); + return this; + } + + public Job removeTask(Task task) { + this.tasks.remove(task); + task.getJobs().remove(this); + return this; + } + + public void setTasks(Set tasks) { + this.tasks = tasks; + } + // 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 Job)) { + return false; + } + return id != null && id.equals(((Job) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Job{" + + "id=" + getId() + + ", jobTitle='" + getJobTitle() + "'" + + ", minSalary=" + getMinSalary() + + ", maxSalary=" + getMaxSalary() + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/JobHistory.java b/src/main/java/org/zdar/domain/JobHistory.java new file mode 100644 index 0000000..3a9f5bb --- /dev/null +++ b/src/main/java/org/zdar/domain/JobHistory.java @@ -0,0 +1,162 @@ +package org.zdar.domain; + +import javax.persistence.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; +import java.time.Instant; + +import org.zdar.domain.enumeration.Language; + +/** + * A JobHistory. + */ +@Entity +@Table(name = "job_history") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "jobhistory") +public class JobHistory implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + @Column(name = "start_date") + private Instant startDate; + + @Column(name = "end_date") + private Instant endDate; + + @Enumerated(EnumType.STRING) + @Column(name = "language") + private Language language; + + @OneToOne + @JoinColumn(unique = true) + private Job job; + + @OneToOne + @JoinColumn(unique = true) + private Department department; + + @OneToOne + @JoinColumn(unique = true) + private Employee employee; + + // 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 Instant getStartDate() { + return startDate; + } + + public JobHistory startDate(Instant startDate) { + this.startDate = startDate; + return this; + } + + public void setStartDate(Instant startDate) { + this.startDate = startDate; + } + + public Instant getEndDate() { + return endDate; + } + + public JobHistory endDate(Instant endDate) { + this.endDate = endDate; + return this; + } + + public void setEndDate(Instant endDate) { + this.endDate = endDate; + } + + public Language getLanguage() { + return language; + } + + public JobHistory language(Language language) { + this.language = language; + return this; + } + + public void setLanguage(Language language) { + this.language = language; + } + + public Job getJob() { + return job; + } + + public JobHistory job(Job job) { + this.job = job; + return this; + } + + public void setJob(Job job) { + this.job = job; + } + + public Department getDepartment() { + return department; + } + + public JobHistory department(Department department) { + this.department = department; + return this; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public Employee getEmployee() { + return employee; + } + + public JobHistory employee(Employee employee) { + this.employee = employee; + return this; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + // 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 JobHistory)) { + return false; + } + return id != null && id.equals(((JobHistory) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "JobHistory{" + + "id=" + getId() + + ", startDate='" + getStartDate() + "'" + + ", endDate='" + getEndDate() + "'" + + ", language='" + getLanguage() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/Location.java b/src/main/java/org/zdar/domain/Location.java new file mode 100644 index 0000000..9b9877c --- /dev/null +++ b/src/main/java/org/zdar/domain/Location.java @@ -0,0 +1,141 @@ +package org.zdar.domain; + +import javax.persistence.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; + +/** + * not an ignored comment + */ +@Entity +@Table(name = "location") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "location") +public class Location implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + @Column(name = "street_address") + private String streetAddress; + + @Column(name = "postal_code") + private String postalCode; + + @Column(name = "city") + private String city; + + @Column(name = "state_province") + private String stateProvince; + + @OneToOne + @JoinColumn(unique = true) + private Country country; + + // 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 getStreetAddress() { + return streetAddress; + } + + public Location streetAddress(String streetAddress) { + this.streetAddress = streetAddress; + return this; + } + + public void setStreetAddress(String streetAddress) { + this.streetAddress = streetAddress; + } + + public String getPostalCode() { + return postalCode; + } + + public Location postalCode(String postalCode) { + this.postalCode = postalCode; + return this; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getCity() { + return city; + } + + public Location city(String city) { + this.city = city; + return this; + } + + public void setCity(String city) { + this.city = city; + } + + public String getStateProvince() { + return stateProvince; + } + + public Location stateProvince(String stateProvince) { + this.stateProvince = stateProvince; + return this; + } + + public void setStateProvince(String stateProvince) { + this.stateProvince = stateProvince; + } + + public Country getCountry() { + return country; + } + + public Location country(Country country) { + this.country = country; + return this; + } + + public void setCountry(Country country) { + this.country = country; + } + // 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 Location)) { + return false; + } + return id != null && id.equals(((Location) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Location{" + + "id=" + getId() + + ", streetAddress='" + getStreetAddress() + "'" + + ", postalCode='" + getPostalCode() + "'" + + ", city='" + getCity() + "'" + + ", stateProvince='" + getStateProvince() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/Region.java b/src/main/java/org/zdar/domain/Region.java new file mode 100644 index 0000000..6f2ed86 --- /dev/null +++ b/src/main/java/org/zdar/domain/Region.java @@ -0,0 +1,73 @@ +package org.zdar.domain; + +import javax.persistence.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; + +/** + * A Region. + */ +@Entity +@Table(name = "region") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "region") +public class Region implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + @Column(name = "region_name") + private String regionName; + + // 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 getRegionName() { + return regionName; + } + + public Region regionName(String regionName) { + this.regionName = regionName; + return this; + } + + public void setRegionName(String regionName) { + this.regionName = regionName; + } + // 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 Region)) { + return false; + } + return id != null && id.equals(((Region) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Region{" + + "id=" + getId() + + ", regionName='" + getRegionName() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/Task.java b/src/main/java/org/zdar/domain/Task.java new file mode 100644 index 0000000..6320265 --- /dev/null +++ b/src/main/java/org/zdar/domain/Task.java @@ -0,0 +1,123 @@ +package org.zdar.domain; +import com.fasterxml.jackson.annotation.JsonIgnore; + +import javax.persistence.*; + +import org.springframework.data.elasticsearch.annotations.FieldType; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +/** + * Task entity. + * @author The JHipster team. + */ +@Entity +@Table(name = "task") +@org.springframework.data.elasticsearch.annotations.Document(indexName = "task") +public class Task implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") + @SequenceGenerator(name = "sequenceGenerator") + @org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword) + private Long id; + + @Column(name = "title") + private String title; + + @Column(name = "description") + private String description; + + @ManyToMany(mappedBy = "tasks") + @JsonIgnore + private Set jobs = new HashSet<>(); + + // 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 getTitle() { + return title; + } + + public Task title(String title) { + this.title = title; + return this; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public Task description(String description) { + this.description = description; + return this; + } + + public void setDescription(String description) { + this.description = description; + } + + public Set getJobs() { + return jobs; + } + + public Task jobs(Set jobs) { + this.jobs = jobs; + return this; + } + + public Task addJob(Job job) { + this.jobs.add(job); + job.getTasks().add(this); + return this; + } + + public Task removeJob(Job job) { + this.jobs.remove(job); + job.getTasks().remove(this); + return this; + } + + public void setJobs(Set jobs) { + this.jobs = jobs; + } + // 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 Task)) { + return false; + } + return id != null && id.equals(((Task) o).id); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public String toString() { + return "Task{" + + "id=" + getId() + + ", title='" + getTitle() + "'" + + ", description='" + getDescription() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/domain/enumeration/Language.java b/src/main/java/org/zdar/domain/enumeration/Language.java new file mode 100644 index 0000000..9b126cf --- /dev/null +++ b/src/main/java/org/zdar/domain/enumeration/Language.java @@ -0,0 +1,8 @@ +package org.zdar.domain.enumeration; + +/** + * The Language enumeration. + */ +public enum Language { + FRENCH, ENGLISH, SPANISH +} diff --git a/src/main/java/org/zdar/repository/CountryRepository.java b/src/main/java/org/zdar/repository/CountryRepository.java new file mode 100644 index 0000000..3be0c04 --- /dev/null +++ b/src/main/java/org/zdar/repository/CountryRepository.java @@ -0,0 +1,15 @@ +package org.zdar.repository; + +import org.zdar.domain.Country; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Country entity. + */ +@SuppressWarnings("unused") +@Repository +public interface CountryRepository extends JpaRepository { + +} diff --git a/src/main/java/org/zdar/repository/DepartmentRepository.java b/src/main/java/org/zdar/repository/DepartmentRepository.java new file mode 100644 index 0000000..8e75410 --- /dev/null +++ b/src/main/java/org/zdar/repository/DepartmentRepository.java @@ -0,0 +1,15 @@ +package org.zdar.repository; + +import org.zdar.domain.Department; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Department entity. + */ +@SuppressWarnings("unused") +@Repository +public interface DepartmentRepository extends JpaRepository { + +} diff --git a/src/main/java/org/zdar/repository/EmployeeRepository.java b/src/main/java/org/zdar/repository/EmployeeRepository.java new file mode 100644 index 0000000..ebbd466 --- /dev/null +++ b/src/main/java/org/zdar/repository/EmployeeRepository.java @@ -0,0 +1,15 @@ +package org.zdar.repository; + +import org.zdar.domain.Employee; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Employee entity. + */ +@SuppressWarnings("unused") +@Repository +public interface EmployeeRepository extends JpaRepository { + +} diff --git a/src/main/java/org/zdar/repository/JobHistoryRepository.java b/src/main/java/org/zdar/repository/JobHistoryRepository.java new file mode 100644 index 0000000..a7f30b3 --- /dev/null +++ b/src/main/java/org/zdar/repository/JobHistoryRepository.java @@ -0,0 +1,15 @@ +package org.zdar.repository; + +import org.zdar.domain.JobHistory; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the JobHistory entity. + */ +@SuppressWarnings("unused") +@Repository +public interface JobHistoryRepository extends JpaRepository { + +} diff --git a/src/main/java/org/zdar/repository/JobRepository.java b/src/main/java/org/zdar/repository/JobRepository.java new file mode 100644 index 0000000..ffd2df8 --- /dev/null +++ b/src/main/java/org/zdar/repository/JobRepository.java @@ -0,0 +1,29 @@ +package org.zdar.repository; + +import org.zdar.domain.Job; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.*; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +/** + * Spring Data repository for the Job entity. + */ +@Repository +public interface JobRepository extends JpaRepository { + + @Query(value = "select distinct job from Job job left join fetch job.tasks", + countQuery = "select count(distinct job) from Job job") + Page findAllWithEagerRelationships(Pageable pageable); + + @Query("select distinct job from Job job left join fetch job.tasks") + List findAllWithEagerRelationships(); + + @Query("select job from Job job left join fetch job.tasks where job.id =:id") + Optional findOneWithEagerRelationships(@Param("id") Long id); + +} diff --git a/src/main/java/org/zdar/repository/LocationRepository.java b/src/main/java/org/zdar/repository/LocationRepository.java new file mode 100644 index 0000000..db8aefb --- /dev/null +++ b/src/main/java/org/zdar/repository/LocationRepository.java @@ -0,0 +1,15 @@ +package org.zdar.repository; + +import org.zdar.domain.Location; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Location entity. + */ +@SuppressWarnings("unused") +@Repository +public interface LocationRepository extends JpaRepository { + +} diff --git a/src/main/java/org/zdar/repository/RegionRepository.java b/src/main/java/org/zdar/repository/RegionRepository.java new file mode 100644 index 0000000..c87fb40 --- /dev/null +++ b/src/main/java/org/zdar/repository/RegionRepository.java @@ -0,0 +1,15 @@ +package org.zdar.repository; + +import org.zdar.domain.Region; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Region entity. + */ +@SuppressWarnings("unused") +@Repository +public interface RegionRepository extends JpaRepository { + +} diff --git a/src/main/java/org/zdar/repository/TaskRepository.java b/src/main/java/org/zdar/repository/TaskRepository.java new file mode 100644 index 0000000..5e4f0ff --- /dev/null +++ b/src/main/java/org/zdar/repository/TaskRepository.java @@ -0,0 +1,15 @@ +package org.zdar.repository; + +import org.zdar.domain.Task; +import org.springframework.data.jpa.repository.*; +import org.springframework.stereotype.Repository; + + +/** + * Spring Data repository for the Task entity. + */ +@SuppressWarnings("unused") +@Repository +public interface TaskRepository extends JpaRepository { + +} diff --git a/src/main/java/org/zdar/repository/search/CountrySearchRepository.java b/src/main/java/org/zdar/repository/search/CountrySearchRepository.java new file mode 100644 index 0000000..3244bbc --- /dev/null +++ b/src/main/java/org/zdar/repository/search/CountrySearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.Country; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Country} entity. + */ +public interface CountrySearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/repository/search/DepartmentSearchRepository.java b/src/main/java/org/zdar/repository/search/DepartmentSearchRepository.java new file mode 100644 index 0000000..e4712d3 --- /dev/null +++ b/src/main/java/org/zdar/repository/search/DepartmentSearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.Department; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Department} entity. + */ +public interface DepartmentSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/repository/search/EmployeeSearchRepository.java b/src/main/java/org/zdar/repository/search/EmployeeSearchRepository.java new file mode 100644 index 0000000..d82fff9 --- /dev/null +++ b/src/main/java/org/zdar/repository/search/EmployeeSearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.Employee; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Employee} entity. + */ +public interface EmployeeSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/repository/search/JobHistorySearchRepository.java b/src/main/java/org/zdar/repository/search/JobHistorySearchRepository.java new file mode 100644 index 0000000..357bab0 --- /dev/null +++ b/src/main/java/org/zdar/repository/search/JobHistorySearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.JobHistory; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link JobHistory} entity. + */ +public interface JobHistorySearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/repository/search/JobSearchRepository.java b/src/main/java/org/zdar/repository/search/JobSearchRepository.java new file mode 100644 index 0000000..e26d89e --- /dev/null +++ b/src/main/java/org/zdar/repository/search/JobSearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.Job; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Job} entity. + */ +public interface JobSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/repository/search/LocationSearchRepository.java b/src/main/java/org/zdar/repository/search/LocationSearchRepository.java new file mode 100644 index 0000000..6419f46 --- /dev/null +++ b/src/main/java/org/zdar/repository/search/LocationSearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.Location; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Location} entity. + */ +public interface LocationSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/repository/search/RegionSearchRepository.java b/src/main/java/org/zdar/repository/search/RegionSearchRepository.java new file mode 100644 index 0000000..305d6a3 --- /dev/null +++ b/src/main/java/org/zdar/repository/search/RegionSearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.Region; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Region} entity. + */ +public interface RegionSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/repository/search/TaskSearchRepository.java b/src/main/java/org/zdar/repository/search/TaskSearchRepository.java new file mode 100644 index 0000000..5a8e505 --- /dev/null +++ b/src/main/java/org/zdar/repository/search/TaskSearchRepository.java @@ -0,0 +1,10 @@ +package org.zdar.repository.search; + +import org.zdar.domain.Task; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +/** + * Spring Data Elasticsearch repository for the {@link Task} entity. + */ +public interface TaskSearchRepository extends ElasticsearchRepository { +} diff --git a/src/main/java/org/zdar/service/CountryService.java b/src/main/java/org/zdar/service/CountryService.java new file mode 100644 index 0000000..b9479f8 --- /dev/null +++ b/src/main/java/org/zdar/service/CountryService.java @@ -0,0 +1,52 @@ +package org.zdar.service; + +import org.zdar.service.dto.CountryDTO; + +import java.util.List; +import java.util.Optional; + +/** + * Service Interface for managing {@link org.zdar.domain.Country}. + */ +public interface CountryService { + + /** + * Save a country. + * + * @param countryDTO the entity to save. + * @return the persisted entity. + */ + CountryDTO save(CountryDTO countryDTO); + + /** + * Get all the countries. + * + * @return the list of entities. + */ + List findAll(); + + + /** + * Get the "id" country. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" country. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the country corresponding to the query. + * + * @param query the query of the search. + * + * @return the list of entities. + */ + List search(String query); +} diff --git a/src/main/java/org/zdar/service/DepartmentService.java b/src/main/java/org/zdar/service/DepartmentService.java new file mode 100644 index 0000000..83fb342 --- /dev/null +++ b/src/main/java/org/zdar/service/DepartmentService.java @@ -0,0 +1,52 @@ +package org.zdar.service; + +import org.zdar.service.dto.DepartmentDTO; + +import java.util.List; +import java.util.Optional; + +/** + * Service Interface for managing {@link org.zdar.domain.Department}. + */ +public interface DepartmentService { + + /** + * Save a department. + * + * @param departmentDTO the entity to save. + * @return the persisted entity. + */ + DepartmentDTO save(DepartmentDTO departmentDTO); + + /** + * Get all the departments. + * + * @return the list of entities. + */ + List findAll(); + + + /** + * Get the "id" department. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" department. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the department corresponding to the query. + * + * @param query the query of the search. + * + * @return the list of entities. + */ + List search(String query); +} diff --git a/src/main/java/org/zdar/service/EmployeeService.java b/src/main/java/org/zdar/service/EmployeeService.java new file mode 100644 index 0000000..d1e40c2 --- /dev/null +++ b/src/main/java/org/zdar/service/EmployeeService.java @@ -0,0 +1,107 @@ +package org.zdar.service; + +import org.zdar.domain.Employee; +import org.zdar.repository.EmployeeRepository; +import org.zdar.repository.search.EmployeeSearchRepository; +import org.zdar.service.dto.EmployeeDTO; +import org.zdar.service.mapper.EmployeeMapper; +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 Employee}. + */ +@Service +@Transactional +public class EmployeeService { + + private final Logger log = LoggerFactory.getLogger(EmployeeService.class); + + private final EmployeeRepository employeeRepository; + + private final EmployeeMapper employeeMapper; + + private final EmployeeSearchRepository employeeSearchRepository; + + public EmployeeService(EmployeeRepository employeeRepository, EmployeeMapper employeeMapper, EmployeeSearchRepository employeeSearchRepository) { + this.employeeRepository = employeeRepository; + this.employeeMapper = employeeMapper; + this.employeeSearchRepository = employeeSearchRepository; + } + + /** + * Save a employee. + * + * @param employeeDTO the entity to save. + * @return the persisted entity. + */ + public EmployeeDTO save(EmployeeDTO employeeDTO) { + log.debug("Request to save Employee : {}", employeeDTO); + Employee employee = employeeMapper.toEntity(employeeDTO); + employee = employeeRepository.save(employee); + EmployeeDTO result = employeeMapper.toDto(employee); + employeeSearchRepository.save(employee); + return result; + } + + /** + * Get all the employees. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + log.debug("Request to get all Employees"); + return employeeRepository.findAll(pageable) + .map(employeeMapper::toDto); + } + + + /** + * Get one employee by id. + * + * @param id the id of the entity. + * @return the entity. + */ + @Transactional(readOnly = true) + public Optional findOne(Long id) { + log.debug("Request to get Employee : {}", id); + return employeeRepository.findById(id) + .map(employeeMapper::toDto); + } + + /** + * Delete the employee by id. + * + * @param id the id of the entity. + */ + public void delete(Long id) { + log.debug("Request to delete Employee : {}", id); + employeeRepository.deleteById(id); + employeeSearchRepository.deleteById(id); + } + + /** + * Search for the employee corresponding to the query. + * + * @param query the query of the search. + * @param pageable the pagination information. + * @return the list of entities. + */ + @Transactional(readOnly = true) + public Page search(String query, Pageable pageable) { + log.debug("Request to search for a page of Employees for query {}", query); + return employeeSearchRepository.search(queryStringQuery(query), pageable) + .map(employeeMapper::toDto); + } +} diff --git a/src/main/java/org/zdar/service/JobHistoryService.java b/src/main/java/org/zdar/service/JobHistoryService.java new file mode 100644 index 0000000..202cf03 --- /dev/null +++ b/src/main/java/org/zdar/service/JobHistoryService.java @@ -0,0 +1,56 @@ +package org.zdar.service; + +import org.zdar.service.dto.JobHistoryDTO; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import java.util.Optional; + +/** + * Service Interface for managing {@link org.zdar.domain.JobHistory}. + */ +public interface JobHistoryService { + + /** + * Save a jobHistory. + * + * @param jobHistoryDTO the entity to save. + * @return the persisted entity. + */ + JobHistoryDTO save(JobHistoryDTO jobHistoryDTO); + + /** + * Get all the jobHistories. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + Page findAll(Pageable pageable); + + + /** + * Get the "id" jobHistory. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" jobHistory. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the jobHistory 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/org/zdar/service/JobService.java b/src/main/java/org/zdar/service/JobService.java new file mode 100644 index 0000000..4bd238f --- /dev/null +++ b/src/main/java/org/zdar/service/JobService.java @@ -0,0 +1,116 @@ +package org.zdar.service; + +import org.zdar.domain.Job; +import org.zdar.repository.JobRepository; +import org.zdar.repository.search.JobSearchRepository; +import org.zdar.service.dto.JobDTO; +import org.zdar.service.mapper.JobMapper; +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 Job}. + */ +@Service +@Transactional +public class JobService { + + private final Logger log = LoggerFactory.getLogger(JobService.class); + + private final JobRepository jobRepository; + + private final JobMapper jobMapper; + + private final JobSearchRepository jobSearchRepository; + + public JobService(JobRepository jobRepository, JobMapper jobMapper, JobSearchRepository jobSearchRepository) { + this.jobRepository = jobRepository; + this.jobMapper = jobMapper; + this.jobSearchRepository = jobSearchRepository; + } + + /** + * Save a job. + * + * @param jobDTO the entity to save. + * @return the persisted entity. + */ + public JobDTO save(JobDTO jobDTO) { + log.debug("Request to save Job : {}", jobDTO); + Job job = jobMapper.toEntity(jobDTO); + job = jobRepository.save(job); + JobDTO result = jobMapper.toDto(job); + jobSearchRepository.save(job); + return result; + } + + /** + * Get all the jobs. + * + * @param pageable the pagination information. + * @return the list of entities. + */ + @Transactional(readOnly = true) + public Page findAll(Pageable pageable) { + log.debug("Request to get all Jobs"); + return jobRepository.findAll(pageable) + .map(jobMapper::toDto); + } + + /** + * Get all the jobs with eager load of many-to-many relationships. + * + * @return the list of entities. + */ + public Page findAllWithEagerRelationships(Pageable pageable) { + return jobRepository.findAllWithEagerRelationships(pageable).map(jobMapper::toDto); + } + + + /** + * Get one job by id. + * + * @param id the id of the entity. + * @return the entity. + */ + @Transactional(readOnly = true) + public Optional findOne(Long id) { + log.debug("Request to get Job : {}", id); + return jobRepository.findOneWithEagerRelationships(id) + .map(jobMapper::toDto); + } + + /** + * Delete the job by id. + * + * @param id the id of the entity. + */ + public void delete(Long id) { + log.debug("Request to delete Job : {}", id); + jobRepository.deleteById(id); + jobSearchRepository.deleteById(id); + } + + /** + * Search for the job corresponding to the query. + * + * @param query the query of the search. + * @param pageable the pagination information. + * @return the list of entities. + */ + @Transactional(readOnly = true) + public Page search(String query, Pageable pageable) { + log.debug("Request to search for a page of Jobs for query {}", query); + return jobSearchRepository.search(queryStringQuery(query), pageable) + .map(jobMapper::toDto); + } +} diff --git a/src/main/java/org/zdar/service/LocationService.java b/src/main/java/org/zdar/service/LocationService.java new file mode 100644 index 0000000..68486ea --- /dev/null +++ b/src/main/java/org/zdar/service/LocationService.java @@ -0,0 +1,52 @@ +package org.zdar.service; + +import org.zdar.service.dto.LocationDTO; + +import java.util.List; +import java.util.Optional; + +/** + * Service Interface for managing {@link org.zdar.domain.Location}. + */ +public interface LocationService { + + /** + * Save a location. + * + * @param locationDTO the entity to save. + * @return the persisted entity. + */ + LocationDTO save(LocationDTO locationDTO); + + /** + * Get all the locations. + * + * @return the list of entities. + */ + List findAll(); + + + /** + * Get the "id" location. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" location. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the location corresponding to the query. + * + * @param query the query of the search. + * + * @return the list of entities. + */ + List search(String query); +} diff --git a/src/main/java/org/zdar/service/RegionService.java b/src/main/java/org/zdar/service/RegionService.java new file mode 100644 index 0000000..b6fdcaa --- /dev/null +++ b/src/main/java/org/zdar/service/RegionService.java @@ -0,0 +1,52 @@ +package org.zdar.service; + +import org.zdar.service.dto.RegionDTO; + +import java.util.List; +import java.util.Optional; + +/** + * Service Interface for managing {@link org.zdar.domain.Region}. + */ +public interface RegionService { + + /** + * Save a region. + * + * @param regionDTO the entity to save. + * @return the persisted entity. + */ + RegionDTO save(RegionDTO regionDTO); + + /** + * Get all the regions. + * + * @return the list of entities. + */ + List findAll(); + + + /** + * Get the "id" region. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" region. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the region corresponding to the query. + * + * @param query the query of the search. + * + * @return the list of entities. + */ + List search(String query); +} diff --git a/src/main/java/org/zdar/service/TaskService.java b/src/main/java/org/zdar/service/TaskService.java new file mode 100644 index 0000000..036435f --- /dev/null +++ b/src/main/java/org/zdar/service/TaskService.java @@ -0,0 +1,52 @@ +package org.zdar.service; + +import org.zdar.service.dto.TaskDTO; + +import java.util.List; +import java.util.Optional; + +/** + * Service Interface for managing {@link org.zdar.domain.Task}. + */ +public interface TaskService { + + /** + * Save a task. + * + * @param taskDTO the entity to save. + * @return the persisted entity. + */ + TaskDTO save(TaskDTO taskDTO); + + /** + * Get all the tasks. + * + * @return the list of entities. + */ + List findAll(); + + + /** + * Get the "id" task. + * + * @param id the id of the entity. + * @return the entity. + */ + Optional findOne(Long id); + + /** + * Delete the "id" task. + * + * @param id the id of the entity. + */ + void delete(Long id); + + /** + * Search for the task corresponding to the query. + * + * @param query the query of the search. + * + * @return the list of entities. + */ + List search(String query); +} diff --git a/src/main/java/org/zdar/service/dto/CountryDTO.java b/src/main/java/org/zdar/service/dto/CountryDTO.java new file mode 100644 index 0000000..fb406cf --- /dev/null +++ b/src/main/java/org/zdar/service/dto/CountryDTO.java @@ -0,0 +1,70 @@ +package org.zdar.service.dto; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link org.zdar.domain.Country} entity. + */ +public class CountryDTO implements Serializable { + + private Long id; + + private String countryName; + + + private Long regionId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getCountryName() { + return countryName; + } + + public void setCountryName(String countryName) { + this.countryName = countryName; + } + + public Long getRegionId() { + return regionId; + } + + public void setRegionId(Long regionId) { + this.regionId = regionId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + CountryDTO countryDTO = (CountryDTO) o; + if (countryDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), countryDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "CountryDTO{" + + "id=" + getId() + + ", countryName='" + getCountryName() + "'" + + ", region=" + getRegionId() + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/dto/DepartmentDTO.java b/src/main/java/org/zdar/service/dto/DepartmentDTO.java new file mode 100644 index 0000000..6163f5d --- /dev/null +++ b/src/main/java/org/zdar/service/dto/DepartmentDTO.java @@ -0,0 +1,77 @@ +package org.zdar.service.dto; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link org.zdar.domain.Department} entity. + */ +public class DepartmentDTO implements Serializable { + + private Long id; + + @NotNull + private String departmentName; + + + private Long locationId; + /** + * A relationship + */ + @ApiModelProperty(value = "A relationship") + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDepartmentName() { + return departmentName; + } + + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; + } + + public Long getLocationId() { + return locationId; + } + + public void setLocationId(Long locationId) { + this.locationId = locationId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + DepartmentDTO departmentDTO = (DepartmentDTO) o; + if (departmentDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), departmentDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "DepartmentDTO{" + + "id=" + getId() + + ", departmentName='" + getDepartmentName() + "'" + + ", location=" + getLocationId() + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/dto/EmployeeDTO.java b/src/main/java/org/zdar/service/dto/EmployeeDTO.java new file mode 100644 index 0000000..36921fb --- /dev/null +++ b/src/main/java/org/zdar/service/dto/EmployeeDTO.java @@ -0,0 +1,155 @@ +package org.zdar.service.dto; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.time.Instant; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link org.zdar.domain.Employee} entity. + */ +@ApiModel(description = "The Employee entity.") +public class EmployeeDTO implements Serializable { + + private Long id; + + /** + * The firstname attribute. + */ + @ApiModelProperty(value = "The firstname attribute.") + private String firstName; + + private String lastName; + + private String email; + + private String phoneNumber; + + private Instant hireDate; + + private Long salary; + + private Long commissionPct; + + + private Long departmentId; + + private Long managerId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPhoneNumber() { + return phoneNumber; + } + + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } + + public Instant getHireDate() { + return hireDate; + } + + public void setHireDate(Instant hireDate) { + this.hireDate = hireDate; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } + + public Long getCommissionPct() { + return commissionPct; + } + + public void setCommissionPct(Long commissionPct) { + this.commissionPct = commissionPct; + } + + public Long getDepartmentId() { + return departmentId; + } + + public void setDepartmentId(Long departmentId) { + this.departmentId = departmentId; + } + + public Long getManagerId() { + return managerId; + } + + public void setManagerId(Long employeeId) { + this.managerId = employeeId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + EmployeeDTO employeeDTO = (EmployeeDTO) o; + if (employeeDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), employeeDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "EmployeeDTO{" + + "id=" + getId() + + ", firstName='" + getFirstName() + "'" + + ", lastName='" + getLastName() + "'" + + ", email='" + getEmail() + "'" + + ", phoneNumber='" + getPhoneNumber() + "'" + + ", hireDate='" + getHireDate() + "'" + + ", salary=" + getSalary() + + ", commissionPct=" + getCommissionPct() + + ", department=" + getDepartmentId() + + ", manager=" + getManagerId() + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/dto/JobDTO.java b/src/main/java/org/zdar/service/dto/JobDTO.java new file mode 100644 index 0000000..1ab1927 --- /dev/null +++ b/src/main/java/org/zdar/service/dto/JobDTO.java @@ -0,0 +1,104 @@ +package org.zdar.service.dto; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; +import java.util.Objects; + +/** + * A DTO for the {@link org.zdar.domain.Job} entity. + */ +public class JobDTO implements Serializable { + + private Long id; + + private String jobTitle; + + private Long minSalary; + + private Long maxSalary; + + + private Long employeeId; + + private Set tasks = new HashSet<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getJobTitle() { + return jobTitle; + } + + public void setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + } + + public Long getMinSalary() { + return minSalary; + } + + public void setMinSalary(Long minSalary) { + this.minSalary = minSalary; + } + + public Long getMaxSalary() { + return maxSalary; + } + + public void setMaxSalary(Long maxSalary) { + this.maxSalary = maxSalary; + } + + public Long getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Long employeeId) { + this.employeeId = employeeId; + } + + public Set getTasks() { + return tasks; + } + + public void setTasks(Set tasks) { + this.tasks = tasks; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + JobDTO jobDTO = (JobDTO) o; + if (jobDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), jobDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "JobDTO{" + + "id=" + getId() + + ", jobTitle='" + getJobTitle() + "'" + + ", minSalary=" + getMinSalary() + + ", maxSalary=" + getMaxSalary() + + ", employee=" + getEmployeeId() + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/dto/JobHistoryDTO.java b/src/main/java/org/zdar/service/dto/JobHistoryDTO.java new file mode 100644 index 0000000..689c2f9 --- /dev/null +++ b/src/main/java/org/zdar/service/dto/JobHistoryDTO.java @@ -0,0 +1,116 @@ +package org.zdar.service.dto; +import java.time.Instant; +import java.io.Serializable; +import java.util.Objects; +import org.zdar.domain.enumeration.Language; + +/** + * A DTO for the {@link org.zdar.domain.JobHistory} entity. + */ +public class JobHistoryDTO implements Serializable { + + private Long id; + + private Instant startDate; + + private Instant endDate; + + private Language language; + + + private Long jobId; + + private Long departmentId; + + private Long employeeId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Instant getStartDate() { + return startDate; + } + + public void setStartDate(Instant startDate) { + this.startDate = startDate; + } + + public Instant getEndDate() { + return endDate; + } + + public void setEndDate(Instant endDate) { + this.endDate = endDate; + } + + public Language getLanguage() { + return language; + } + + public void setLanguage(Language language) { + this.language = language; + } + + public Long getJobId() { + return jobId; + } + + public void setJobId(Long jobId) { + this.jobId = jobId; + } + + public Long getDepartmentId() { + return departmentId; + } + + public void setDepartmentId(Long departmentId) { + this.departmentId = departmentId; + } + + public Long getEmployeeId() { + return employeeId; + } + + public void setEmployeeId(Long employeeId) { + this.employeeId = employeeId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + JobHistoryDTO jobHistoryDTO = (JobHistoryDTO) o; + if (jobHistoryDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), jobHistoryDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "JobHistoryDTO{" + + "id=" + getId() + + ", startDate='" + getStartDate() + "'" + + ", endDate='" + getEndDate() + "'" + + ", language='" + getLanguage() + "'" + + ", job=" + getJobId() + + ", department=" + getDepartmentId() + + ", employee=" + getEmployeeId() + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/dto/LocationDTO.java b/src/main/java/org/zdar/service/dto/LocationDTO.java new file mode 100644 index 0000000..1e934c2 --- /dev/null +++ b/src/main/java/org/zdar/service/dto/LocationDTO.java @@ -0,0 +1,105 @@ +package org.zdar.service.dto; +import io.swagger.annotations.ApiModel; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link org.zdar.domain.Location} entity. + */ +@ApiModel(description = "not an ignored comment") +public class LocationDTO implements Serializable { + + private Long id; + + private String streetAddress; + + private String postalCode; + + private String city; + + private String stateProvince; + + + private Long countryId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreetAddress() { + return streetAddress; + } + + public void setStreetAddress(String streetAddress) { + this.streetAddress = streetAddress; + } + + public String getPostalCode() { + return postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getStateProvince() { + return stateProvince; + } + + public void setStateProvince(String stateProvince) { + this.stateProvince = stateProvince; + } + + public Long getCountryId() { + return countryId; + } + + public void setCountryId(Long countryId) { + this.countryId = countryId; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + LocationDTO locationDTO = (LocationDTO) o; + if (locationDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), locationDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "LocationDTO{" + + "id=" + getId() + + ", streetAddress='" + getStreetAddress() + "'" + + ", postalCode='" + getPostalCode() + "'" + + ", city='" + getCity() + "'" + + ", stateProvince='" + getStateProvince() + "'" + + ", country=" + getCountryId() + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/dto/RegionDTO.java b/src/main/java/org/zdar/service/dto/RegionDTO.java new file mode 100644 index 0000000..8197946 --- /dev/null +++ b/src/main/java/org/zdar/service/dto/RegionDTO.java @@ -0,0 +1,59 @@ +package org.zdar.service.dto; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link org.zdar.domain.Region} entity. + */ +public class RegionDTO implements Serializable { + + private Long id; + + private String regionName; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getRegionName() { + return regionName; + } + + public void setRegionName(String regionName) { + this.regionName = regionName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + RegionDTO regionDTO = (RegionDTO) o; + if (regionDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), regionDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "RegionDTO{" + + "id=" + getId() + + ", regionName='" + getRegionName() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/dto/TaskDTO.java b/src/main/java/org/zdar/service/dto/TaskDTO.java new file mode 100644 index 0000000..cc2e5d1 --- /dev/null +++ b/src/main/java/org/zdar/service/dto/TaskDTO.java @@ -0,0 +1,72 @@ +package org.zdar.service.dto; +import io.swagger.annotations.ApiModel; +import java.io.Serializable; +import java.util.Objects; + +/** + * A DTO for the {@link org.zdar.domain.Task} entity. + */ +@ApiModel(description = "Task entity. @author The JHipster team.") +public class TaskDTO implements Serializable { + + private Long id; + + private String title; + + private String description; + + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + TaskDTO taskDTO = (TaskDTO) o; + if (taskDTO.getId() == null || getId() == null) { + return false; + } + return Objects.equals(getId(), taskDTO.getId()); + } + + @Override + public int hashCode() { + return Objects.hashCode(getId()); + } + + @Override + public String toString() { + return "TaskDTO{" + + "id=" + getId() + + ", title='" + getTitle() + "'" + + ", description='" + getDescription() + "'" + + "}"; + } +} diff --git a/src/main/java/org/zdar/service/impl/CountryServiceImpl.java b/src/main/java/org/zdar/service/impl/CountryServiceImpl.java new file mode 100644 index 0000000..8834517 --- /dev/null +++ b/src/main/java/org/zdar/service/impl/CountryServiceImpl.java @@ -0,0 +1,116 @@ +package org.zdar.service.impl; + +import org.zdar.service.CountryService; +import org.zdar.domain.Country; +import org.zdar.repository.CountryRepository; +import org.zdar.repository.search.CountrySearchRepository; +import org.zdar.service.dto.CountryDTO; +import org.zdar.service.mapper.CountryMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link Country}. + */ +@Service +@Transactional +public class CountryServiceImpl implements CountryService { + + private final Logger log = LoggerFactory.getLogger(CountryServiceImpl.class); + + private final CountryRepository countryRepository; + + private final CountryMapper countryMapper; + + private final CountrySearchRepository countrySearchRepository; + + public CountryServiceImpl(CountryRepository countryRepository, CountryMapper countryMapper, CountrySearchRepository countrySearchRepository) { + this.countryRepository = countryRepository; + this.countryMapper = countryMapper; + this.countrySearchRepository = countrySearchRepository; + } + + /** + * Save a country. + * + * @param countryDTO the entity to save. + * @return the persisted entity. + */ + @Override + public CountryDTO save(CountryDTO countryDTO) { + log.debug("Request to save Country : {}", countryDTO); + Country country = countryMapper.toEntity(countryDTO); + country = countryRepository.save(country); + CountryDTO result = countryMapper.toDto(country); + countrySearchRepository.save(country); + return result; + } + + /** + * Get all the countries. + * + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List findAll() { + log.debug("Request to get all Countries"); + return countryRepository.findAll().stream() + .map(countryMapper::toDto) + .collect(Collectors.toCollection(LinkedList::new)); + } + + + /** + * Get one country 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 Country : {}", id); + return countryRepository.findById(id) + .map(countryMapper::toDto); + } + + /** + * Delete the country by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete Country : {}", id); + countryRepository.deleteById(id); + countrySearchRepository.deleteById(id); + } + + /** + * Search for the country corresponding to the query. + * + * @param query the query of the search. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List search(String query) { + log.debug("Request to search Countries for query {}", query); + return StreamSupport + .stream(countrySearchRepository.search(queryStringQuery(query)).spliterator(), false) + .map(countryMapper::toDto) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/org/zdar/service/impl/DepartmentServiceImpl.java b/src/main/java/org/zdar/service/impl/DepartmentServiceImpl.java new file mode 100644 index 0000000..2d3a58a --- /dev/null +++ b/src/main/java/org/zdar/service/impl/DepartmentServiceImpl.java @@ -0,0 +1,116 @@ +package org.zdar.service.impl; + +import org.zdar.service.DepartmentService; +import org.zdar.domain.Department; +import org.zdar.repository.DepartmentRepository; +import org.zdar.repository.search.DepartmentSearchRepository; +import org.zdar.service.dto.DepartmentDTO; +import org.zdar.service.mapper.DepartmentMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link Department}. + */ +@Service +@Transactional +public class DepartmentServiceImpl implements DepartmentService { + + private final Logger log = LoggerFactory.getLogger(DepartmentServiceImpl.class); + + private final DepartmentRepository departmentRepository; + + private final DepartmentMapper departmentMapper; + + private final DepartmentSearchRepository departmentSearchRepository; + + public DepartmentServiceImpl(DepartmentRepository departmentRepository, DepartmentMapper departmentMapper, DepartmentSearchRepository departmentSearchRepository) { + this.departmentRepository = departmentRepository; + this.departmentMapper = departmentMapper; + this.departmentSearchRepository = departmentSearchRepository; + } + + /** + * Save a department. + * + * @param departmentDTO the entity to save. + * @return the persisted entity. + */ + @Override + public DepartmentDTO save(DepartmentDTO departmentDTO) { + log.debug("Request to save Department : {}", departmentDTO); + Department department = departmentMapper.toEntity(departmentDTO); + department = departmentRepository.save(department); + DepartmentDTO result = departmentMapper.toDto(department); + departmentSearchRepository.save(department); + return result; + } + + /** + * Get all the departments. + * + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List findAll() { + log.debug("Request to get all Departments"); + return departmentRepository.findAll().stream() + .map(departmentMapper::toDto) + .collect(Collectors.toCollection(LinkedList::new)); + } + + + /** + * Get one department 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 Department : {}", id); + return departmentRepository.findById(id) + .map(departmentMapper::toDto); + } + + /** + * Delete the department by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete Department : {}", id); + departmentRepository.deleteById(id); + departmentSearchRepository.deleteById(id); + } + + /** + * Search for the department corresponding to the query. + * + * @param query the query of the search. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List search(String query) { + log.debug("Request to search Departments for query {}", query); + return StreamSupport + .stream(departmentSearchRepository.search(queryStringQuery(query)).spliterator(), false) + .map(departmentMapper::toDto) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/org/zdar/service/impl/JobHistoryServiceImpl.java b/src/main/java/org/zdar/service/impl/JobHistoryServiceImpl.java new file mode 100644 index 0000000..3281231 --- /dev/null +++ b/src/main/java/org/zdar/service/impl/JobHistoryServiceImpl.java @@ -0,0 +1,113 @@ +package org.zdar.service.impl; + +import org.zdar.service.JobHistoryService; +import org.zdar.domain.JobHistory; +import org.zdar.repository.JobHistoryRepository; +import org.zdar.repository.search.JobHistorySearchRepository; +import org.zdar.service.dto.JobHistoryDTO; +import org.zdar.service.mapper.JobHistoryMapper; +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 JobHistory}. + */ +@Service +@Transactional +public class JobHistoryServiceImpl implements JobHistoryService { + + private final Logger log = LoggerFactory.getLogger(JobHistoryServiceImpl.class); + + private final JobHistoryRepository jobHistoryRepository; + + private final JobHistoryMapper jobHistoryMapper; + + private final JobHistorySearchRepository jobHistorySearchRepository; + + public JobHistoryServiceImpl(JobHistoryRepository jobHistoryRepository, JobHistoryMapper jobHistoryMapper, JobHistorySearchRepository jobHistorySearchRepository) { + this.jobHistoryRepository = jobHistoryRepository; + this.jobHistoryMapper = jobHistoryMapper; + this.jobHistorySearchRepository = jobHistorySearchRepository; + } + + /** + * Save a jobHistory. + * + * @param jobHistoryDTO the entity to save. + * @return the persisted entity. + */ + @Override + public JobHistoryDTO save(JobHistoryDTO jobHistoryDTO) { + log.debug("Request to save JobHistory : {}", jobHistoryDTO); + JobHistory jobHistory = jobHistoryMapper.toEntity(jobHistoryDTO); + jobHistory = jobHistoryRepository.save(jobHistory); + JobHistoryDTO result = jobHistoryMapper.toDto(jobHistory); + jobHistorySearchRepository.save(jobHistory); + return result; + } + + /** + * Get all the jobHistories. + * + * @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 JobHistories"); + return jobHistoryRepository.findAll(pageable) + .map(jobHistoryMapper::toDto); + } + + + /** + * Get one jobHistory 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 JobHistory : {}", id); + return jobHistoryRepository.findById(id) + .map(jobHistoryMapper::toDto); + } + + /** + * Delete the jobHistory by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete JobHistory : {}", id); + jobHistoryRepository.deleteById(id); + jobHistorySearchRepository.deleteById(id); + } + + /** + * Search for the jobHistory 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 JobHistories for query {}", query); + return jobHistorySearchRepository.search(queryStringQuery(query), pageable) + .map(jobHistoryMapper::toDto); + } +} diff --git a/src/main/java/org/zdar/service/impl/LocationServiceImpl.java b/src/main/java/org/zdar/service/impl/LocationServiceImpl.java new file mode 100644 index 0000000..ff4bcd5 --- /dev/null +++ b/src/main/java/org/zdar/service/impl/LocationServiceImpl.java @@ -0,0 +1,116 @@ +package org.zdar.service.impl; + +import org.zdar.service.LocationService; +import org.zdar.domain.Location; +import org.zdar.repository.LocationRepository; +import org.zdar.repository.search.LocationSearchRepository; +import org.zdar.service.dto.LocationDTO; +import org.zdar.service.mapper.LocationMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link Location}. + */ +@Service +@Transactional +public class LocationServiceImpl implements LocationService { + + private final Logger log = LoggerFactory.getLogger(LocationServiceImpl.class); + + private final LocationRepository locationRepository; + + private final LocationMapper locationMapper; + + private final LocationSearchRepository locationSearchRepository; + + public LocationServiceImpl(LocationRepository locationRepository, LocationMapper locationMapper, LocationSearchRepository locationSearchRepository) { + this.locationRepository = locationRepository; + this.locationMapper = locationMapper; + this.locationSearchRepository = locationSearchRepository; + } + + /** + * Save a location. + * + * @param locationDTO the entity to save. + * @return the persisted entity. + */ + @Override + public LocationDTO save(LocationDTO locationDTO) { + log.debug("Request to save Location : {}", locationDTO); + Location location = locationMapper.toEntity(locationDTO); + location = locationRepository.save(location); + LocationDTO result = locationMapper.toDto(location); + locationSearchRepository.save(location); + return result; + } + + /** + * Get all the locations. + * + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List findAll() { + log.debug("Request to get all Locations"); + return locationRepository.findAll().stream() + .map(locationMapper::toDto) + .collect(Collectors.toCollection(LinkedList::new)); + } + + + /** + * Get one location 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 Location : {}", id); + return locationRepository.findById(id) + .map(locationMapper::toDto); + } + + /** + * Delete the location by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete Location : {}", id); + locationRepository.deleteById(id); + locationSearchRepository.deleteById(id); + } + + /** + * Search for the location corresponding to the query. + * + * @param query the query of the search. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List search(String query) { + log.debug("Request to search Locations for query {}", query); + return StreamSupport + .stream(locationSearchRepository.search(queryStringQuery(query)).spliterator(), false) + .map(locationMapper::toDto) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/org/zdar/service/impl/RegionServiceImpl.java b/src/main/java/org/zdar/service/impl/RegionServiceImpl.java new file mode 100644 index 0000000..c94c638 --- /dev/null +++ b/src/main/java/org/zdar/service/impl/RegionServiceImpl.java @@ -0,0 +1,116 @@ +package org.zdar.service.impl; + +import org.zdar.service.RegionService; +import org.zdar.domain.Region; +import org.zdar.repository.RegionRepository; +import org.zdar.repository.search.RegionSearchRepository; +import org.zdar.service.dto.RegionDTO; +import org.zdar.service.mapper.RegionMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link Region}. + */ +@Service +@Transactional +public class RegionServiceImpl implements RegionService { + + private final Logger log = LoggerFactory.getLogger(RegionServiceImpl.class); + + private final RegionRepository regionRepository; + + private final RegionMapper regionMapper; + + private final RegionSearchRepository regionSearchRepository; + + public RegionServiceImpl(RegionRepository regionRepository, RegionMapper regionMapper, RegionSearchRepository regionSearchRepository) { + this.regionRepository = regionRepository; + this.regionMapper = regionMapper; + this.regionSearchRepository = regionSearchRepository; + } + + /** + * Save a region. + * + * @param regionDTO the entity to save. + * @return the persisted entity. + */ + @Override + public RegionDTO save(RegionDTO regionDTO) { + log.debug("Request to save Region : {}", regionDTO); + Region region = regionMapper.toEntity(regionDTO); + region = regionRepository.save(region); + RegionDTO result = regionMapper.toDto(region); + regionSearchRepository.save(region); + return result; + } + + /** + * Get all the regions. + * + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List findAll() { + log.debug("Request to get all Regions"); + return regionRepository.findAll().stream() + .map(regionMapper::toDto) + .collect(Collectors.toCollection(LinkedList::new)); + } + + + /** + * Get one region 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 Region : {}", id); + return regionRepository.findById(id) + .map(regionMapper::toDto); + } + + /** + * Delete the region by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete Region : {}", id); + regionRepository.deleteById(id); + regionSearchRepository.deleteById(id); + } + + /** + * Search for the region corresponding to the query. + * + * @param query the query of the search. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List search(String query) { + log.debug("Request to search Regions for query {}", query); + return StreamSupport + .stream(regionSearchRepository.search(queryStringQuery(query)).spliterator(), false) + .map(regionMapper::toDto) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/org/zdar/service/impl/TaskServiceImpl.java b/src/main/java/org/zdar/service/impl/TaskServiceImpl.java new file mode 100644 index 0000000..c1d2c3b --- /dev/null +++ b/src/main/java/org/zdar/service/impl/TaskServiceImpl.java @@ -0,0 +1,116 @@ +package org.zdar.service.impl; + +import org.zdar.service.TaskService; +import org.zdar.domain.Task; +import org.zdar.repository.TaskRepository; +import org.zdar.repository.search.TaskSearchRepository; +import org.zdar.service.dto.TaskDTO; +import org.zdar.service.mapper.TaskMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * Service Implementation for managing {@link Task}. + */ +@Service +@Transactional +public class TaskServiceImpl implements TaskService { + + private final Logger log = LoggerFactory.getLogger(TaskServiceImpl.class); + + private final TaskRepository taskRepository; + + private final TaskMapper taskMapper; + + private final TaskSearchRepository taskSearchRepository; + + public TaskServiceImpl(TaskRepository taskRepository, TaskMapper taskMapper, TaskSearchRepository taskSearchRepository) { + this.taskRepository = taskRepository; + this.taskMapper = taskMapper; + this.taskSearchRepository = taskSearchRepository; + } + + /** + * Save a task. + * + * @param taskDTO the entity to save. + * @return the persisted entity. + */ + @Override + public TaskDTO save(TaskDTO taskDTO) { + log.debug("Request to save Task : {}", taskDTO); + Task task = taskMapper.toEntity(taskDTO); + task = taskRepository.save(task); + TaskDTO result = taskMapper.toDto(task); + taskSearchRepository.save(task); + return result; + } + + /** + * Get all the tasks. + * + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List findAll() { + log.debug("Request to get all Tasks"); + return taskRepository.findAll().stream() + .map(taskMapper::toDto) + .collect(Collectors.toCollection(LinkedList::new)); + } + + + /** + * Get one task 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 Task : {}", id); + return taskRepository.findById(id) + .map(taskMapper::toDto); + } + + /** + * Delete the task by id. + * + * @param id the id of the entity. + */ + @Override + public void delete(Long id) { + log.debug("Request to delete Task : {}", id); + taskRepository.deleteById(id); + taskSearchRepository.deleteById(id); + } + + /** + * Search for the task corresponding to the query. + * + * @param query the query of the search. + * @return the list of entities. + */ + @Override + @Transactional(readOnly = true) + public List search(String query) { + log.debug("Request to search Tasks for query {}", query); + return StreamSupport + .stream(taskSearchRepository.search(queryStringQuery(query)).spliterator(), false) + .map(taskMapper::toDto) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/org/zdar/service/mapper/CountryMapper.java b/src/main/java/org/zdar/service/mapper/CountryMapper.java new file mode 100644 index 0000000..6b090e6 --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/CountryMapper.java @@ -0,0 +1,28 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.CountryDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Country} and its DTO {@link CountryDTO}. + */ +@Mapper(componentModel = "spring", uses = {RegionMapper.class}) +public interface CountryMapper extends EntityMapper { + + @Mapping(source = "region.id", target = "regionId") + CountryDTO toDto(Country country); + + @Mapping(source = "regionId", target = "region") + Country toEntity(CountryDTO countryDTO); + + default Country fromId(Long id) { + if (id == null) { + return null; + } + Country country = new Country(); + country.setId(id); + return country; + } +} diff --git a/src/main/java/org/zdar/service/mapper/DepartmentMapper.java b/src/main/java/org/zdar/service/mapper/DepartmentMapper.java new file mode 100644 index 0000000..bc63f5d --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/DepartmentMapper.java @@ -0,0 +1,30 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.DepartmentDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Department} and its DTO {@link DepartmentDTO}. + */ +@Mapper(componentModel = "spring", uses = {LocationMapper.class}) +public interface DepartmentMapper extends EntityMapper { + + @Mapping(source = "location.id", target = "locationId") + DepartmentDTO toDto(Department department); + + @Mapping(source = "locationId", target = "location") + @Mapping(target = "employees", ignore = true) + @Mapping(target = "removeEmployee", ignore = true) + Department toEntity(DepartmentDTO departmentDTO); + + default Department fromId(Long id) { + if (id == null) { + return null; + } + Department department = new Department(); + department.setId(id); + return department; + } +} diff --git a/src/main/java/org/zdar/service/mapper/EmployeeMapper.java b/src/main/java/org/zdar/service/mapper/EmployeeMapper.java new file mode 100644 index 0000000..6128a35 --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/EmployeeMapper.java @@ -0,0 +1,32 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.EmployeeDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Employee} and its DTO {@link EmployeeDTO}. + */ +@Mapper(componentModel = "spring", uses = {DepartmentMapper.class}) +public interface EmployeeMapper extends EntityMapper { + + @Mapping(source = "department.id", target = "departmentId") + @Mapping(source = "manager.id", target = "managerId") + EmployeeDTO toDto(Employee employee); + + @Mapping(source = "departmentId", target = "department") + @Mapping(target = "jobs", ignore = true) + @Mapping(target = "removeJob", ignore = true) + @Mapping(source = "managerId", target = "manager") + Employee toEntity(EmployeeDTO employeeDTO); + + default Employee fromId(Long id) { + if (id == null) { + return null; + } + Employee employee = new Employee(); + employee.setId(id); + return employee; + } +} diff --git a/src/main/java/org/zdar/service/mapper/EntityMapper.java b/src/main/java/org/zdar/service/mapper/EntityMapper.java new file mode 100644 index 0000000..d5c4025 --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/EntityMapper.java @@ -0,0 +1,21 @@ +package org.zdar.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/org/zdar/service/mapper/JobHistoryMapper.java b/src/main/java/org/zdar/service/mapper/JobHistoryMapper.java new file mode 100644 index 0000000..6e92b2d --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/JobHistoryMapper.java @@ -0,0 +1,32 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.JobHistoryDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link JobHistory} and its DTO {@link JobHistoryDTO}. + */ +@Mapper(componentModel = "spring", uses = {JobMapper.class, DepartmentMapper.class, EmployeeMapper.class}) +public interface JobHistoryMapper extends EntityMapper { + + @Mapping(source = "job.id", target = "jobId") + @Mapping(source = "department.id", target = "departmentId") + @Mapping(source = "employee.id", target = "employeeId") + JobHistoryDTO toDto(JobHistory jobHistory); + + @Mapping(source = "jobId", target = "job") + @Mapping(source = "departmentId", target = "department") + @Mapping(source = "employeeId", target = "employee") + JobHistory toEntity(JobHistoryDTO jobHistoryDTO); + + default JobHistory fromId(Long id) { + if (id == null) { + return null; + } + JobHistory jobHistory = new JobHistory(); + jobHistory.setId(id); + return jobHistory; + } +} diff --git a/src/main/java/org/zdar/service/mapper/JobMapper.java b/src/main/java/org/zdar/service/mapper/JobMapper.java new file mode 100644 index 0000000..c96d846 --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/JobMapper.java @@ -0,0 +1,29 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.JobDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Job} and its DTO {@link JobDTO}. + */ +@Mapper(componentModel = "spring", uses = {EmployeeMapper.class, TaskMapper.class}) +public interface JobMapper extends EntityMapper { + + @Mapping(source = "employee.id", target = "employeeId") + JobDTO toDto(Job job); + + @Mapping(source = "employeeId", target = "employee") + @Mapping(target = "removeTask", ignore = true) + Job toEntity(JobDTO jobDTO); + + default Job fromId(Long id) { + if (id == null) { + return null; + } + Job job = new Job(); + job.setId(id); + return job; + } +} diff --git a/src/main/java/org/zdar/service/mapper/LocationMapper.java b/src/main/java/org/zdar/service/mapper/LocationMapper.java new file mode 100644 index 0000000..7eb36e0 --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/LocationMapper.java @@ -0,0 +1,28 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.LocationDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Location} and its DTO {@link LocationDTO}. + */ +@Mapper(componentModel = "spring", uses = {CountryMapper.class}) +public interface LocationMapper extends EntityMapper { + + @Mapping(source = "country.id", target = "countryId") + LocationDTO toDto(Location location); + + @Mapping(source = "countryId", target = "country") + Location toEntity(LocationDTO locationDTO); + + default Location fromId(Long id) { + if (id == null) { + return null; + } + Location location = new Location(); + location.setId(id); + return location; + } +} diff --git a/src/main/java/org/zdar/service/mapper/RegionMapper.java b/src/main/java/org/zdar/service/mapper/RegionMapper.java new file mode 100644 index 0000000..b937431 --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/RegionMapper.java @@ -0,0 +1,24 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.RegionDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Region} and its DTO {@link RegionDTO}. + */ +@Mapper(componentModel = "spring", uses = {}) +public interface RegionMapper extends EntityMapper { + + + + default Region fromId(Long id) { + if (id == null) { + return null; + } + Region region = new Region(); + region.setId(id); + return region; + } +} diff --git a/src/main/java/org/zdar/service/mapper/TaskMapper.java b/src/main/java/org/zdar/service/mapper/TaskMapper.java new file mode 100644 index 0000000..184c014 --- /dev/null +++ b/src/main/java/org/zdar/service/mapper/TaskMapper.java @@ -0,0 +1,27 @@ +package org.zdar.service.mapper; + +import org.zdar.domain.*; +import org.zdar.service.dto.TaskDTO; + +import org.mapstruct.*; + +/** + * Mapper for the entity {@link Task} and its DTO {@link TaskDTO}. + */ +@Mapper(componentModel = "spring", uses = {}) +public interface TaskMapper extends EntityMapper { + + + @Mapping(target = "jobs", ignore = true) + @Mapping(target = "removeJob", ignore = true) + Task toEntity(TaskDTO taskDTO); + + default Task fromId(Long id) { + if (id == null) { + return null; + } + Task task = new Task(); + task.setId(id); + return task; + } +} diff --git a/src/main/java/org/zdar/web/rest/CountryResource.java b/src/main/java/org/zdar/web/rest/CountryResource.java new file mode 100644 index 0000000..60feec6 --- /dev/null +++ b/src/main/java/org/zdar/web/rest/CountryResource.java @@ -0,0 +1,134 @@ +package org.zdar.web.rest; + +import org.zdar.service.CountryService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.CountryDTO; + +import io.github.jhipster.web.util.HeaderUtil; +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.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link org.zdar.domain.Country}. + */ +@RestController +@RequestMapping("/api") +public class CountryResource { + + private final Logger log = LoggerFactory.getLogger(CountryResource.class); + + private static final String ENTITY_NAME = "country"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final CountryService countryService; + + public CountryResource(CountryService countryService) { + this.countryService = countryService; + } + + /** + * {@code POST /countries} : Create a new country. + * + * @param countryDTO the countryDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new countryDTO, or with status {@code 400 (Bad Request)} if the country has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/countries") + public ResponseEntity createCountry(@RequestBody CountryDTO countryDTO) throws URISyntaxException { + log.debug("REST request to save Country : {}", countryDTO); + if (countryDTO.getId() != null) { + throw new BadRequestAlertException("A new country cannot already have an ID", ENTITY_NAME, "idexists"); + } + CountryDTO result = countryService.save(countryDTO); + return ResponseEntity.created(new URI("/api/countries/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /countries} : Updates an existing country. + * + * @param countryDTO the countryDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated countryDTO, + * or with status {@code 400 (Bad Request)} if the countryDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the countryDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/countries") + public ResponseEntity updateCountry(@RequestBody CountryDTO countryDTO) throws URISyntaxException { + log.debug("REST request to update Country : {}", countryDTO); + if (countryDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + CountryDTO result = countryService.save(countryDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, countryDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /countries} : get all the countries. + * + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of countries in body. + */ + @GetMapping("/countries") + public List getAllCountries() { + log.debug("REST request to get all Countries"); + return countryService.findAll(); + } + + /** + * {@code GET /countries/:id} : get the "id" country. + * + * @param id the id of the countryDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the countryDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/countries/{id}") + public ResponseEntity getCountry(@PathVariable Long id) { + log.debug("REST request to get Country : {}", id); + Optional countryDTO = countryService.findOne(id); + return ResponseUtil.wrapOrNotFound(countryDTO); + } + + /** + * {@code DELETE /countries/:id} : delete the "id" country. + * + * @param id the id of the countryDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/countries/{id}") + public ResponseEntity deleteCountry(@PathVariable Long id) { + log.debug("REST request to delete Country : {}", id); + countryService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/countries?query=:query} : search for the country corresponding + * to the query. + * + * @param query the query of the country search. + * @return the result of the search. + */ + @GetMapping("/_search/countries") + public List searchCountries(@RequestParam String query) { + log.debug("REST request to search Countries for query {}", query); + return countryService.search(query); + } + +} diff --git a/src/main/java/org/zdar/web/rest/DepartmentResource.java b/src/main/java/org/zdar/web/rest/DepartmentResource.java new file mode 100644 index 0000000..66e1c01 --- /dev/null +++ b/src/main/java/org/zdar/web/rest/DepartmentResource.java @@ -0,0 +1,135 @@ +package org.zdar.web.rest; + +import org.zdar.service.DepartmentService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.DepartmentDTO; + +import io.github.jhipster.web.util.HeaderUtil; +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.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 org.zdar.domain.Department}. + */ +@RestController +@RequestMapping("/api") +public class DepartmentResource { + + private final Logger log = LoggerFactory.getLogger(DepartmentResource.class); + + private static final String ENTITY_NAME = "department"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final DepartmentService departmentService; + + public DepartmentResource(DepartmentService departmentService) { + this.departmentService = departmentService; + } + + /** + * {@code POST /departments} : Create a new department. + * + * @param departmentDTO the departmentDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new departmentDTO, or with status {@code 400 (Bad Request)} if the department has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/departments") + public ResponseEntity createDepartment(@Valid @RequestBody DepartmentDTO departmentDTO) throws URISyntaxException { + log.debug("REST request to save Department : {}", departmentDTO); + if (departmentDTO.getId() != null) { + throw new BadRequestAlertException("A new department cannot already have an ID", ENTITY_NAME, "idexists"); + } + DepartmentDTO result = departmentService.save(departmentDTO); + return ResponseEntity.created(new URI("/api/departments/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /departments} : Updates an existing department. + * + * @param departmentDTO the departmentDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated departmentDTO, + * or with status {@code 400 (Bad Request)} if the departmentDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the departmentDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/departments") + public ResponseEntity updateDepartment(@Valid @RequestBody DepartmentDTO departmentDTO) throws URISyntaxException { + log.debug("REST request to update Department : {}", departmentDTO); + if (departmentDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + DepartmentDTO result = departmentService.save(departmentDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, departmentDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /departments} : get all the departments. + * + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of departments in body. + */ + @GetMapping("/departments") + public List getAllDepartments() { + log.debug("REST request to get all Departments"); + return departmentService.findAll(); + } + + /** + * {@code GET /departments/:id} : get the "id" department. + * + * @param id the id of the departmentDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the departmentDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/departments/{id}") + public ResponseEntity getDepartment(@PathVariable Long id) { + log.debug("REST request to get Department : {}", id); + Optional departmentDTO = departmentService.findOne(id); + return ResponseUtil.wrapOrNotFound(departmentDTO); + } + + /** + * {@code DELETE /departments/:id} : delete the "id" department. + * + * @param id the id of the departmentDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/departments/{id}") + public ResponseEntity deleteDepartment(@PathVariable Long id) { + log.debug("REST request to delete Department : {}", id); + departmentService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/departments?query=:query} : search for the department corresponding + * to the query. + * + * @param query the query of the department search. + * @return the result of the search. + */ + @GetMapping("/_search/departments") + public List searchDepartments(@RequestParam String query) { + log.debug("REST request to search Departments for query {}", query); + return departmentService.search(query); + } + +} diff --git a/src/main/java/org/zdar/web/rest/EmployeeResource.java b/src/main/java/org/zdar/web/rest/EmployeeResource.java new file mode 100644 index 0000000..05451cb --- /dev/null +++ b/src/main/java/org/zdar/web/rest/EmployeeResource.java @@ -0,0 +1,147 @@ +package org.zdar.web.rest; + +import org.zdar.service.EmployeeService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.EmployeeDTO; + +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.util.MultiValueMap; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link org.zdar.domain.Employee}. + */ +@RestController +@RequestMapping("/api") +public class EmployeeResource { + + private final Logger log = LoggerFactory.getLogger(EmployeeResource.class); + + private static final String ENTITY_NAME = "employee"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final EmployeeService employeeService; + + public EmployeeResource(EmployeeService employeeService) { + this.employeeService = employeeService; + } + + /** + * {@code POST /employees} : Create a new employee. + * + * @param employeeDTO the employeeDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new employeeDTO, or with status {@code 400 (Bad Request)} if the employee has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/employees") + public ResponseEntity createEmployee(@RequestBody EmployeeDTO employeeDTO) throws URISyntaxException { + log.debug("REST request to save Employee : {}", employeeDTO); + if (employeeDTO.getId() != null) { + throw new BadRequestAlertException("A new employee cannot already have an ID", ENTITY_NAME, "idexists"); + } + EmployeeDTO result = employeeService.save(employeeDTO); + return ResponseEntity.created(new URI("/api/employees/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /employees} : Updates an existing employee. + * + * @param employeeDTO the employeeDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated employeeDTO, + * or with status {@code 400 (Bad Request)} if the employeeDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the employeeDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/employees") + public ResponseEntity updateEmployee(@RequestBody EmployeeDTO employeeDTO) throws URISyntaxException { + log.debug("REST request to update Employee : {}", employeeDTO); + if (employeeDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + EmployeeDTO result = employeeService.save(employeeDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, employeeDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /employees} : get all the employees. + * + * @param pageable the pagination information. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of employees in body. + */ + @GetMapping("/employees") + public ResponseEntity> getAllEmployees(Pageable pageable, @RequestParam MultiValueMap queryParams, UriComponentsBuilder uriBuilder) { + log.debug("REST request to get a page of Employees"); + Page page = employeeService.findAll(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * {@code GET /employees/:id} : get the "id" employee. + * + * @param id the id of the employeeDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the employeeDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/employees/{id}") + public ResponseEntity getEmployee(@PathVariable Long id) { + log.debug("REST request to get Employee : {}", id); + Optional employeeDTO = employeeService.findOne(id); + return ResponseUtil.wrapOrNotFound(employeeDTO); + } + + /** + * {@code DELETE /employees/:id} : delete the "id" employee. + * + * @param id the id of the employeeDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/employees/{id}") + public ResponseEntity deleteEmployee(@PathVariable Long id) { + log.debug("REST request to delete Employee : {}", id); + employeeService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/employees?query=:query} : search for the employee corresponding + * to the query. + * + * @param query the query of the employee search. + * @param pageable the pagination information. + * @return the result of the search. + */ + @GetMapping("/_search/employees") + public ResponseEntity> searchEmployees(@RequestParam String query, Pageable pageable, @RequestParam MultiValueMap queryParams, UriComponentsBuilder uriBuilder) { + log.debug("REST request to search for a page of Employees for query {}", query); + Page page = employeeService.search(query, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + +} diff --git a/src/main/java/org/zdar/web/rest/JobHistoryResource.java b/src/main/java/org/zdar/web/rest/JobHistoryResource.java new file mode 100644 index 0000000..ccf7157 --- /dev/null +++ b/src/main/java/org/zdar/web/rest/JobHistoryResource.java @@ -0,0 +1,147 @@ +package org.zdar.web.rest; + +import org.zdar.service.JobHistoryService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.JobHistoryDTO; + +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.util.MultiValueMap; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link org.zdar.domain.JobHistory}. + */ +@RestController +@RequestMapping("/api") +public class JobHistoryResource { + + private final Logger log = LoggerFactory.getLogger(JobHistoryResource.class); + + private static final String ENTITY_NAME = "jobHistory"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final JobHistoryService jobHistoryService; + + public JobHistoryResource(JobHistoryService jobHistoryService) { + this.jobHistoryService = jobHistoryService; + } + + /** + * {@code POST /job-histories} : Create a new jobHistory. + * + * @param jobHistoryDTO the jobHistoryDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new jobHistoryDTO, or with status {@code 400 (Bad Request)} if the jobHistory has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/job-histories") + public ResponseEntity createJobHistory(@RequestBody JobHistoryDTO jobHistoryDTO) throws URISyntaxException { + log.debug("REST request to save JobHistory : {}", jobHistoryDTO); + if (jobHistoryDTO.getId() != null) { + throw new BadRequestAlertException("A new jobHistory cannot already have an ID", ENTITY_NAME, "idexists"); + } + JobHistoryDTO result = jobHistoryService.save(jobHistoryDTO); + return ResponseEntity.created(new URI("/api/job-histories/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /job-histories} : Updates an existing jobHistory. + * + * @param jobHistoryDTO the jobHistoryDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated jobHistoryDTO, + * or with status {@code 400 (Bad Request)} if the jobHistoryDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the jobHistoryDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/job-histories") + public ResponseEntity updateJobHistory(@RequestBody JobHistoryDTO jobHistoryDTO) throws URISyntaxException { + log.debug("REST request to update JobHistory : {}", jobHistoryDTO); + if (jobHistoryDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + JobHistoryDTO result = jobHistoryService.save(jobHistoryDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, jobHistoryDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /job-histories} : get all the jobHistories. + * + * @param pageable the pagination information. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of jobHistories in body. + */ + @GetMapping("/job-histories") + public ResponseEntity> getAllJobHistories(Pageable pageable, @RequestParam MultiValueMap queryParams, UriComponentsBuilder uriBuilder) { + log.debug("REST request to get a page of JobHistories"); + Page page = jobHistoryService.findAll(pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * {@code GET /job-histories/:id} : get the "id" jobHistory. + * + * @param id the id of the jobHistoryDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the jobHistoryDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/job-histories/{id}") + public ResponseEntity getJobHistory(@PathVariable Long id) { + log.debug("REST request to get JobHistory : {}", id); + Optional jobHistoryDTO = jobHistoryService.findOne(id); + return ResponseUtil.wrapOrNotFound(jobHistoryDTO); + } + + /** + * {@code DELETE /job-histories/:id} : delete the "id" jobHistory. + * + * @param id the id of the jobHistoryDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/job-histories/{id}") + public ResponseEntity deleteJobHistory(@PathVariable Long id) { + log.debug("REST request to delete JobHistory : {}", id); + jobHistoryService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/job-histories?query=:query} : search for the jobHistory corresponding + * to the query. + * + * @param query the query of the jobHistory search. + * @param pageable the pagination information. + * @return the result of the search. + */ + @GetMapping("/_search/job-histories") + public ResponseEntity> searchJobHistories(@RequestParam String query, Pageable pageable, @RequestParam MultiValueMap queryParams, UriComponentsBuilder uriBuilder) { + log.debug("REST request to search for a page of JobHistories for query {}", query); + Page page = jobHistoryService.search(query, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + +} diff --git a/src/main/java/org/zdar/web/rest/JobResource.java b/src/main/java/org/zdar/web/rest/JobResource.java new file mode 100644 index 0000000..488f498 --- /dev/null +++ b/src/main/java/org/zdar/web/rest/JobResource.java @@ -0,0 +1,153 @@ +package org.zdar.web.rest; + +import org.zdar.service.JobService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.JobDTO; + +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.util.MultiValueMap; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link org.zdar.domain.Job}. + */ +@RestController +@RequestMapping("/api") +public class JobResource { + + private final Logger log = LoggerFactory.getLogger(JobResource.class); + + private static final String ENTITY_NAME = "job"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final JobService jobService; + + public JobResource(JobService jobService) { + this.jobService = jobService; + } + + /** + * {@code POST /jobs} : Create a new job. + * + * @param jobDTO the jobDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new jobDTO, or with status {@code 400 (Bad Request)} if the job has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/jobs") + public ResponseEntity createJob(@RequestBody JobDTO jobDTO) throws URISyntaxException { + log.debug("REST request to save Job : {}", jobDTO); + if (jobDTO.getId() != null) { + throw new BadRequestAlertException("A new job cannot already have an ID", ENTITY_NAME, "idexists"); + } + JobDTO result = jobService.save(jobDTO); + return ResponseEntity.created(new URI("/api/jobs/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /jobs} : Updates an existing job. + * + * @param jobDTO the jobDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated jobDTO, + * or with status {@code 400 (Bad Request)} if the jobDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the jobDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/jobs") + public ResponseEntity updateJob(@RequestBody JobDTO jobDTO) throws URISyntaxException { + log.debug("REST request to update Job : {}", jobDTO); + if (jobDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + JobDTO result = jobService.save(jobDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, jobDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /jobs} : get all the jobs. + * + * @param pageable the pagination information. + * @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many). + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of jobs in body. + */ + @GetMapping("/jobs") + public ResponseEntity> getAllJobs(Pageable pageable, @RequestParam MultiValueMap queryParams, UriComponentsBuilder uriBuilder, @RequestParam(required = false, defaultValue = "false") boolean eagerload) { + log.debug("REST request to get a page of Jobs"); + Page page; + if (eagerload) { + page = jobService.findAllWithEagerRelationships(pageable); + } else { + page = jobService.findAll(pageable); + } + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + + /** + * {@code GET /jobs/:id} : get the "id" job. + * + * @param id the id of the jobDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the jobDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/jobs/{id}") + public ResponseEntity getJob(@PathVariable Long id) { + log.debug("REST request to get Job : {}", id); + Optional jobDTO = jobService.findOne(id); + return ResponseUtil.wrapOrNotFound(jobDTO); + } + + /** + * {@code DELETE /jobs/:id} : delete the "id" job. + * + * @param id the id of the jobDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/jobs/{id}") + public ResponseEntity deleteJob(@PathVariable Long id) { + log.debug("REST request to delete Job : {}", id); + jobService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/jobs?query=:query} : search for the job corresponding + * to the query. + * + * @param query the query of the job search. + * @param pageable the pagination information. + * @return the result of the search. + */ + @GetMapping("/_search/jobs") + public ResponseEntity> searchJobs(@RequestParam String query, Pageable pageable, @RequestParam MultiValueMap queryParams, UriComponentsBuilder uriBuilder) { + log.debug("REST request to search for a page of Jobs for query {}", query); + Page page = jobService.search(query, pageable); + HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page); + return ResponseEntity.ok().headers(headers).body(page.getContent()); + } + +} diff --git a/src/main/java/org/zdar/web/rest/LocationResource.java b/src/main/java/org/zdar/web/rest/LocationResource.java new file mode 100644 index 0000000..39d7bef --- /dev/null +++ b/src/main/java/org/zdar/web/rest/LocationResource.java @@ -0,0 +1,134 @@ +package org.zdar.web.rest; + +import org.zdar.service.LocationService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.LocationDTO; + +import io.github.jhipster.web.util.HeaderUtil; +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.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link org.zdar.domain.Location}. + */ +@RestController +@RequestMapping("/api") +public class LocationResource { + + private final Logger log = LoggerFactory.getLogger(LocationResource.class); + + private static final String ENTITY_NAME = "location"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final LocationService locationService; + + public LocationResource(LocationService locationService) { + this.locationService = locationService; + } + + /** + * {@code POST /locations} : Create a new location. + * + * @param locationDTO the locationDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new locationDTO, or with status {@code 400 (Bad Request)} if the location has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/locations") + public ResponseEntity createLocation(@RequestBody LocationDTO locationDTO) throws URISyntaxException { + log.debug("REST request to save Location : {}", locationDTO); + if (locationDTO.getId() != null) { + throw new BadRequestAlertException("A new location cannot already have an ID", ENTITY_NAME, "idexists"); + } + LocationDTO result = locationService.save(locationDTO); + return ResponseEntity.created(new URI("/api/locations/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /locations} : Updates an existing location. + * + * @param locationDTO the locationDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated locationDTO, + * or with status {@code 400 (Bad Request)} if the locationDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the locationDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/locations") + public ResponseEntity updateLocation(@RequestBody LocationDTO locationDTO) throws URISyntaxException { + log.debug("REST request to update Location : {}", locationDTO); + if (locationDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + LocationDTO result = locationService.save(locationDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, locationDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /locations} : get all the locations. + * + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of locations in body. + */ + @GetMapping("/locations") + public List getAllLocations() { + log.debug("REST request to get all Locations"); + return locationService.findAll(); + } + + /** + * {@code GET /locations/:id} : get the "id" location. + * + * @param id the id of the locationDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the locationDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/locations/{id}") + public ResponseEntity getLocation(@PathVariable Long id) { + log.debug("REST request to get Location : {}", id); + Optional locationDTO = locationService.findOne(id); + return ResponseUtil.wrapOrNotFound(locationDTO); + } + + /** + * {@code DELETE /locations/:id} : delete the "id" location. + * + * @param id the id of the locationDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/locations/{id}") + public ResponseEntity deleteLocation(@PathVariable Long id) { + log.debug("REST request to delete Location : {}", id); + locationService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/locations?query=:query} : search for the location corresponding + * to the query. + * + * @param query the query of the location search. + * @return the result of the search. + */ + @GetMapping("/_search/locations") + public List searchLocations(@RequestParam String query) { + log.debug("REST request to search Locations for query {}", query); + return locationService.search(query); + } + +} diff --git a/src/main/java/org/zdar/web/rest/RegionResource.java b/src/main/java/org/zdar/web/rest/RegionResource.java new file mode 100644 index 0000000..fe2ae1b --- /dev/null +++ b/src/main/java/org/zdar/web/rest/RegionResource.java @@ -0,0 +1,134 @@ +package org.zdar.web.rest; + +import org.zdar.service.RegionService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.RegionDTO; + +import io.github.jhipster.web.util.HeaderUtil; +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.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link org.zdar.domain.Region}. + */ +@RestController +@RequestMapping("/api") +public class RegionResource { + + private final Logger log = LoggerFactory.getLogger(RegionResource.class); + + private static final String ENTITY_NAME = "region"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final RegionService regionService; + + public RegionResource(RegionService regionService) { + this.regionService = regionService; + } + + /** + * {@code POST /regions} : Create a new region. + * + * @param regionDTO the regionDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new regionDTO, or with status {@code 400 (Bad Request)} if the region has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/regions") + public ResponseEntity createRegion(@RequestBody RegionDTO regionDTO) throws URISyntaxException { + log.debug("REST request to save Region : {}", regionDTO); + if (regionDTO.getId() != null) { + throw new BadRequestAlertException("A new region cannot already have an ID", ENTITY_NAME, "idexists"); + } + RegionDTO result = regionService.save(regionDTO); + return ResponseEntity.created(new URI("/api/regions/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /regions} : Updates an existing region. + * + * @param regionDTO the regionDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated regionDTO, + * or with status {@code 400 (Bad Request)} if the regionDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the regionDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/regions") + public ResponseEntity updateRegion(@RequestBody RegionDTO regionDTO) throws URISyntaxException { + log.debug("REST request to update Region : {}", regionDTO); + if (regionDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + RegionDTO result = regionService.save(regionDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, regionDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /regions} : get all the regions. + * + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of regions in body. + */ + @GetMapping("/regions") + public List getAllRegions() { + log.debug("REST request to get all Regions"); + return regionService.findAll(); + } + + /** + * {@code GET /regions/:id} : get the "id" region. + * + * @param id the id of the regionDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the regionDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/regions/{id}") + public ResponseEntity getRegion(@PathVariable Long id) { + log.debug("REST request to get Region : {}", id); + Optional regionDTO = regionService.findOne(id); + return ResponseUtil.wrapOrNotFound(regionDTO); + } + + /** + * {@code DELETE /regions/:id} : delete the "id" region. + * + * @param id the id of the regionDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/regions/{id}") + public ResponseEntity deleteRegion(@PathVariable Long id) { + log.debug("REST request to delete Region : {}", id); + regionService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/regions?query=:query} : search for the region corresponding + * to the query. + * + * @param query the query of the region search. + * @return the result of the search. + */ + @GetMapping("/_search/regions") + public List searchRegions(@RequestParam String query) { + log.debug("REST request to search Regions for query {}", query); + return regionService.search(query); + } + +} diff --git a/src/main/java/org/zdar/web/rest/TaskResource.java b/src/main/java/org/zdar/web/rest/TaskResource.java new file mode 100644 index 0000000..146f54a --- /dev/null +++ b/src/main/java/org/zdar/web/rest/TaskResource.java @@ -0,0 +1,134 @@ +package org.zdar.web.rest; + +import org.zdar.service.TaskService; +import org.zdar.web.rest.errors.BadRequestAlertException; +import org.zdar.service.dto.TaskDTO; + +import io.github.jhipster.web.util.HeaderUtil; +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.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.net.URISyntaxException; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import static org.elasticsearch.index.query.QueryBuilders.*; + +/** + * REST controller for managing {@link org.zdar.domain.Task}. + */ +@RestController +@RequestMapping("/api") +public class TaskResource { + + private final Logger log = LoggerFactory.getLogger(TaskResource.class); + + private static final String ENTITY_NAME = "task"; + + @Value("${jhipster.clientApp.name}") + private String applicationName; + + private final TaskService taskService; + + public TaskResource(TaskService taskService) { + this.taskService = taskService; + } + + /** + * {@code POST /tasks} : Create a new task. + * + * @param taskDTO the taskDTO to create. + * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new taskDTO, or with status {@code 400 (Bad Request)} if the task has already an ID. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PostMapping("/tasks") + public ResponseEntity createTask(@RequestBody TaskDTO taskDTO) throws URISyntaxException { + log.debug("REST request to save Task : {}", taskDTO); + if (taskDTO.getId() != null) { + throw new BadRequestAlertException("A new task cannot already have an ID", ENTITY_NAME, "idexists"); + } + TaskDTO result = taskService.save(taskDTO); + return ResponseEntity.created(new URI("/api/tasks/" + result.getId())) + .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) + .body(result); + } + + /** + * {@code PUT /tasks} : Updates an existing task. + * + * @param taskDTO the taskDTO to update. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated taskDTO, + * or with status {@code 400 (Bad Request)} if the taskDTO is not valid, + * or with status {@code 500 (Internal Server Error)} if the taskDTO couldn't be updated. + * @throws URISyntaxException if the Location URI syntax is incorrect. + */ + @PutMapping("/tasks") + public ResponseEntity updateTask(@RequestBody TaskDTO taskDTO) throws URISyntaxException { + log.debug("REST request to update Task : {}", taskDTO); + if (taskDTO.getId() == null) { + throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); + } + TaskDTO result = taskService.save(taskDTO); + return ResponseEntity.ok() + .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, taskDTO.getId().toString())) + .body(result); + } + + /** + * {@code GET /tasks} : get all the tasks. + * + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of tasks in body. + */ + @GetMapping("/tasks") + public List getAllTasks() { + log.debug("REST request to get all Tasks"); + return taskService.findAll(); + } + + /** + * {@code GET /tasks/:id} : get the "id" task. + * + * @param id the id of the taskDTO to retrieve. + * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the taskDTO, or with status {@code 404 (Not Found)}. + */ + @GetMapping("/tasks/{id}") + public ResponseEntity getTask(@PathVariable Long id) { + log.debug("REST request to get Task : {}", id); + Optional taskDTO = taskService.findOne(id); + return ResponseUtil.wrapOrNotFound(taskDTO); + } + + /** + * {@code DELETE /tasks/:id} : delete the "id" task. + * + * @param id the id of the taskDTO to delete. + * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. + */ + @DeleteMapping("/tasks/{id}") + public ResponseEntity deleteTask(@PathVariable Long id) { + log.debug("REST request to delete Task : {}", id); + taskService.delete(id); + return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + } + + /** + * {@code SEARCH /_search/tasks?query=:query} : search for the task corresponding + * to the query. + * + * @param query the query of the task search. + * @return the result of the search. + */ + @GetMapping("/_search/tasks") + public List searchTasks(@RequestParam String query) { + log.debug("REST request to search Tasks for query {}", query); + return taskService.search(query); + } + +} diff --git a/src/main/resources/config/liquibase/changelog/20190619192229_added_entity_Region.xml b/src/main/resources/config/liquibase/changelog/20190619192229_added_entity_Region.xml new file mode 100644 index 0000000..3dbd301 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192229_added_entity_Region.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192230_added_entity_Country.xml b/src/main/resources/config/liquibase/changelog/20190619192230_added_entity_Country.xml new file mode 100644 index 0000000..dd38337 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192230_added_entity_Country.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192230_added_entity_constraints_Country.xml b/src/main/resources/config/liquibase/changelog/20190619192230_added_entity_constraints_Country.xml new file mode 100644 index 0000000..a576cf5 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192230_added_entity_constraints_Country.xml @@ -0,0 +1,18 @@ + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192231_added_entity_Location.xml b/src/main/resources/config/liquibase/changelog/20190619192231_added_entity_Location.xml new file mode 100644 index 0000000..edcfbf3 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192231_added_entity_Location.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192231_added_entity_constraints_Location.xml b/src/main/resources/config/liquibase/changelog/20190619192231_added_entity_constraints_Location.xml new file mode 100644 index 0000000..f3ee3a4 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192231_added_entity_constraints_Location.xml @@ -0,0 +1,18 @@ + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192232_added_entity_Department.xml b/src/main/resources/config/liquibase/changelog/20190619192232_added_entity_Department.xml new file mode 100644 index 0000000..fd8ca19 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192232_added_entity_Department.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192232_added_entity_constraints_Department.xml b/src/main/resources/config/liquibase/changelog/20190619192232_added_entity_constraints_Department.xml new file mode 100644 index 0000000..023b7ad --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192232_added_entity_constraints_Department.xml @@ -0,0 +1,18 @@ + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192233_added_entity_Task.xml b/src/main/resources/config/liquibase/changelog/20190619192233_added_entity_Task.xml new file mode 100644 index 0000000..52e8acc --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192233_added_entity_Task.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192234_added_entity_Employee.xml b/src/main/resources/config/liquibase/changelog/20190619192234_added_entity_Employee.xml new file mode 100644 index 0000000..5e87275 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192234_added_entity_Employee.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192234_added_entity_constraints_Employee.xml b/src/main/resources/config/liquibase/changelog/20190619192234_added_entity_constraints_Employee.xml new file mode 100644 index 0000000..c1ef53f --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192234_added_entity_constraints_Employee.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192235_added_entity_Job.xml b/src/main/resources/config/liquibase/changelog/20190619192235_added_entity_Job.xml new file mode 100644 index 0000000..3f7a2ad --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192235_added_entity_Job.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192235_added_entity_constraints_Job.xml b/src/main/resources/config/liquibase/changelog/20190619192235_added_entity_constraints_Job.xml new file mode 100644 index 0000000..e5dc86f --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192235_added_entity_constraints_Job.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192236_added_entity_JobHistory.xml b/src/main/resources/config/liquibase/changelog/20190619192236_added_entity_JobHistory.xml new file mode 100644 index 0000000..0d4ba81 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192236_added_entity_JobHistory.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/changelog/20190619192236_added_entity_constraints_JobHistory.xml b/src/main/resources/config/liquibase/changelog/20190619192236_added_entity_constraints_JobHistory.xml new file mode 100644 index 0000000..e4d0511 --- /dev/null +++ b/src/main/resources/config/liquibase/changelog/20190619192236_added_entity_constraints_JobHistory.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + diff --git a/src/main/resources/config/liquibase/data/country.csv b/src/main/resources/config/liquibase/data/country.csv new file mode 100644 index 0000000..2ac8c2b --- /dev/null +++ b/src/main/resources/config/liquibase/data/country.csv @@ -0,0 +1,11 @@ +id;country_name +1;Multi-channelled Licensed +2;grey Cambridgeshire +3;Canyon HDD +4;Table Small Frozen Sausages Planner +5;envisioneer Music Public-key +6;infomediaries +7;Investment Account +8;Games Regional Digitized +9;copy convergence +10;Mayotte diff --git a/src/main/resources/config/liquibase/data/department.csv b/src/main/resources/config/liquibase/data/department.csv new file mode 100644 index 0000000..396b839 --- /dev/null +++ b/src/main/resources/config/liquibase/data/department.csv @@ -0,0 +1,11 @@ +id;department_name +1;Exclusive Moroccan Dirham card +2;zero tolerance +3;mission-critical +4;Berkshire Small Plastic Pants Investor +5;Canadian Dollar +6;Berkshire Designer +7;Credit Card Account +8;navigate +9;Re-contextualized +10;web-enabled invoice withdrawal diff --git a/src/main/resources/config/liquibase/data/employee.csv b/src/main/resources/config/liquibase/data/employee.csv new file mode 100644 index 0000000..34eaa92 --- /dev/null +++ b/src/main/resources/config/liquibase/data/employee.csv @@ -0,0 +1,11 @@ +id;first_name;last_name;email;phone_number;hire_date;salary;commission_pct +1;Eric;Daugherty;Frederick_OConnell72@hotmail.com;local area network Benin;2019-06-19T07:09:49;36771;63633 +2;Dimitri;Friesen;Lamar.Wiza48@gmail.com;Investor users dot-com;2019-06-19T03:53:34;57690;66892 +3;Jeramie;Stracke;Daren.Reichert@gmail.com;Shoes deposit;2019-06-19T15:07:28;99455;94045 +4;Janet;Wilkinson;Tavares_Tillman@gmail.com;Factors;2019-06-19T11:26:14;42818;55276 +5;Vita;Marquardt;Wilhelmine29@hotmail.com;reinvent;2019-06-18T22:56:53;26847;31692 +6;Jazmyne;Dach;Kaylie_Huels69@yahoo.com;Arkansas Intelligent Credit Card Account;2019-06-18T19:36:51;35864;14008 +7;Deonte;Larson;Serenity_Hammes69@gmail.com;Sudanese Pound;2019-06-19T10:44:51;55281;29359 +8;Elenora;Schowalter;Ramiro_Gaylord91@yahoo.com;Avon;2019-06-19T07:20:20;62789;79829 +9;Clemmie;O'Conner;Maybelle.Hyatt89@gmail.com;value-added incubate Practical;2019-06-19T05:29:48;67202;3594 +10;Erling;Kohler;Karen83@gmail.com;TCP Assimilated;2019-06-19T18:26:35;82260;30326 diff --git a/src/main/resources/config/liquibase/data/job.csv b/src/main/resources/config/liquibase/data/job.csv new file mode 100644 index 0000000..689c964 --- /dev/null +++ b/src/main/resources/config/liquibase/data/job.csv @@ -0,0 +1,11 @@ +id;job_title;min_salary;max_salary +1;National Operations Liaison;32665;52224 +2;Internal Accounts Engineer;21582;96525 +3;Investor Division Executive;84202;5168 +4;Dynamic Operations Administrator;54063;69951 +5;Dynamic Marketing Producer;13274;97585 +6;Principal Operations Developer;32295;4106 +7;Forward Markets Engineer;43352;43897 +8;Legacy Brand Engineer;2535;18433 +9;Principal Brand Assistant;42831;69597 +10;International Group Associate;17329;91521 diff --git a/src/main/resources/config/liquibase/data/job_history.csv b/src/main/resources/config/liquibase/data/job_history.csv new file mode 100644 index 0000000..bd5398a --- /dev/null +++ b/src/main/resources/config/liquibase/data/job_history.csv @@ -0,0 +1,11 @@ +id;start_date;end_date;language +1;2019-06-19T15:37:15;2019-06-19T08:45:32;ENGLISH +2;2019-06-19T17:07:20;2019-06-19T02:13:30;FRENCH +3;2019-06-19T12:39:25;2019-06-19T04:03:25;SPANISH +4;2019-06-19T01:51:16;2019-06-19T09:18:18;ENGLISH +5;2019-06-19T10:49:55;2019-06-19T15:34:04;SPANISH +6;2019-06-19T17:06:56;2019-06-19T18:23:52;FRENCH +7;2019-06-19T02:29:15;2019-06-19T15:10:02;FRENCH +8;2019-06-19T00:00:34;2019-06-19T08:00:43;SPANISH +9;2019-06-19T09:48:40;2019-06-19T18:13:18;SPANISH +10;2019-06-19T13:06:50;2019-06-19T10:23:04;ENGLISH diff --git a/src/main/resources/config/liquibase/data/location.csv b/src/main/resources/config/liquibase/data/location.csv new file mode 100644 index 0000000..64e162b --- /dev/null +++ b/src/main/resources/config/liquibase/data/location.csv @@ -0,0 +1,11 @@ +id;street_address;postal_code;city;state_province +1;Industrial;connect Markets Chief;Monaside;Awesome +2;Aruba;software scale interactive;McGlynnborough;mission-critical Faroe Islands Plastic +3;Car Industrial deliverables;orange Books;Dooleychester;application quantify Unbranded Plastic Tuna +4;Internal;Investment Account archive Fantastic Plastic Chicken;New Monte;withdrawal COM +5;embrace Developer;synthesize Idaho compress;North Joyce;partnerships Grocery Intelligent +6;Dynamic;knowledge base Buckinghamshire;Connellyberg;relationships override +7;Brand;neutral Salad;Muellerfort;deposit +8;Squares mint green e-business;Ghana back-end National;Port Bernice;Profit-focused +9;Jewelery cutting-edge;Games;Kadenbury;magenta Concrete +10;User-centric Gloves;Mauritania;Guidoborough;Engineer diff --git a/src/main/resources/config/liquibase/data/region.csv b/src/main/resources/config/liquibase/data/region.csv new file mode 100644 index 0000000..b89a904 --- /dev/null +++ b/src/main/resources/config/liquibase/data/region.csv @@ -0,0 +1,11 @@ +id;region_name +1;mobile Fish +2;Home Loan Account Table Computer +3;Trace +4;Savings Account alarm +5;Tasty Metal Bacon +6;red Chips Soap +7;Home Loan Account +8;web-readiness +9;Namibia +10;Steel zero administration diff --git a/src/main/resources/config/liquibase/data/task.csv b/src/main/resources/config/liquibase/data/task.csv new file mode 100644 index 0000000..2e4617b --- /dev/null +++ b/src/main/resources/config/liquibase/data/task.csv @@ -0,0 +1,11 @@ +id;title;description +1;bypassing optical;installation +2;Argentine Peso;Kentucky Algerian Dinar Clothing +3;open-source turn-key;Sausages +4;disintermediate Cambridgeshire hacking;bricks-and-clicks Concrete Global +5;Fiji Dollar Profound Bacon;Macao Equatorial Guinea Vision-oriented +6;Agent;Human deposit +7;even-keeled Saint Helena Pound;Internal AI optical +8;bypassing Marketing;Dynamic Home Loan Account Tools +9;Branding;Home Gloves Latvia +10;Ports Manager Fish;Networked diff --git a/src/main/resources/config/liquibase/master.xml b/src/main/resources/config/liquibase/master.xml index 12f6453..f5e1dae 100644 --- a/src/main/resources/config/liquibase/master.xml +++ b/src/main/resources/config/liquibase/master.xml @@ -14,6 +14,20 @@ + + + + + + + + + + + + + + diff --git a/src/main/webapp/app/entities/country/country-delete-dialog.component.html b/src/main/webapp/app/entities/country/country-delete-dialog.component.html new file mode 100644 index 0000000..fe30d4a --- /dev/null +++ b/src/main/webapp/app/entities/country/country-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/country/country-delete-dialog.component.ts b/src/main/webapp/app/entities/country/country-delete-dialog.component.ts new file mode 100644 index 0000000..0a2915d --- /dev/null +++ b/src/main/webapp/app/entities/country/country-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 { ICountry } from 'app/shared/model/country.model'; +import { CountryService } from './country.service'; + +@Component({ + selector: 'jhi-country-delete-dialog', + templateUrl: './country-delete-dialog.component.html' +}) +export class CountryDeleteDialogComponent { + country: ICountry; + + constructor(protected countryService: CountryService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.countryService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'countryListModification', + content: 'Deleted an country' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-country-delete-popup', + template: '' +}) +export class CountryDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ country }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(CountryDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.country = country; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/country', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/country', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/country/country-detail.component.html b/src/main/webapp/app/entities/country/country-detail.component.html new file mode 100644 index 0000000..ca11477 --- /dev/null +++ b/src/main/webapp/app/entities/country/country-detail.component.html @@ -0,0 +1,33 @@ +
+
+
+

Country {{country.id}}

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

Create or edit a Country

+
+ +
+ + +
+
+ + +
+ +
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/country/country-update.component.ts b/src/main/webapp/app/entities/country/country-update.component.ts new file mode 100644 index 0000000..6e1da08 --- /dev/null +++ b/src/main/webapp/app/entities/country/country-update.component.ts @@ -0,0 +1,119 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiAlertService } from 'ng-jhipster'; +import { ICountry, Country } from 'app/shared/model/country.model'; +import { CountryService } from './country.service'; +import { IRegion } from 'app/shared/model/region.model'; +import { RegionService } from 'app/entities/region'; + +@Component({ + selector: 'jhi-country-update', + templateUrl: './country-update.component.html' +}) +export class CountryUpdateComponent implements OnInit { + isSaving: boolean; + + regions: IRegion[]; + + editForm = this.fb.group({ + id: [], + countryName: [], + regionId: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected countryService: CountryService, + protected regionService: RegionService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ country }) => { + this.updateForm(country); + }); + this.regionService + .query({ filter: 'country-is-null' }) + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe( + (res: IRegion[]) => { + if (!!this.editForm.get('regionId').value) { + this.regions = res; + } else { + this.regionService + .find(this.editForm.get('regionId').value) + .pipe( + filter((subResMayBeOk: HttpResponse) => subResMayBeOk.ok), + map((subResponse: HttpResponse) => subResponse.body) + ) + .subscribe( + (subRes: IRegion) => (this.regions = [subRes].concat(res)), + (subRes: HttpErrorResponse) => this.onError(subRes.message) + ); + } + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + updateForm(country: ICountry) { + this.editForm.patchValue({ + id: country.id, + countryName: country.countryName, + regionId: country.regionId + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const country = this.createFromForm(); + if (country.id !== undefined) { + this.subscribeToSaveResponse(this.countryService.update(country)); + } else { + this.subscribeToSaveResponse(this.countryService.create(country)); + } + } + + private createFromForm(): ICountry { + const entity = { + ...new Country(), + id: this.editForm.get(['id']).value, + countryName: this.editForm.get(['countryName']).value, + regionId: this.editForm.get(['regionId']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackRegionById(index: number, item: IRegion) { + return item.id; + } +} diff --git a/src/main/webapp/app/entities/country/country.component.html b/src/main/webapp/app/entities/country/country.component.html new file mode 100644 index 0000000..3b4883d --- /dev/null +++ b/src/main/webapp/app/entities/country/country.component.html @@ -0,0 +1,78 @@ +
+

+ Countries + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No countries found +
+
+ + + + + + + + + + + + + + + + + +
IDCountry NameRegion
{{country.id}}{{country.countryName}} + + +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/country/country.component.ts b/src/main/webapp/app/entities/country/country.component.ts new file mode 100644 index 0000000..08ded28 --- /dev/null +++ b/src/main/webapp/app/entities/country/country.component.ts @@ -0,0 +1,97 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; + +import { ICountry } from 'app/shared/model/country.model'; +import { AccountService } from 'app/core'; +import { CountryService } from './country.service'; + +@Component({ + selector: 'jhi-country', + templateUrl: './country.component.html' +}) +export class CountryComponent implements OnInit, OnDestroy { + countries: ICountry[]; + currentAccount: any; + eventSubscriber: Subscription; + currentSearch: string; + + constructor( + protected countryService: CountryService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected activatedRoute: ActivatedRoute, + protected accountService: AccountService + ) { + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.countryService + .search({ + query: this.currentSearch + }) + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe((res: ICountry[]) => (this.countries = res), (res: HttpErrorResponse) => this.onError(res.message)); + return; + } + this.countryService + .query() + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe( + (res: ICountry[]) => { + this.countries = res; + this.currentSearch = ''; + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.currentSearch = query; + this.loadAll(); + } + + clear() { + this.currentSearch = ''; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInCountries(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: ICountry) { + return item.id; + } + + registerChangeInCountries() { + this.eventSubscriber = this.eventManager.subscribe('countryListModification', response => this.loadAll()); + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/country/country.module.ts b/src/main/webapp/app/entities/country/country.module.ts new file mode 100644 index 0000000..2d216d3 --- /dev/null +++ b/src/main/webapp/app/entities/country/country.module.ts @@ -0,0 +1,29 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + CountryComponent, + CountryDetailComponent, + CountryUpdateComponent, + CountryDeletePopupComponent, + CountryDeleteDialogComponent, + countryRoute, + countryPopupRoute +} from './'; + +const ENTITY_STATES = [...countryRoute, ...countryPopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + CountryComponent, + CountryDetailComponent, + CountryUpdateComponent, + CountryDeleteDialogComponent, + CountryDeletePopupComponent + ], + entryComponents: [CountryComponent, CountryUpdateComponent, CountryDeleteDialogComponent, CountryDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioCountryModule {} diff --git a/src/main/webapp/app/entities/country/country.route.ts b/src/main/webapp/app/entities/country/country.route.ts new file mode 100644 index 0000000..d69dd4d --- /dev/null +++ b/src/main/webapp/app/entities/country/country.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Country } from 'app/shared/model/country.model'; +import { CountryService } from './country.service'; +import { CountryComponent } from './country.component'; +import { CountryDetailComponent } from './country-detail.component'; +import { CountryUpdateComponent } from './country-update.component'; +import { CountryDeletePopupComponent } from './country-delete-dialog.component'; +import { ICountry } from 'app/shared/model/country.model'; + +@Injectable({ providedIn: 'root' }) +export class CountryResolve implements Resolve { + constructor(private service: CountryService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((country: HttpResponse) => country.body) + ); + } + return of(new Country()); + } +} + +export const countryRoute: Routes = [ + { + path: '', + component: CountryComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Countries' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: CountryDetailComponent, + resolve: { + country: CountryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Countries' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: CountryUpdateComponent, + resolve: { + country: CountryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Countries' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: CountryUpdateComponent, + resolve: { + country: CountryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Countries' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const countryPopupRoute: Routes = [ + { + path: ':id/delete', + component: CountryDeletePopupComponent, + resolve: { + country: CountryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Countries' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/country/country.service.ts b/src/main/webapp/app/entities/country/country.service.ts new file mode 100644 index 0000000..7794001 --- /dev/null +++ b/src/main/webapp/app/entities/country/country.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'; +import { ICountry } from 'app/shared/model/country.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class CountryService { + public resourceUrl = SERVER_API_URL + 'api/countries'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/countries'; + + constructor(protected http: HttpClient) {} + + create(country: ICountry): Observable { + return this.http.post(this.resourceUrl, country, { observe: 'response' }); + } + + update(country: ICountry): Observable { + return this.http.put(this.resourceUrl, country, { 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/country/index.ts b/src/main/webapp/app/entities/country/index.ts new file mode 100644 index 0000000..51d4824 --- /dev/null +++ b/src/main/webapp/app/entities/country/index.ts @@ -0,0 +1,6 @@ +export * from './country.service'; +export * from './country-update.component'; +export * from './country-delete-dialog.component'; +export * from './country-detail.component'; +export * from './country.component'; +export * from './country.route'; diff --git a/src/main/webapp/app/entities/department/department-delete-dialog.component.html b/src/main/webapp/app/entities/department/department-delete-dialog.component.html new file mode 100644 index 0000000..a282848 --- /dev/null +++ b/src/main/webapp/app/entities/department/department-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/department/department-delete-dialog.component.ts b/src/main/webapp/app/entities/department/department-delete-dialog.component.ts new file mode 100644 index 0000000..9dd0279 --- /dev/null +++ b/src/main/webapp/app/entities/department/department-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 { IDepartment } from 'app/shared/model/department.model'; +import { DepartmentService } from './department.service'; + +@Component({ + selector: 'jhi-department-delete-dialog', + templateUrl: './department-delete-dialog.component.html' +}) +export class DepartmentDeleteDialogComponent { + department: IDepartment; + + constructor( + protected departmentService: DepartmentService, + public activeModal: NgbActiveModal, + protected eventManager: JhiEventManager + ) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.departmentService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'departmentListModification', + content: 'Deleted an department' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-department-delete-popup', + template: '' +}) +export class DepartmentDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ department }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(DepartmentDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.department = department; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/department', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/department', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/department/department-detail.component.html b/src/main/webapp/app/entities/department/department-detail.component.html new file mode 100644 index 0000000..edf5976 --- /dev/null +++ b/src/main/webapp/app/entities/department/department-detail.component.html @@ -0,0 +1,33 @@ +
+
+
+

Department {{department.id}}

+
+ +
+
Department Name
+
+ {{department.departmentName}} +
+
Location
+
+ +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/department/department-detail.component.ts b/src/main/webapp/app/entities/department/department-detail.component.ts new file mode 100644 index 0000000..3eb94f3 --- /dev/null +++ b/src/main/webapp/app/entities/department/department-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { IDepartment } from 'app/shared/model/department.model'; + +@Component({ + selector: 'jhi-department-detail', + templateUrl: './department-detail.component.html' +}) +export class DepartmentDetailComponent implements OnInit { + department: IDepartment; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ department }) => { + this.department = department; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/department/department-update.component.html b/src/main/webapp/app/entities/department/department-update.component.html new file mode 100644 index 0000000..7f8de01 --- /dev/null +++ b/src/main/webapp/app/entities/department/department-update.component.html @@ -0,0 +1,42 @@ +
+
+
+

Create or edit a Department

+
+ +
+ + +
+
+ + +
+ + This field is required. + +
+
+ +
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/department/department-update.component.ts b/src/main/webapp/app/entities/department/department-update.component.ts new file mode 100644 index 0000000..0f5ac80 --- /dev/null +++ b/src/main/webapp/app/entities/department/department-update.component.ts @@ -0,0 +1,119 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiAlertService } from 'ng-jhipster'; +import { IDepartment, Department } from 'app/shared/model/department.model'; +import { DepartmentService } from './department.service'; +import { ILocation } from 'app/shared/model/location.model'; +import { LocationService } from 'app/entities/location'; + +@Component({ + selector: 'jhi-department-update', + templateUrl: './department-update.component.html' +}) +export class DepartmentUpdateComponent implements OnInit { + isSaving: boolean; + + locations: ILocation[]; + + editForm = this.fb.group({ + id: [], + departmentName: [null, [Validators.required]], + locationId: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected departmentService: DepartmentService, + protected locationService: LocationService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ department }) => { + this.updateForm(department); + }); + this.locationService + .query({ filter: 'department-is-null' }) + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe( + (res: ILocation[]) => { + if (!!this.editForm.get('locationId').value) { + this.locations = res; + } else { + this.locationService + .find(this.editForm.get('locationId').value) + .pipe( + filter((subResMayBeOk: HttpResponse) => subResMayBeOk.ok), + map((subResponse: HttpResponse) => subResponse.body) + ) + .subscribe( + (subRes: ILocation) => (this.locations = [subRes].concat(res)), + (subRes: HttpErrorResponse) => this.onError(subRes.message) + ); + } + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + updateForm(department: IDepartment) { + this.editForm.patchValue({ + id: department.id, + departmentName: department.departmentName, + locationId: department.locationId + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const department = this.createFromForm(); + if (department.id !== undefined) { + this.subscribeToSaveResponse(this.departmentService.update(department)); + } else { + this.subscribeToSaveResponse(this.departmentService.create(department)); + } + } + + private createFromForm(): IDepartment { + const entity = { + ...new Department(), + id: this.editForm.get(['id']).value, + departmentName: this.editForm.get(['departmentName']).value, + locationId: this.editForm.get(['locationId']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackLocationById(index: number, item: ILocation) { + return item.id; + } +} diff --git a/src/main/webapp/app/entities/department/department.component.html b/src/main/webapp/app/entities/department/department.component.html new file mode 100644 index 0000000..6ff9bcb --- /dev/null +++ b/src/main/webapp/app/entities/department/department.component.html @@ -0,0 +1,78 @@ +
+

+ Departments + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No departments found +
+
+ + + + + + + + + + + + + + + + + +
IDDepartment NameLocation
{{department.id}}{{department.departmentName}} + + +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/department/department.component.ts b/src/main/webapp/app/entities/department/department.component.ts new file mode 100644 index 0000000..d7d756d --- /dev/null +++ b/src/main/webapp/app/entities/department/department.component.ts @@ -0,0 +1,97 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; + +import { IDepartment } from 'app/shared/model/department.model'; +import { AccountService } from 'app/core'; +import { DepartmentService } from './department.service'; + +@Component({ + selector: 'jhi-department', + templateUrl: './department.component.html' +}) +export class DepartmentComponent implements OnInit, OnDestroy { + departments: IDepartment[]; + currentAccount: any; + eventSubscriber: Subscription; + currentSearch: string; + + constructor( + protected departmentService: DepartmentService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected activatedRoute: ActivatedRoute, + protected accountService: AccountService + ) { + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.departmentService + .search({ + query: this.currentSearch + }) + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe((res: IDepartment[]) => (this.departments = res), (res: HttpErrorResponse) => this.onError(res.message)); + return; + } + this.departmentService + .query() + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe( + (res: IDepartment[]) => { + this.departments = res; + this.currentSearch = ''; + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.currentSearch = query; + this.loadAll(); + } + + clear() { + this.currentSearch = ''; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInDepartments(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IDepartment) { + return item.id; + } + + registerChangeInDepartments() { + this.eventSubscriber = this.eventManager.subscribe('departmentListModification', response => this.loadAll()); + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/department/department.module.ts b/src/main/webapp/app/entities/department/department.module.ts new file mode 100644 index 0000000..85f744c --- /dev/null +++ b/src/main/webapp/app/entities/department/department.module.ts @@ -0,0 +1,29 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + DepartmentComponent, + DepartmentDetailComponent, + DepartmentUpdateComponent, + DepartmentDeletePopupComponent, + DepartmentDeleteDialogComponent, + departmentRoute, + departmentPopupRoute +} from './'; + +const ENTITY_STATES = [...departmentRoute, ...departmentPopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + DepartmentComponent, + DepartmentDetailComponent, + DepartmentUpdateComponent, + DepartmentDeleteDialogComponent, + DepartmentDeletePopupComponent + ], + entryComponents: [DepartmentComponent, DepartmentUpdateComponent, DepartmentDeleteDialogComponent, DepartmentDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioDepartmentModule {} diff --git a/src/main/webapp/app/entities/department/department.route.ts b/src/main/webapp/app/entities/department/department.route.ts new file mode 100644 index 0000000..d369a68 --- /dev/null +++ b/src/main/webapp/app/entities/department/department.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Department } from 'app/shared/model/department.model'; +import { DepartmentService } from './department.service'; +import { DepartmentComponent } from './department.component'; +import { DepartmentDetailComponent } from './department-detail.component'; +import { DepartmentUpdateComponent } from './department-update.component'; +import { DepartmentDeletePopupComponent } from './department-delete-dialog.component'; +import { IDepartment } from 'app/shared/model/department.model'; + +@Injectable({ providedIn: 'root' }) +export class DepartmentResolve implements Resolve { + constructor(private service: DepartmentService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((department: HttpResponse) => department.body) + ); + } + return of(new Department()); + } +} + +export const departmentRoute: Routes = [ + { + path: '', + component: DepartmentComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Departments' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: DepartmentDetailComponent, + resolve: { + department: DepartmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Departments' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: DepartmentUpdateComponent, + resolve: { + department: DepartmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Departments' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: DepartmentUpdateComponent, + resolve: { + department: DepartmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Departments' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const departmentPopupRoute: Routes = [ + { + path: ':id/delete', + component: DepartmentDeletePopupComponent, + resolve: { + department: DepartmentResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Departments' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/department/department.service.ts b/src/main/webapp/app/entities/department/department.service.ts new file mode 100644 index 0000000..1f9e1c8 --- /dev/null +++ b/src/main/webapp/app/entities/department/department.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'; +import { IDepartment } from 'app/shared/model/department.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class DepartmentService { + public resourceUrl = SERVER_API_URL + 'api/departments'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/departments'; + + constructor(protected http: HttpClient) {} + + create(department: IDepartment): Observable { + return this.http.post(this.resourceUrl, department, { observe: 'response' }); + } + + update(department: IDepartment): Observable { + return this.http.put(this.resourceUrl, department, { 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/department/index.ts b/src/main/webapp/app/entities/department/index.ts new file mode 100644 index 0000000..709526d --- /dev/null +++ b/src/main/webapp/app/entities/department/index.ts @@ -0,0 +1,6 @@ +export * from './department.service'; +export * from './department-update.component'; +export * from './department-delete-dialog.component'; +export * from './department-detail.component'; +export * from './department.component'; +export * from './department.route'; diff --git a/src/main/webapp/app/entities/employee/employee-delete-dialog.component.html b/src/main/webapp/app/entities/employee/employee-delete-dialog.component.html new file mode 100644 index 0000000..d3c59a1 --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/employee/employee-delete-dialog.component.ts b/src/main/webapp/app/entities/employee/employee-delete-dialog.component.ts new file mode 100644 index 0000000..676c8c8 --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee-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 { IEmployee } from 'app/shared/model/employee.model'; +import { EmployeeService } from './employee.service'; + +@Component({ + selector: 'jhi-employee-delete-dialog', + templateUrl: './employee-delete-dialog.component.html' +}) +export class EmployeeDeleteDialogComponent { + employee: IEmployee; + + constructor(protected employeeService: EmployeeService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.employeeService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'employeeListModification', + content: 'Deleted an employee' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-employee-delete-popup', + template: '' +}) +export class EmployeeDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ employee }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(EmployeeDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.employee = employee; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/employee', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/employee', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/employee/employee-detail.component.html b/src/main/webapp/app/entities/employee/employee-detail.component.html new file mode 100644 index 0000000..6c55ca9 --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee-detail.component.html @@ -0,0 +1,63 @@ +
+
+
+

Employee {{employee.id}}

+
+ +
+
First Name
+
+ {{employee.firstName}} +
+
Last Name
+
+ {{employee.lastName}} +
+
Email
+
+ {{employee.email}} +
+
Phone Number
+
+ {{employee.phoneNumber}} +
+
Hire Date
+
+ {{employee.hireDate}} +
+
Salary
+
+ {{employee.salary}} +
+
Commission Pct
+
+ {{employee.commissionPct}} +
+
Department
+
+ +
+
Manager
+
+ +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/employee/employee-detail.component.ts b/src/main/webapp/app/entities/employee/employee-detail.component.ts new file mode 100644 index 0000000..bce433d --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { IEmployee } from 'app/shared/model/employee.model'; + +@Component({ + selector: 'jhi-employee-detail', + templateUrl: './employee-detail.component.html' +}) +export class EmployeeDetailComponent implements OnInit { + employee: IEmployee; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ employee }) => { + this.employee = employee; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/employee/employee-update.component.html b/src/main/webapp/app/entities/employee/employee-update.component.html new file mode 100644 index 0000000..de20999 --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee-update.component.html @@ -0,0 +1,74 @@ +
+
+
+

Create or edit a Employee

+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ +
+
+
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/employee/employee-update.component.ts b/src/main/webapp/app/entities/employee/employee-update.component.ts new file mode 100644 index 0000000..24dda15 --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee-update.component.ts @@ -0,0 +1,137 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +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 { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; +import { JhiAlertService } from 'ng-jhipster'; +import { IEmployee, Employee } from 'app/shared/model/employee.model'; +import { EmployeeService } from './employee.service'; +import { IDepartment } from 'app/shared/model/department.model'; +import { DepartmentService } from 'app/entities/department'; + +@Component({ + selector: 'jhi-employee-update', + templateUrl: './employee-update.component.html' +}) +export class EmployeeUpdateComponent implements OnInit { + isSaving: boolean; + + departments: IDepartment[]; + + employees: IEmployee[]; + + editForm = this.fb.group({ + id: [], + firstName: [], + lastName: [], + email: [], + phoneNumber: [], + hireDate: [], + salary: [], + commissionPct: [], + departmentId: [], + managerId: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected employeeService: EmployeeService, + protected departmentService: DepartmentService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ employee }) => { + this.updateForm(employee); + }); + this.departmentService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: IDepartment[]) => (this.departments = res), (res: HttpErrorResponse) => this.onError(res.message)); + this.employeeService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: IEmployee[]) => (this.employees = res), (res: HttpErrorResponse) => this.onError(res.message)); + } + + updateForm(employee: IEmployee) { + this.editForm.patchValue({ + id: employee.id, + firstName: employee.firstName, + lastName: employee.lastName, + email: employee.email, + phoneNumber: employee.phoneNumber, + hireDate: employee.hireDate != null ? employee.hireDate.format(DATE_TIME_FORMAT) : null, + salary: employee.salary, + commissionPct: employee.commissionPct, + departmentId: employee.departmentId, + managerId: employee.managerId + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const employee = this.createFromForm(); + if (employee.id !== undefined) { + this.subscribeToSaveResponse(this.employeeService.update(employee)); + } else { + this.subscribeToSaveResponse(this.employeeService.create(employee)); + } + } + + private createFromForm(): IEmployee { + const entity = { + ...new Employee(), + id: this.editForm.get(['id']).value, + firstName: this.editForm.get(['firstName']).value, + lastName: this.editForm.get(['lastName']).value, + email: this.editForm.get(['email']).value, + phoneNumber: this.editForm.get(['phoneNumber']).value, + hireDate: this.editForm.get(['hireDate']).value != null ? moment(this.editForm.get(['hireDate']).value, DATE_TIME_FORMAT) : undefined, + salary: this.editForm.get(['salary']).value, + commissionPct: this.editForm.get(['commissionPct']).value, + departmentId: this.editForm.get(['departmentId']).value, + managerId: this.editForm.get(['managerId']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackDepartmentById(index: number, item: IDepartment) { + return item.id; + } + + trackEmployeeById(index: number, item: IEmployee) { + return item.id; + } +} diff --git a/src/main/webapp/app/entities/employee/employee.component.html b/src/main/webapp/app/entities/employee/employee.component.html new file mode 100644 index 0000000..ae85be1 --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee.component.html @@ -0,0 +1,96 @@ +
+

+ Employees + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No employees found +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ID First Name Last Name Email Phone Number Hire Date Salary Commission Pct Department Manager
{{employee.id}}{{employee.firstName}}{{employee.lastName}}{{employee.email}}{{employee.phoneNumber}}{{employee.hireDate | date:'medium'}}{{employee.salary}}{{employee.commissionPct}} + + + + +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/employee/employee.component.ts b/src/main/webapp/app/entities/employee/employee.component.ts new file mode 100644 index 0000000..d32e25b --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee.component.ts @@ -0,0 +1,154 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiParseLinks, JhiAlertService } from 'ng-jhipster'; + +import { IEmployee } from 'app/shared/model/employee.model'; +import { AccountService } from 'app/core'; + +import { ITEMS_PER_PAGE } from 'app/shared'; +import { EmployeeService } from './employee.service'; + +@Component({ + selector: 'jhi-employee', + templateUrl: './employee.component.html' +}) +export class EmployeeComponent implements OnInit, OnDestroy { + employees: IEmployee[]; + currentAccount: any; + eventSubscriber: Subscription; + itemsPerPage: number; + links: any; + page: any; + predicate: any; + reverse: any; + totalItems: number; + currentSearch: string; + + constructor( + protected employeeService: EmployeeService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected parseLinks: JhiParseLinks, + protected activatedRoute: ActivatedRoute, + protected accountService: AccountService + ) { + this.employees = []; + this.itemsPerPage = ITEMS_PER_PAGE; + this.page = 0; + this.links = { + last: 0 + }; + this.predicate = 'id'; + this.reverse = true; + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.employeeService + .search({ + query: this.currentSearch, + page: this.page, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe( + (res: HttpResponse) => this.paginateEmployees(res.body, res.headers), + (res: HttpErrorResponse) => this.onError(res.message) + ); + return; + } + this.employeeService + .query({ + page: this.page, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe( + (res: HttpResponse) => this.paginateEmployees(res.body, res.headers), + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + reset() { + this.page = 0; + this.employees = []; + this.loadAll(); + } + + loadPage(page) { + this.page = page; + this.loadAll(); + } + + clear() { + this.employees = []; + this.links = { + last: 0 + }; + this.page = 0; + this.predicate = 'id'; + this.reverse = true; + this.currentSearch = ''; + this.loadAll(); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.employees = []; + this.links = { + last: 0 + }; + this.page = 0; + this.predicate = '_score'; + this.reverse = false; + this.currentSearch = query; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInEmployees(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IEmployee) { + return item.id; + } + + registerChangeInEmployees() { + this.eventSubscriber = this.eventManager.subscribe('employeeListModification', response => this.reset()); + } + + sort() { + const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')]; + if (this.predicate !== 'id') { + result.push('id'); + } + return result; + } + + protected paginateEmployees(data: IEmployee[], headers: HttpHeaders) { + this.links = this.parseLinks.parse(headers.get('link')); + this.totalItems = parseInt(headers.get('X-Total-Count'), 10); + for (let i = 0; i < data.length; i++) { + this.employees.push(data[i]); + } + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/employee/employee.module.ts b/src/main/webapp/app/entities/employee/employee.module.ts new file mode 100644 index 0000000..2345371 --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee.module.ts @@ -0,0 +1,29 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + EmployeeComponent, + EmployeeDetailComponent, + EmployeeUpdateComponent, + EmployeeDeletePopupComponent, + EmployeeDeleteDialogComponent, + employeeRoute, + employeePopupRoute +} from './'; + +const ENTITY_STATES = [...employeeRoute, ...employeePopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + EmployeeComponent, + EmployeeDetailComponent, + EmployeeUpdateComponent, + EmployeeDeleteDialogComponent, + EmployeeDeletePopupComponent + ], + entryComponents: [EmployeeComponent, EmployeeUpdateComponent, EmployeeDeleteDialogComponent, EmployeeDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioEmployeeModule {} diff --git a/src/main/webapp/app/entities/employee/employee.route.ts b/src/main/webapp/app/entities/employee/employee.route.ts new file mode 100644 index 0000000..6edc39e --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Employee } from 'app/shared/model/employee.model'; +import { EmployeeService } from './employee.service'; +import { EmployeeComponent } from './employee.component'; +import { EmployeeDetailComponent } from './employee-detail.component'; +import { EmployeeUpdateComponent } from './employee-update.component'; +import { EmployeeDeletePopupComponent } from './employee-delete-dialog.component'; +import { IEmployee } from 'app/shared/model/employee.model'; + +@Injectable({ providedIn: 'root' }) +export class EmployeeResolve implements Resolve { + constructor(private service: EmployeeService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((employee: HttpResponse) => employee.body) + ); + } + return of(new Employee()); + } +} + +export const employeeRoute: Routes = [ + { + path: '', + component: EmployeeComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Employees' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: EmployeeDetailComponent, + resolve: { + employee: EmployeeResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Employees' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: EmployeeUpdateComponent, + resolve: { + employee: EmployeeResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Employees' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: EmployeeUpdateComponent, + resolve: { + employee: EmployeeResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Employees' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const employeePopupRoute: Routes = [ + { + path: ':id/delete', + component: EmployeeDeletePopupComponent, + resolve: { + employee: EmployeeResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Employees' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/employee/employee.service.ts b/src/main/webapp/app/entities/employee/employee.service.ts new file mode 100644 index 0000000..a0e144e --- /dev/null +++ b/src/main/webapp/app/entities/employee/employee.service.ts @@ -0,0 +1,82 @@ +import { Injectable } from '@angular/core'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import * as moment from 'moment'; +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'; +import { IEmployee } from 'app/shared/model/employee.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class EmployeeService { + public resourceUrl = SERVER_API_URL + 'api/employees'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/employees'; + + constructor(protected http: HttpClient) {} + + create(employee: IEmployee): Observable { + const copy = this.convertDateFromClient(employee); + return this.http + .post(this.resourceUrl, copy, { observe: 'response' }) + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); + } + + update(employee: IEmployee): Observable { + const copy = this.convertDateFromClient(employee); + 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(employee: IEmployee): IEmployee { + const copy: IEmployee = Object.assign({}, employee, { + hireDate: employee.hireDate != null && employee.hireDate.isValid() ? employee.hireDate.toJSON() : null + }); + return copy; + } + + protected convertDateFromServer(res: EntityResponseType): EntityResponseType { + if (res.body) { + res.body.hireDate = res.body.hireDate != null ? moment(res.body.hireDate) : null; + } + return res; + } + + protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType { + if (res.body) { + res.body.forEach((employee: IEmployee) => { + employee.hireDate = employee.hireDate != null ? moment(employee.hireDate) : null; + }); + } + return res; + } +} diff --git a/src/main/webapp/app/entities/employee/index.ts b/src/main/webapp/app/entities/employee/index.ts new file mode 100644 index 0000000..3599b59 --- /dev/null +++ b/src/main/webapp/app/entities/employee/index.ts @@ -0,0 +1,6 @@ +export * from './employee.service'; +export * from './employee-update.component'; +export * from './employee-delete-dialog.component'; +export * from './employee-detail.component'; +export * from './employee.component'; +export * from './employee.route'; diff --git a/src/main/webapp/app/entities/entity.module.ts b/src/main/webapp/app/entities/entity.module.ts index e28ce3b..2076560 100644 --- a/src/main/webapp/app/entities/entity.module.ts +++ b/src/main/webapp/app/entities/entity.module.ts @@ -4,6 +4,38 @@ import { RouterModule } from '@angular/router'; @NgModule({ imports: [ RouterModule.forChild([ + { + path: 'region', + loadChildren: './region/region.module#VisioRegionModule' + }, + { + path: 'country', + loadChildren: './country/country.module#VisioCountryModule' + }, + { + path: 'location', + loadChildren: './location/location.module#VisioLocationModule' + }, + { + path: 'department', + loadChildren: './department/department.module#VisioDepartmentModule' + }, + { + path: 'task', + loadChildren: './task/task.module#VisioTaskModule' + }, + { + path: 'employee', + loadChildren: './employee/employee.module#VisioEmployeeModule' + }, + { + path: 'job', + loadChildren: './job/job.module#VisioJobModule' + }, + { + path: 'job-history', + loadChildren: './job-history/job-history.module#VisioJobHistoryModule' + } /* jhipster-needle-add-entity-route - JHipster will add entity modules routes here */ ]) ], diff --git a/src/main/webapp/app/entities/job-history/index.ts b/src/main/webapp/app/entities/job-history/index.ts new file mode 100644 index 0000000..64c6986 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/index.ts @@ -0,0 +1,6 @@ +export * from './job-history.service'; +export * from './job-history-update.component'; +export * from './job-history-delete-dialog.component'; +export * from './job-history-detail.component'; +export * from './job-history.component'; +export * from './job-history.route'; diff --git a/src/main/webapp/app/entities/job-history/job-history-delete-dialog.component.html b/src/main/webapp/app/entities/job-history/job-history-delete-dialog.component.html new file mode 100644 index 0000000..97d9c4f --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/job-history/job-history-delete-dialog.component.ts b/src/main/webapp/app/entities/job-history/job-history-delete-dialog.component.ts new file mode 100644 index 0000000..e8ba438 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history-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 { IJobHistory } from 'app/shared/model/job-history.model'; +import { JobHistoryService } from './job-history.service'; + +@Component({ + selector: 'jhi-job-history-delete-dialog', + templateUrl: './job-history-delete-dialog.component.html' +}) +export class JobHistoryDeleteDialogComponent { + jobHistory: IJobHistory; + + constructor( + protected jobHistoryService: JobHistoryService, + public activeModal: NgbActiveModal, + protected eventManager: JhiEventManager + ) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.jobHistoryService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'jobHistoryListModification', + content: 'Deleted an jobHistory' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-job-history-delete-popup', + template: '' +}) +export class JobHistoryDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ jobHistory }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(JobHistoryDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.jobHistory = jobHistory; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/job-history', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/job-history', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/job-history/job-history-detail.component.html b/src/main/webapp/app/entities/job-history/job-history-detail.component.html new file mode 100644 index 0000000..71cb378 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history-detail.component.html @@ -0,0 +1,53 @@ +
+
+
+

Job History {{jobHistory.id}}

+
+ +
+
Start Date
+
+ {{jobHistory.startDate}} +
+
End Date
+
+ {{jobHistory.endDate}} +
+
Language
+
+ {{jobHistory.language}} +
+
Job
+
+ +
+
Department
+
+ +
+
Employee
+
+ +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/job-history/job-history-detail.component.ts b/src/main/webapp/app/entities/job-history/job-history-detail.component.ts new file mode 100644 index 0000000..dc9bc1d --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { IJobHistory } from 'app/shared/model/job-history.model'; + +@Component({ + selector: 'jhi-job-history-detail', + templateUrl: './job-history-detail.component.html' +}) +export class JobHistoryDetailComponent implements OnInit { + jobHistory: IJobHistory; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ jobHistory }) => { + this.jobHistory = jobHistory; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/job-history/job-history-update.component.html b/src/main/webapp/app/entities/job-history/job-history-update.component.html new file mode 100644 index 0000000..4526854 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history-update.component.html @@ -0,0 +1,65 @@ +
+
+
+

Create or edit a Job History

+
+ +
+ + +
+
+ +
+ +
+
+
+ +
+ +
+
+
+ + +
+ +
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/job-history/job-history-update.component.ts b/src/main/webapp/app/entities/job-history/job-history-update.component.ts new file mode 100644 index 0000000..77ab855 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history-update.component.ts @@ -0,0 +1,199 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +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 { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; +import { JhiAlertService } from 'ng-jhipster'; +import { IJobHistory, JobHistory } from 'app/shared/model/job-history.model'; +import { JobHistoryService } from './job-history.service'; +import { IJob } from 'app/shared/model/job.model'; +import { JobService } from 'app/entities/job'; +import { IDepartment } from 'app/shared/model/department.model'; +import { DepartmentService } from 'app/entities/department'; +import { IEmployee } from 'app/shared/model/employee.model'; +import { EmployeeService } from 'app/entities/employee'; + +@Component({ + selector: 'jhi-job-history-update', + templateUrl: './job-history-update.component.html' +}) +export class JobHistoryUpdateComponent implements OnInit { + isSaving: boolean; + + jobs: IJob[]; + + departments: IDepartment[]; + + employees: IEmployee[]; + + editForm = this.fb.group({ + id: [], + startDate: [], + endDate: [], + language: [], + jobId: [], + departmentId: [], + employeeId: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected jobHistoryService: JobHistoryService, + protected jobService: JobService, + protected departmentService: DepartmentService, + protected employeeService: EmployeeService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ jobHistory }) => { + this.updateForm(jobHistory); + }); + this.jobService + .query({ filter: 'jobhistory-is-null' }) + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe( + (res: IJob[]) => { + if (!!this.editForm.get('jobId').value) { + this.jobs = res; + } else { + this.jobService + .find(this.editForm.get('jobId').value) + .pipe( + filter((subResMayBeOk: HttpResponse) => subResMayBeOk.ok), + map((subResponse: HttpResponse) => subResponse.body) + ) + .subscribe((subRes: IJob) => (this.jobs = [subRes].concat(res)), (subRes: HttpErrorResponse) => this.onError(subRes.message)); + } + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + this.departmentService + .query({ filter: 'jobhistory-is-null' }) + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe( + (res: IDepartment[]) => { + if (!!this.editForm.get('departmentId').value) { + this.departments = res; + } else { + this.departmentService + .find(this.editForm.get('departmentId').value) + .pipe( + filter((subResMayBeOk: HttpResponse) => subResMayBeOk.ok), + map((subResponse: HttpResponse) => subResponse.body) + ) + .subscribe( + (subRes: IDepartment) => (this.departments = [subRes].concat(res)), + (subRes: HttpErrorResponse) => this.onError(subRes.message) + ); + } + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + this.employeeService + .query({ filter: 'jobhistory-is-null' }) + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe( + (res: IEmployee[]) => { + if (!!this.editForm.get('employeeId').value) { + this.employees = res; + } else { + this.employeeService + .find(this.editForm.get('employeeId').value) + .pipe( + filter((subResMayBeOk: HttpResponse) => subResMayBeOk.ok), + map((subResponse: HttpResponse) => subResponse.body) + ) + .subscribe( + (subRes: IEmployee) => (this.employees = [subRes].concat(res)), + (subRes: HttpErrorResponse) => this.onError(subRes.message) + ); + } + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + updateForm(jobHistory: IJobHistory) { + this.editForm.patchValue({ + id: jobHistory.id, + startDate: jobHistory.startDate != null ? jobHistory.startDate.format(DATE_TIME_FORMAT) : null, + endDate: jobHistory.endDate != null ? jobHistory.endDate.format(DATE_TIME_FORMAT) : null, + language: jobHistory.language, + jobId: jobHistory.jobId, + departmentId: jobHistory.departmentId, + employeeId: jobHistory.employeeId + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const jobHistory = this.createFromForm(); + if (jobHistory.id !== undefined) { + this.subscribeToSaveResponse(this.jobHistoryService.update(jobHistory)); + } else { + this.subscribeToSaveResponse(this.jobHistoryService.create(jobHistory)); + } + } + + private createFromForm(): IJobHistory { + const entity = { + ...new JobHistory(), + id: this.editForm.get(['id']).value, + startDate: + this.editForm.get(['startDate']).value != null ? moment(this.editForm.get(['startDate']).value, DATE_TIME_FORMAT) : undefined, + endDate: this.editForm.get(['endDate']).value != null ? moment(this.editForm.get(['endDate']).value, DATE_TIME_FORMAT) : undefined, + language: this.editForm.get(['language']).value, + jobId: this.editForm.get(['jobId']).value, + departmentId: this.editForm.get(['departmentId']).value, + employeeId: this.editForm.get(['employeeId']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackJobById(index: number, item: IJob) { + return item.id; + } + + trackDepartmentById(index: number, item: IDepartment) { + return item.id; + } + + trackEmployeeById(index: number, item: IEmployee) { + return item.id; + } +} diff --git a/src/main/webapp/app/entities/job-history/job-history.component.html b/src/main/webapp/app/entities/job-history/job-history.component.html new file mode 100644 index 0000000..dddf514 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history.component.html @@ -0,0 +1,94 @@ +
+

+ Job Histories + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No jobHistories found +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
ID Start Date End Date Language Job Department Employee
{{jobHistory.id}}{{jobHistory.startDate | date:'medium'}}{{jobHistory.endDate | date:'medium'}}{{jobHistory.language}} + + + + + + +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/job-history/job-history.component.ts b/src/main/webapp/app/entities/job-history/job-history.component.ts new file mode 100644 index 0000000..9a4868e --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history.component.ts @@ -0,0 +1,154 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiParseLinks, JhiAlertService } from 'ng-jhipster'; + +import { IJobHistory } from 'app/shared/model/job-history.model'; +import { AccountService } from 'app/core'; + +import { ITEMS_PER_PAGE } from 'app/shared'; +import { JobHistoryService } from './job-history.service'; + +@Component({ + selector: 'jhi-job-history', + templateUrl: './job-history.component.html' +}) +export class JobHistoryComponent implements OnInit, OnDestroy { + jobHistories: IJobHistory[]; + currentAccount: any; + eventSubscriber: Subscription; + itemsPerPage: number; + links: any; + page: any; + predicate: any; + reverse: any; + totalItems: number; + currentSearch: string; + + constructor( + protected jobHistoryService: JobHistoryService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected parseLinks: JhiParseLinks, + protected activatedRoute: ActivatedRoute, + protected accountService: AccountService + ) { + this.jobHistories = []; + this.itemsPerPage = ITEMS_PER_PAGE; + this.page = 0; + this.links = { + last: 0 + }; + this.predicate = 'id'; + this.reverse = true; + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.jobHistoryService + .search({ + query: this.currentSearch, + page: this.page, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe( + (res: HttpResponse) => this.paginateJobHistories(res.body, res.headers), + (res: HttpErrorResponse) => this.onError(res.message) + ); + return; + } + this.jobHistoryService + .query({ + page: this.page, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe( + (res: HttpResponse) => this.paginateJobHistories(res.body, res.headers), + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + reset() { + this.page = 0; + this.jobHistories = []; + this.loadAll(); + } + + loadPage(page) { + this.page = page; + this.loadAll(); + } + + clear() { + this.jobHistories = []; + this.links = { + last: 0 + }; + this.page = 0; + this.predicate = 'id'; + this.reverse = true; + this.currentSearch = ''; + this.loadAll(); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.jobHistories = []; + this.links = { + last: 0 + }; + this.page = 0; + this.predicate = '_score'; + this.reverse = false; + this.currentSearch = query; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInJobHistories(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IJobHistory) { + return item.id; + } + + registerChangeInJobHistories() { + this.eventSubscriber = this.eventManager.subscribe('jobHistoryListModification', response => this.reset()); + } + + sort() { + const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')]; + if (this.predicate !== 'id') { + result.push('id'); + } + return result; + } + + protected paginateJobHistories(data: IJobHistory[], headers: HttpHeaders) { + this.links = this.parseLinks.parse(headers.get('link')); + this.totalItems = parseInt(headers.get('X-Total-Count'), 10); + for (let i = 0; i < data.length; i++) { + this.jobHistories.push(data[i]); + } + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/job-history/job-history.module.ts b/src/main/webapp/app/entities/job-history/job-history.module.ts new file mode 100644 index 0000000..a715694 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history.module.ts @@ -0,0 +1,29 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + JobHistoryComponent, + JobHistoryDetailComponent, + JobHistoryUpdateComponent, + JobHistoryDeletePopupComponent, + JobHistoryDeleteDialogComponent, + jobHistoryRoute, + jobHistoryPopupRoute +} from './'; + +const ENTITY_STATES = [...jobHistoryRoute, ...jobHistoryPopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + JobHistoryComponent, + JobHistoryDetailComponent, + JobHistoryUpdateComponent, + JobHistoryDeleteDialogComponent, + JobHistoryDeletePopupComponent + ], + entryComponents: [JobHistoryComponent, JobHistoryUpdateComponent, JobHistoryDeleteDialogComponent, JobHistoryDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioJobHistoryModule {} diff --git a/src/main/webapp/app/entities/job-history/job-history.route.ts b/src/main/webapp/app/entities/job-history/job-history.route.ts new file mode 100644 index 0000000..3591cfd --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JobHistory } from 'app/shared/model/job-history.model'; +import { JobHistoryService } from './job-history.service'; +import { JobHistoryComponent } from './job-history.component'; +import { JobHistoryDetailComponent } from './job-history-detail.component'; +import { JobHistoryUpdateComponent } from './job-history-update.component'; +import { JobHistoryDeletePopupComponent } from './job-history-delete-dialog.component'; +import { IJobHistory } from 'app/shared/model/job-history.model'; + +@Injectable({ providedIn: 'root' }) +export class JobHistoryResolve implements Resolve { + constructor(private service: JobHistoryService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((jobHistory: HttpResponse) => jobHistory.body) + ); + } + return of(new JobHistory()); + } +} + +export const jobHistoryRoute: Routes = [ + { + path: '', + component: JobHistoryComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'JobHistories' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: JobHistoryDetailComponent, + resolve: { + jobHistory: JobHistoryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'JobHistories' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: JobHistoryUpdateComponent, + resolve: { + jobHistory: JobHistoryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'JobHistories' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: JobHistoryUpdateComponent, + resolve: { + jobHistory: JobHistoryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'JobHistories' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const jobHistoryPopupRoute: Routes = [ + { + path: ':id/delete', + component: JobHistoryDeletePopupComponent, + resolve: { + jobHistory: JobHistoryResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'JobHistories' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/job-history/job-history.service.ts b/src/main/webapp/app/entities/job-history/job-history.service.ts new file mode 100644 index 0000000..4ffb774 --- /dev/null +++ b/src/main/webapp/app/entities/job-history/job-history.service.ts @@ -0,0 +1,85 @@ +import { Injectable } from '@angular/core'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { Observable } from 'rxjs'; +import * as moment from 'moment'; +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'; +import { IJobHistory } from 'app/shared/model/job-history.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class JobHistoryService { + public resourceUrl = SERVER_API_URL + 'api/job-histories'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/job-histories'; + + constructor(protected http: HttpClient) {} + + create(jobHistory: IJobHistory): Observable { + const copy = this.convertDateFromClient(jobHistory); + return this.http + .post(this.resourceUrl, copy, { observe: 'response' }) + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); + } + + update(jobHistory: IJobHistory): Observable { + const copy = this.convertDateFromClient(jobHistory); + 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(jobHistory: IJobHistory): IJobHistory { + const copy: IJobHistory = Object.assign({}, jobHistory, { + startDate: jobHistory.startDate != null && jobHistory.startDate.isValid() ? jobHistory.startDate.toJSON() : null, + endDate: jobHistory.endDate != null && jobHistory.endDate.isValid() ? jobHistory.endDate.toJSON() : null + }); + return copy; + } + + protected convertDateFromServer(res: EntityResponseType): EntityResponseType { + if (res.body) { + res.body.startDate = res.body.startDate != null ? moment(res.body.startDate) : null; + res.body.endDate = res.body.endDate != null ? moment(res.body.endDate) : null; + } + return res; + } + + protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType { + if (res.body) { + res.body.forEach((jobHistory: IJobHistory) => { + jobHistory.startDate = jobHistory.startDate != null ? moment(jobHistory.startDate) : null; + jobHistory.endDate = jobHistory.endDate != null ? moment(jobHistory.endDate) : null; + }); + } + return res; + } +} diff --git a/src/main/webapp/app/entities/job/index.ts b/src/main/webapp/app/entities/job/index.ts new file mode 100644 index 0000000..6d95bd5 --- /dev/null +++ b/src/main/webapp/app/entities/job/index.ts @@ -0,0 +1,6 @@ +export * from './job.service'; +export * from './job-update.component'; +export * from './job-delete-dialog.component'; +export * from './job-detail.component'; +export * from './job.component'; +export * from './job.route'; diff --git a/src/main/webapp/app/entities/job/job-delete-dialog.component.html b/src/main/webapp/app/entities/job/job-delete-dialog.component.html new file mode 100644 index 0000000..886dbb2 --- /dev/null +++ b/src/main/webapp/app/entities/job/job-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/job/job-delete-dialog.component.ts b/src/main/webapp/app/entities/job/job-delete-dialog.component.ts new file mode 100644 index 0000000..e4e3247 --- /dev/null +++ b/src/main/webapp/app/entities/job/job-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 { IJob } from 'app/shared/model/job.model'; +import { JobService } from './job.service'; + +@Component({ + selector: 'jhi-job-delete-dialog', + templateUrl: './job-delete-dialog.component.html' +}) +export class JobDeleteDialogComponent { + job: IJob; + + constructor(protected jobService: JobService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.jobService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'jobListModification', + content: 'Deleted an job' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-job-delete-popup', + template: '' +}) +export class JobDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ job }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(JobDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.job = job; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/job', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/job', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/job/job-detail.component.html b/src/main/webapp/app/entities/job/job-detail.component.html new file mode 100644 index 0000000..21acf6b --- /dev/null +++ b/src/main/webapp/app/entities/job/job-detail.component.html @@ -0,0 +1,47 @@ +
+
+
+

Job {{job.id}}

+
+ +
+
Job Title
+
+ {{job.jobTitle}} +
+
Min Salary
+
+ {{job.minSalary}} +
+
Max Salary
+
+ {{job.maxSalary}} +
+
Employee
+
+ +
+
Task
+
+ + {{task.title}}{{last ? '' : ', '}} + +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/job/job-detail.component.ts b/src/main/webapp/app/entities/job/job-detail.component.ts new file mode 100644 index 0000000..9bd6f52 --- /dev/null +++ b/src/main/webapp/app/entities/job/job-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { IJob } from 'app/shared/model/job.model'; + +@Component({ + selector: 'jhi-job-detail', + templateUrl: './job-detail.component.html' +}) +export class JobDetailComponent implements OnInit { + job: IJob; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ job }) => { + this.job = job; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/job/job-update.component.html b/src/main/webapp/app/entities/job/job-update.component.html new file mode 100644 index 0000000..764e7e0 --- /dev/null +++ b/src/main/webapp/app/entities/job/job-update.component.html @@ -0,0 +1,52 @@ +
+
+
+

Create or edit a Job

+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/job/job-update.component.ts b/src/main/webapp/app/entities/job/job-update.component.ts new file mode 100644 index 0000000..c94b1f0 --- /dev/null +++ b/src/main/webapp/app/entities/job/job-update.component.ts @@ -0,0 +1,137 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiAlertService } from 'ng-jhipster'; +import { IJob, Job } from 'app/shared/model/job.model'; +import { JobService } from './job.service'; +import { IEmployee } from 'app/shared/model/employee.model'; +import { EmployeeService } from 'app/entities/employee'; +import { ITask } from 'app/shared/model/task.model'; +import { TaskService } from 'app/entities/task'; + +@Component({ + selector: 'jhi-job-update', + templateUrl: './job-update.component.html' +}) +export class JobUpdateComponent implements OnInit { + isSaving: boolean; + + employees: IEmployee[]; + + tasks: ITask[]; + + editForm = this.fb.group({ + id: [], + jobTitle: [], + minSalary: [], + maxSalary: [], + employeeId: [], + tasks: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected jobService: JobService, + protected employeeService: EmployeeService, + protected taskService: TaskService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ job }) => { + this.updateForm(job); + }); + this.employeeService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: IEmployee[]) => (this.employees = res), (res: HttpErrorResponse) => this.onError(res.message)); + this.taskService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: ITask[]) => (this.tasks = res), (res: HttpErrorResponse) => this.onError(res.message)); + } + + updateForm(job: IJob) { + this.editForm.patchValue({ + id: job.id, + jobTitle: job.jobTitle, + minSalary: job.minSalary, + maxSalary: job.maxSalary, + employeeId: job.employeeId, + tasks: job.tasks + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const job = this.createFromForm(); + if (job.id !== undefined) { + this.subscribeToSaveResponse(this.jobService.update(job)); + } else { + this.subscribeToSaveResponse(this.jobService.create(job)); + } + } + + private createFromForm(): IJob { + const entity = { + ...new Job(), + id: this.editForm.get(['id']).value, + jobTitle: this.editForm.get(['jobTitle']).value, + minSalary: this.editForm.get(['minSalary']).value, + maxSalary: this.editForm.get(['maxSalary']).value, + employeeId: this.editForm.get(['employeeId']).value, + tasks: this.editForm.get(['tasks']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackEmployeeById(index: number, item: IEmployee) { + return item.id; + } + + trackTaskById(index: number, item: ITask) { + return item.id; + } + + getSelected(selectedVals: Array, option: any) { + if (selectedVals) { + for (let i = 0; i < selectedVals.length; i++) { + if (option.id === selectedVals[i].id) { + return selectedVals[i]; + } + } + } + return option; + } +} diff --git a/src/main/webapp/app/entities/job/job.component.html b/src/main/webapp/app/entities/job/job.component.html new file mode 100644 index 0000000..e1a7c36 --- /dev/null +++ b/src/main/webapp/app/entities/job/job.component.html @@ -0,0 +1,90 @@ +
+

+ Jobs + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No jobs found +
+
+ + + + + + + + + + + + + + + + + + + + + +
ID Job Title Min Salary Max Salary Employee
{{job.id}}{{job.jobTitle}}{{job.minSalary}}{{job.maxSalary}} + + +
+ + + +
+
+
+
+
+ +
+
+ +
+
+
diff --git a/src/main/webapp/app/entities/job/job.component.ts b/src/main/webapp/app/entities/job/job.component.ts new file mode 100644 index 0000000..810ca32 --- /dev/null +++ b/src/main/webapp/app/entities/job/job.component.ts @@ -0,0 +1,167 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Router } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiParseLinks, JhiAlertService } from 'ng-jhipster'; + +import { IJob } from 'app/shared/model/job.model'; +import { AccountService } from 'app/core'; + +import { ITEMS_PER_PAGE } from 'app/shared'; +import { JobService } from './job.service'; + +@Component({ + selector: 'jhi-job', + templateUrl: './job.component.html' +}) +export class JobComponent implements OnInit, OnDestroy { + currentAccount: any; + jobs: IJob[]; + 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 jobService: JobService, + protected parseLinks: JhiParseLinks, + protected jhiAlertService: JhiAlertService, + 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.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.jobService + .search({ + page: this.page - 1, + query: this.currentSearch, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe( + (res: HttpResponse) => this.paginateJobs(res.body, res.headers), + (res: HttpErrorResponse) => this.onError(res.message) + ); + return; + } + this.jobService + .query({ + page: this.page - 1, + size: this.itemsPerPage, + sort: this.sort() + }) + .subscribe( + (res: HttpResponse) => this.paginateJobs(res.body, res.headers), + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + loadPage(page: number) { + if (page !== this.previousPage) { + this.previousPage = page; + this.transition(); + } + } + + transition() { + this.router.navigate(['/job'], { + 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([ + '/job', + { + 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([ + '/job', + { + search: this.currentSearch, + page: this.page, + sort: this.predicate + ',' + (this.reverse ? 'asc' : 'desc') + } + ]); + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInJobs(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IJob) { + return item.id; + } + + registerChangeInJobs() { + this.eventSubscriber = this.eventManager.subscribe('jobListModification', response => this.loadAll()); + } + + sort() { + const result = [this.predicate + ',' + (this.reverse ? 'asc' : 'desc')]; + if (this.predicate !== 'id') { + result.push('id'); + } + return result; + } + + protected paginateJobs(data: IJob[], headers: HttpHeaders) { + this.links = this.parseLinks.parse(headers.get('link')); + this.totalItems = parseInt(headers.get('X-Total-Count'), 10); + this.jobs = data; + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/job/job.module.ts b/src/main/webapp/app/entities/job/job.module.ts new file mode 100644 index 0000000..6dc4fca --- /dev/null +++ b/src/main/webapp/app/entities/job/job.module.ts @@ -0,0 +1,23 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + JobComponent, + JobDetailComponent, + JobUpdateComponent, + JobDeletePopupComponent, + JobDeleteDialogComponent, + jobRoute, + jobPopupRoute +} from './'; + +const ENTITY_STATES = [...jobRoute, ...jobPopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [JobComponent, JobDetailComponent, JobUpdateComponent, JobDeleteDialogComponent, JobDeletePopupComponent], + entryComponents: [JobComponent, JobUpdateComponent, JobDeleteDialogComponent, JobDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioJobModule {} diff --git a/src/main/webapp/app/entities/job/job.route.ts b/src/main/webapp/app/entities/job/job.route.ts new file mode 100644 index 0000000..792fb24 --- /dev/null +++ b/src/main/webapp/app/entities/job/job.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 { JhiPaginationUtil, JhiResolvePagingParams } from 'ng-jhipster'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Job } from 'app/shared/model/job.model'; +import { JobService } from './job.service'; +import { JobComponent } from './job.component'; +import { JobDetailComponent } from './job-detail.component'; +import { JobUpdateComponent } from './job-update.component'; +import { JobDeletePopupComponent } from './job-delete-dialog.component'; +import { IJob } from 'app/shared/model/job.model'; + +@Injectable({ providedIn: 'root' }) +export class JobResolve implements Resolve { + constructor(private service: JobService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((job: HttpResponse) => job.body) + ); + } + return of(new Job()); + } +} + +export const jobRoute: Routes = [ + { + path: '', + component: JobComponent, + resolve: { + pagingParams: JhiResolvePagingParams + }, + data: { + authorities: ['ROLE_USER'], + defaultSort: 'id,asc', + pageTitle: 'Jobs' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: JobDetailComponent, + resolve: { + job: JobResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Jobs' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: JobUpdateComponent, + resolve: { + job: JobResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Jobs' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: JobUpdateComponent, + resolve: { + job: JobResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Jobs' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const jobPopupRoute: Routes = [ + { + path: ':id/delete', + component: JobDeletePopupComponent, + resolve: { + job: JobResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Jobs' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/job/job.service.ts b/src/main/webapp/app/entities/job/job.service.ts new file mode 100644 index 0000000..de3ae41 --- /dev/null +++ b/src/main/webapp/app/entities/job/job.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'; +import { IJob } from 'app/shared/model/job.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class JobService { + public resourceUrl = SERVER_API_URL + 'api/jobs'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/jobs'; + + constructor(protected http: HttpClient) {} + + create(job: IJob): Observable { + return this.http.post(this.resourceUrl, job, { observe: 'response' }); + } + + update(job: IJob): Observable { + return this.http.put(this.resourceUrl, job, { 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/location/index.ts b/src/main/webapp/app/entities/location/index.ts new file mode 100644 index 0000000..1789788 --- /dev/null +++ b/src/main/webapp/app/entities/location/index.ts @@ -0,0 +1,6 @@ +export * from './location.service'; +export * from './location-update.component'; +export * from './location-delete-dialog.component'; +export * from './location-detail.component'; +export * from './location.component'; +export * from './location.route'; diff --git a/src/main/webapp/app/entities/location/location-delete-dialog.component.html b/src/main/webapp/app/entities/location/location-delete-dialog.component.html new file mode 100644 index 0000000..c32231a --- /dev/null +++ b/src/main/webapp/app/entities/location/location-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/location/location-delete-dialog.component.ts b/src/main/webapp/app/entities/location/location-delete-dialog.component.ts new file mode 100644 index 0000000..50eb1fa --- /dev/null +++ b/src/main/webapp/app/entities/location/location-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 { ILocation } from 'app/shared/model/location.model'; +import { LocationService } from './location.service'; + +@Component({ + selector: 'jhi-location-delete-dialog', + templateUrl: './location-delete-dialog.component.html' +}) +export class LocationDeleteDialogComponent { + location: ILocation; + + constructor(protected locationService: LocationService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.locationService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'locationListModification', + content: 'Deleted an location' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-location-delete-popup', + template: '' +}) +export class LocationDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ location }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(LocationDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.location = location; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/location', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/location', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/location/location-detail.component.html b/src/main/webapp/app/entities/location/location-detail.component.html new file mode 100644 index 0000000..4edd3c7 --- /dev/null +++ b/src/main/webapp/app/entities/location/location-detail.component.html @@ -0,0 +1,45 @@ +
+
+
+

Location {{location.id}}

+
+ +
+
Street Address
+
+ {{location.streetAddress}} +
+
Postal Code
+
+ {{location.postalCode}} +
+
City
+
+ {{location.city}} +
+
State Province
+
+ {{location.stateProvince}} +
+
Country
+
+ +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/location/location-detail.component.ts b/src/main/webapp/app/entities/location/location-detail.component.ts new file mode 100644 index 0000000..39bd169 --- /dev/null +++ b/src/main/webapp/app/entities/location/location-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { ILocation } from 'app/shared/model/location.model'; + +@Component({ + selector: 'jhi-location-detail', + templateUrl: './location-detail.component.html' +}) +export class LocationDetailComponent implements OnInit { + location: ILocation; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ location }) => { + this.location = location; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/location/location-update.component.html b/src/main/webapp/app/entities/location/location-update.component.html new file mode 100644 index 0000000..3d3bf80 --- /dev/null +++ b/src/main/webapp/app/entities/location/location-update.component.html @@ -0,0 +1,51 @@ +
+
+
+

Create or edit a Location

+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ + +
+
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/location/location-update.component.ts b/src/main/webapp/app/entities/location/location-update.component.ts new file mode 100644 index 0000000..f4fc87a --- /dev/null +++ b/src/main/webapp/app/entities/location/location-update.component.ts @@ -0,0 +1,128 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiAlertService } from 'ng-jhipster'; +import { ILocation, Location } from 'app/shared/model/location.model'; +import { LocationService } from './location.service'; +import { ICountry } from 'app/shared/model/country.model'; +import { CountryService } from 'app/entities/country'; + +@Component({ + selector: 'jhi-location-update', + templateUrl: './location-update.component.html' +}) +export class LocationUpdateComponent implements OnInit { + isSaving: boolean; + + countries: ICountry[]; + + editForm = this.fb.group({ + id: [], + streetAddress: [], + postalCode: [], + city: [], + stateProvince: [], + countryId: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected locationService: LocationService, + protected countryService: CountryService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ location }) => { + this.updateForm(location); + }); + this.countryService + .query({ filter: 'location-is-null' }) + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe( + (res: ICountry[]) => { + if (!!this.editForm.get('countryId').value) { + this.countries = res; + } else { + this.countryService + .find(this.editForm.get('countryId').value) + .pipe( + filter((subResMayBeOk: HttpResponse) => subResMayBeOk.ok), + map((subResponse: HttpResponse) => subResponse.body) + ) + .subscribe( + (subRes: ICountry) => (this.countries = [subRes].concat(res)), + (subRes: HttpErrorResponse) => this.onError(subRes.message) + ); + } + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + updateForm(location: ILocation) { + this.editForm.patchValue({ + id: location.id, + streetAddress: location.streetAddress, + postalCode: location.postalCode, + city: location.city, + stateProvince: location.stateProvince, + countryId: location.countryId + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const location = this.createFromForm(); + if (location.id !== undefined) { + this.subscribeToSaveResponse(this.locationService.update(location)); + } else { + this.subscribeToSaveResponse(this.locationService.create(location)); + } + } + + private createFromForm(): ILocation { + const entity = { + ...new Location(), + id: this.editForm.get(['id']).value, + streetAddress: this.editForm.get(['streetAddress']).value, + postalCode: this.editForm.get(['postalCode']).value, + city: this.editForm.get(['city']).value, + stateProvince: this.editForm.get(['stateProvince']).value, + countryId: this.editForm.get(['countryId']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackCountryById(index: number, item: ICountry) { + return item.id; + } +} diff --git a/src/main/webapp/app/entities/location/location.component.html b/src/main/webapp/app/entities/location/location.component.html new file mode 100644 index 0000000..e8ceff4 --- /dev/null +++ b/src/main/webapp/app/entities/location/location.component.html @@ -0,0 +1,84 @@ +
+

+ Locations + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No locations found +
+
+ + + + + + + + + + + + + + + + + + + + + + + +
IDStreet AddressPostal CodeCityState ProvinceCountry
{{location.id}}{{location.streetAddress}}{{location.postalCode}}{{location.city}}{{location.stateProvince}} + + +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/location/location.component.ts b/src/main/webapp/app/entities/location/location.component.ts new file mode 100644 index 0000000..27b4b93 --- /dev/null +++ b/src/main/webapp/app/entities/location/location.component.ts @@ -0,0 +1,97 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; + +import { ILocation } from 'app/shared/model/location.model'; +import { AccountService } from 'app/core'; +import { LocationService } from './location.service'; + +@Component({ + selector: 'jhi-location', + templateUrl: './location.component.html' +}) +export class LocationComponent implements OnInit, OnDestroy { + locations: ILocation[]; + currentAccount: any; + eventSubscriber: Subscription; + currentSearch: string; + + constructor( + protected locationService: LocationService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected activatedRoute: ActivatedRoute, + protected accountService: AccountService + ) { + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.locationService + .search({ + query: this.currentSearch + }) + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe((res: ILocation[]) => (this.locations = res), (res: HttpErrorResponse) => this.onError(res.message)); + return; + } + this.locationService + .query() + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe( + (res: ILocation[]) => { + this.locations = res; + this.currentSearch = ''; + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.currentSearch = query; + this.loadAll(); + } + + clear() { + this.currentSearch = ''; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInLocations(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: ILocation) { + return item.id; + } + + registerChangeInLocations() { + this.eventSubscriber = this.eventManager.subscribe('locationListModification', response => this.loadAll()); + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/location/location.module.ts b/src/main/webapp/app/entities/location/location.module.ts new file mode 100644 index 0000000..e88a967 --- /dev/null +++ b/src/main/webapp/app/entities/location/location.module.ts @@ -0,0 +1,29 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + LocationComponent, + LocationDetailComponent, + LocationUpdateComponent, + LocationDeletePopupComponent, + LocationDeleteDialogComponent, + locationRoute, + locationPopupRoute +} from './'; + +const ENTITY_STATES = [...locationRoute, ...locationPopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [ + LocationComponent, + LocationDetailComponent, + LocationUpdateComponent, + LocationDeleteDialogComponent, + LocationDeletePopupComponent + ], + entryComponents: [LocationComponent, LocationUpdateComponent, LocationDeleteDialogComponent, LocationDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioLocationModule {} diff --git a/src/main/webapp/app/entities/location/location.route.ts b/src/main/webapp/app/entities/location/location.route.ts new file mode 100644 index 0000000..325e068 --- /dev/null +++ b/src/main/webapp/app/entities/location/location.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Location } from 'app/shared/model/location.model'; +import { LocationService } from './location.service'; +import { LocationComponent } from './location.component'; +import { LocationDetailComponent } from './location-detail.component'; +import { LocationUpdateComponent } from './location-update.component'; +import { LocationDeletePopupComponent } from './location-delete-dialog.component'; +import { ILocation } from 'app/shared/model/location.model'; + +@Injectable({ providedIn: 'root' }) +export class LocationResolve implements Resolve { + constructor(private service: LocationService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((location: HttpResponse) => location.body) + ); + } + return of(new Location()); + } +} + +export const locationRoute: Routes = [ + { + path: '', + component: LocationComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Locations' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: LocationDetailComponent, + resolve: { + location: LocationResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Locations' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: LocationUpdateComponent, + resolve: { + location: LocationResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Locations' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: LocationUpdateComponent, + resolve: { + location: LocationResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Locations' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const locationPopupRoute: Routes = [ + { + path: ':id/delete', + component: LocationDeletePopupComponent, + resolve: { + location: LocationResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Locations' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/location/location.service.ts b/src/main/webapp/app/entities/location/location.service.ts new file mode 100644 index 0000000..0c37a36 --- /dev/null +++ b/src/main/webapp/app/entities/location/location.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'; +import { ILocation } from 'app/shared/model/location.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class LocationService { + public resourceUrl = SERVER_API_URL + 'api/locations'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/locations'; + + constructor(protected http: HttpClient) {} + + create(location: ILocation): Observable { + return this.http.post(this.resourceUrl, location, { observe: 'response' }); + } + + update(location: ILocation): Observable { + return this.http.put(this.resourceUrl, location, { 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/region/index.ts b/src/main/webapp/app/entities/region/index.ts new file mode 100644 index 0000000..587d678 --- /dev/null +++ b/src/main/webapp/app/entities/region/index.ts @@ -0,0 +1,6 @@ +export * from './region.service'; +export * from './region-update.component'; +export * from './region-delete-dialog.component'; +export * from './region-detail.component'; +export * from './region.component'; +export * from './region.route'; diff --git a/src/main/webapp/app/entities/region/region-delete-dialog.component.html b/src/main/webapp/app/entities/region/region-delete-dialog.component.html new file mode 100644 index 0000000..df486e7 --- /dev/null +++ b/src/main/webapp/app/entities/region/region-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/region/region-delete-dialog.component.ts b/src/main/webapp/app/entities/region/region-delete-dialog.component.ts new file mode 100644 index 0000000..df6b6b2 --- /dev/null +++ b/src/main/webapp/app/entities/region/region-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 { IRegion } from 'app/shared/model/region.model'; +import { RegionService } from './region.service'; + +@Component({ + selector: 'jhi-region-delete-dialog', + templateUrl: './region-delete-dialog.component.html' +}) +export class RegionDeleteDialogComponent { + region: IRegion; + + constructor(protected regionService: RegionService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.regionService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'regionListModification', + content: 'Deleted an region' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-region-delete-popup', + template: '' +}) +export class RegionDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ region }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(RegionDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.region = region; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/region', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/region', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/region/region-detail.component.html b/src/main/webapp/app/entities/region/region-detail.component.html new file mode 100644 index 0000000..a6748f0 --- /dev/null +++ b/src/main/webapp/app/entities/region/region-detail.component.html @@ -0,0 +1,27 @@ +
+
+
+

Region {{region.id}}

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

Create or edit a Region

+
+ +
+ + +
+
+ + +
+ +
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/region/region-update.component.ts b/src/main/webapp/app/entities/region/region-update.component.ts new file mode 100644 index 0000000..c8aed28 --- /dev/null +++ b/src/main/webapp/app/entities/region/region-update.component.ts @@ -0,0 +1,72 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { IRegion, Region } from 'app/shared/model/region.model'; +import { RegionService } from './region.service'; + +@Component({ + selector: 'jhi-region-update', + templateUrl: './region-update.component.html' +}) +export class RegionUpdateComponent implements OnInit { + isSaving: boolean; + + editForm = this.fb.group({ + id: [], + regionName: [] + }); + + constructor(protected regionService: RegionService, protected activatedRoute: ActivatedRoute, private fb: FormBuilder) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ region }) => { + this.updateForm(region); + }); + } + + updateForm(region: IRegion) { + this.editForm.patchValue({ + id: region.id, + regionName: region.regionName + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const region = this.createFromForm(); + if (region.id !== undefined) { + this.subscribeToSaveResponse(this.regionService.update(region)); + } else { + this.subscribeToSaveResponse(this.regionService.create(region)); + } + } + + private createFromForm(): IRegion { + const entity = { + ...new Region(), + id: this.editForm.get(['id']).value, + regionName: this.editForm.get(['regionName']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } +} diff --git a/src/main/webapp/app/entities/region/region.component.html b/src/main/webapp/app/entities/region/region.component.html new file mode 100644 index 0000000..3051328 --- /dev/null +++ b/src/main/webapp/app/entities/region/region.component.html @@ -0,0 +1,72 @@ +
+

+ Regions + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No regions found +
+
+ + + + + + + + + + + + + + + +
IDRegion Name
{{region.id}}{{region.regionName}} +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/region/region.component.ts b/src/main/webapp/app/entities/region/region.component.ts new file mode 100644 index 0000000..ebf047c --- /dev/null +++ b/src/main/webapp/app/entities/region/region.component.ts @@ -0,0 +1,97 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; + +import { IRegion } from 'app/shared/model/region.model'; +import { AccountService } from 'app/core'; +import { RegionService } from './region.service'; + +@Component({ + selector: 'jhi-region', + templateUrl: './region.component.html' +}) +export class RegionComponent implements OnInit, OnDestroy { + regions: IRegion[]; + currentAccount: any; + eventSubscriber: Subscription; + currentSearch: string; + + constructor( + protected regionService: RegionService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected activatedRoute: ActivatedRoute, + protected accountService: AccountService + ) { + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.regionService + .search({ + query: this.currentSearch + }) + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe((res: IRegion[]) => (this.regions = res), (res: HttpErrorResponse) => this.onError(res.message)); + return; + } + this.regionService + .query() + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe( + (res: IRegion[]) => { + this.regions = res; + this.currentSearch = ''; + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.currentSearch = query; + this.loadAll(); + } + + clear() { + this.currentSearch = ''; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInRegions(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: IRegion) { + return item.id; + } + + registerChangeInRegions() { + this.eventSubscriber = this.eventManager.subscribe('regionListModification', response => this.loadAll()); + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/region/region.module.ts b/src/main/webapp/app/entities/region/region.module.ts new file mode 100644 index 0000000..e00c6a9 --- /dev/null +++ b/src/main/webapp/app/entities/region/region.module.ts @@ -0,0 +1,23 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + RegionComponent, + RegionDetailComponent, + RegionUpdateComponent, + RegionDeletePopupComponent, + RegionDeleteDialogComponent, + regionRoute, + regionPopupRoute +} from './'; + +const ENTITY_STATES = [...regionRoute, ...regionPopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [RegionComponent, RegionDetailComponent, RegionUpdateComponent, RegionDeleteDialogComponent, RegionDeletePopupComponent], + entryComponents: [RegionComponent, RegionUpdateComponent, RegionDeleteDialogComponent, RegionDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioRegionModule {} diff --git a/src/main/webapp/app/entities/region/region.route.ts b/src/main/webapp/app/entities/region/region.route.ts new file mode 100644 index 0000000..d77739b --- /dev/null +++ b/src/main/webapp/app/entities/region/region.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Region } from 'app/shared/model/region.model'; +import { RegionService } from './region.service'; +import { RegionComponent } from './region.component'; +import { RegionDetailComponent } from './region-detail.component'; +import { RegionUpdateComponent } from './region-update.component'; +import { RegionDeletePopupComponent } from './region-delete-dialog.component'; +import { IRegion } from 'app/shared/model/region.model'; + +@Injectable({ providedIn: 'root' }) +export class RegionResolve implements Resolve { + constructor(private service: RegionService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((region: HttpResponse) => region.body) + ); + } + return of(new Region()); + } +} + +export const regionRoute: Routes = [ + { + path: '', + component: RegionComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Regions' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: RegionDetailComponent, + resolve: { + region: RegionResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Regions' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: RegionUpdateComponent, + resolve: { + region: RegionResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Regions' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: RegionUpdateComponent, + resolve: { + region: RegionResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Regions' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const regionPopupRoute: Routes = [ + { + path: ':id/delete', + component: RegionDeletePopupComponent, + resolve: { + region: RegionResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Regions' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/region/region.service.ts b/src/main/webapp/app/entities/region/region.service.ts new file mode 100644 index 0000000..5893479 --- /dev/null +++ b/src/main/webapp/app/entities/region/region.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'; +import { IRegion } from 'app/shared/model/region.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class RegionService { + public resourceUrl = SERVER_API_URL + 'api/regions'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/regions'; + + constructor(protected http: HttpClient) {} + + create(region: IRegion): Observable { + return this.http.post(this.resourceUrl, region, { observe: 'response' }); + } + + update(region: IRegion): Observable { + return this.http.put(this.resourceUrl, region, { 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/task/index.ts b/src/main/webapp/app/entities/task/index.ts new file mode 100644 index 0000000..2abc445 --- /dev/null +++ b/src/main/webapp/app/entities/task/index.ts @@ -0,0 +1,6 @@ +export * from './task.service'; +export * from './task-update.component'; +export * from './task-delete-dialog.component'; +export * from './task-detail.component'; +export * from './task.component'; +export * from './task.route'; diff --git a/src/main/webapp/app/entities/task/task-delete-dialog.component.html b/src/main/webapp/app/entities/task/task-delete-dialog.component.html new file mode 100644 index 0000000..f5c9d2a --- /dev/null +++ b/src/main/webapp/app/entities/task/task-delete-dialog.component.html @@ -0,0 +1,19 @@ +
+ + + +
diff --git a/src/main/webapp/app/entities/task/task-delete-dialog.component.ts b/src/main/webapp/app/entities/task/task-delete-dialog.component.ts new file mode 100644 index 0000000..dad31a3 --- /dev/null +++ b/src/main/webapp/app/entities/task/task-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 { ITask } from 'app/shared/model/task.model'; +import { TaskService } from './task.service'; + +@Component({ + selector: 'jhi-task-delete-dialog', + templateUrl: './task-delete-dialog.component.html' +}) +export class TaskDeleteDialogComponent { + task: ITask; + + constructor(protected taskService: TaskService, public activeModal: NgbActiveModal, protected eventManager: JhiEventManager) {} + + clear() { + this.activeModal.dismiss('cancel'); + } + + confirmDelete(id: number) { + this.taskService.delete(id).subscribe(response => { + this.eventManager.broadcast({ + name: 'taskListModification', + content: 'Deleted an task' + }); + this.activeModal.dismiss(true); + }); + } +} + +@Component({ + selector: 'jhi-task-delete-popup', + template: '' +}) +export class TaskDeletePopupComponent implements OnInit, OnDestroy { + protected ngbModalRef: NgbModalRef; + + constructor(protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ task }) => { + setTimeout(() => { + this.ngbModalRef = this.modalService.open(TaskDeleteDialogComponent as Component, { size: 'lg', backdrop: 'static' }); + this.ngbModalRef.componentInstance.task = task; + this.ngbModalRef.result.then( + result => { + this.router.navigate(['/task', { outlets: { popup: null } }]); + this.ngbModalRef = null; + }, + reason => { + this.router.navigate(['/task', { outlets: { popup: null } }]); + this.ngbModalRef = null; + } + ); + }, 0); + }); + } + + ngOnDestroy() { + this.ngbModalRef = null; + } +} diff --git a/src/main/webapp/app/entities/task/task-detail.component.html b/src/main/webapp/app/entities/task/task-detail.component.html new file mode 100644 index 0000000..9e6963c --- /dev/null +++ b/src/main/webapp/app/entities/task/task-detail.component.html @@ -0,0 +1,31 @@ +
+
+
+

Task {{task.id}}

+
+ +
+
Title
+
+ {{task.title}} +
+
Description
+
+ {{task.description}} +
+
+ + + + +
+
+
diff --git a/src/main/webapp/app/entities/task/task-detail.component.ts b/src/main/webapp/app/entities/task/task-detail.component.ts new file mode 100644 index 0000000..23934ba --- /dev/null +++ b/src/main/webapp/app/entities/task/task-detail.component.ts @@ -0,0 +1,24 @@ +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { ITask } from 'app/shared/model/task.model'; + +@Component({ + selector: 'jhi-task-detail', + templateUrl: './task-detail.component.html' +}) +export class TaskDetailComponent implements OnInit { + task: ITask; + + constructor(protected activatedRoute: ActivatedRoute) {} + + ngOnInit() { + this.activatedRoute.data.subscribe(({ task }) => { + this.task = task; + }); + } + + previousState() { + window.history.back(); + } +} diff --git a/src/main/webapp/app/entities/task/task-update.component.html b/src/main/webapp/app/entities/task/task-update.component.html new file mode 100644 index 0000000..fbcc7f2 --- /dev/null +++ b/src/main/webapp/app/entities/task/task-update.component.html @@ -0,0 +1,34 @@ +
+
+
+

Create or edit a Task

+
+ +
+ + +
+
+ + +
+
+ + +
+ +
+
+ + +
+
+
+
diff --git a/src/main/webapp/app/entities/task/task-update.component.ts b/src/main/webapp/app/entities/task/task-update.component.ts new file mode 100644 index 0000000..3661d1b --- /dev/null +++ b/src/main/webapp/app/entities/task/task-update.component.ts @@ -0,0 +1,112 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; +import { FormBuilder, Validators } from '@angular/forms'; +import { ActivatedRoute } from '@angular/router'; +import { Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiAlertService } from 'ng-jhipster'; +import { ITask, Task } from 'app/shared/model/task.model'; +import { TaskService } from './task.service'; +import { IJob } from 'app/shared/model/job.model'; +import { JobService } from 'app/entities/job'; + +@Component({ + selector: 'jhi-task-update', + templateUrl: './task-update.component.html' +}) +export class TaskUpdateComponent implements OnInit { + isSaving: boolean; + + jobs: IJob[]; + + editForm = this.fb.group({ + id: [], + title: [], + description: [] + }); + + constructor( + protected jhiAlertService: JhiAlertService, + protected taskService: TaskService, + protected jobService: JobService, + protected activatedRoute: ActivatedRoute, + private fb: FormBuilder + ) {} + + ngOnInit() { + this.isSaving = false; + this.activatedRoute.data.subscribe(({ task }) => { + this.updateForm(task); + }); + this.jobService + .query() + .pipe( + filter((mayBeOk: HttpResponse) => mayBeOk.ok), + map((response: HttpResponse) => response.body) + ) + .subscribe((res: IJob[]) => (this.jobs = res), (res: HttpErrorResponse) => this.onError(res.message)); + } + + updateForm(task: ITask) { + this.editForm.patchValue({ + id: task.id, + title: task.title, + description: task.description + }); + } + + previousState() { + window.history.back(); + } + + save() { + this.isSaving = true; + const task = this.createFromForm(); + if (task.id !== undefined) { + this.subscribeToSaveResponse(this.taskService.update(task)); + } else { + this.subscribeToSaveResponse(this.taskService.create(task)); + } + } + + private createFromForm(): ITask { + const entity = { + ...new Task(), + id: this.editForm.get(['id']).value, + title: this.editForm.get(['title']).value, + description: this.editForm.get(['description']).value + }; + return entity; + } + + protected subscribeToSaveResponse(result: Observable>) { + result.subscribe((res: HttpResponse) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError()); + } + + protected onSaveSuccess() { + this.isSaving = false; + this.previousState(); + } + + protected onSaveError() { + this.isSaving = false; + } + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } + + trackJobById(index: number, item: IJob) { + return item.id; + } + + getSelected(selectedVals: Array, option: any) { + if (selectedVals) { + for (let i = 0; i < selectedVals.length; i++) { + if (option.id === selectedVals[i].id) { + return selectedVals[i]; + } + } + } + return option; + } +} diff --git a/src/main/webapp/app/entities/task/task.component.html b/src/main/webapp/app/entities/task/task.component.html new file mode 100644 index 0000000..7c626a2 --- /dev/null +++ b/src/main/webapp/app/entities/task/task.component.html @@ -0,0 +1,74 @@ +
+

+ Tasks + +

+ +
+
+
+
+ + + +
+
+
+
+
+
+ No tasks found +
+
+ + + + + + + + + + + + + + + + + +
IDTitleDescription
{{task.id}}{{task.title}}{{task.description}} +
+ + + +
+
+
+
diff --git a/src/main/webapp/app/entities/task/task.component.ts b/src/main/webapp/app/entities/task/task.component.ts new file mode 100644 index 0000000..3a060c3 --- /dev/null +++ b/src/main/webapp/app/entities/task/task.component.ts @@ -0,0 +1,97 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { Subscription } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; + +import { ITask } from 'app/shared/model/task.model'; +import { AccountService } from 'app/core'; +import { TaskService } from './task.service'; + +@Component({ + selector: 'jhi-task', + templateUrl: './task.component.html' +}) +export class TaskComponent implements OnInit, OnDestroy { + tasks: ITask[]; + currentAccount: any; + eventSubscriber: Subscription; + currentSearch: string; + + constructor( + protected taskService: TaskService, + protected jhiAlertService: JhiAlertService, + protected eventManager: JhiEventManager, + protected activatedRoute: ActivatedRoute, + protected accountService: AccountService + ) { + this.currentSearch = + this.activatedRoute.snapshot && this.activatedRoute.snapshot.params['search'] ? this.activatedRoute.snapshot.params['search'] : ''; + } + + loadAll() { + if (this.currentSearch) { + this.taskService + .search({ + query: this.currentSearch + }) + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe((res: ITask[]) => (this.tasks = res), (res: HttpErrorResponse) => this.onError(res.message)); + return; + } + this.taskService + .query() + .pipe( + filter((res: HttpResponse) => res.ok), + map((res: HttpResponse) => res.body) + ) + .subscribe( + (res: ITask[]) => { + this.tasks = res; + this.currentSearch = ''; + }, + (res: HttpErrorResponse) => this.onError(res.message) + ); + } + + search(query) { + if (!query) { + return this.clear(); + } + this.currentSearch = query; + this.loadAll(); + } + + clear() { + this.currentSearch = ''; + this.loadAll(); + } + + ngOnInit() { + this.loadAll(); + this.accountService.identity().then(account => { + this.currentAccount = account; + }); + this.registerChangeInTasks(); + } + + ngOnDestroy() { + this.eventManager.destroy(this.eventSubscriber); + } + + trackId(index: number, item: ITask) { + return item.id; + } + + registerChangeInTasks() { + this.eventSubscriber = this.eventManager.subscribe('taskListModification', response => this.loadAll()); + } + + protected onError(errorMessage: string) { + this.jhiAlertService.error(errorMessage, null, null); + } +} diff --git a/src/main/webapp/app/entities/task/task.module.ts b/src/main/webapp/app/entities/task/task.module.ts new file mode 100644 index 0000000..51c0779 --- /dev/null +++ b/src/main/webapp/app/entities/task/task.module.ts @@ -0,0 +1,23 @@ +import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { VisioSharedModule } from 'app/shared'; +import { + TaskComponent, + TaskDetailComponent, + TaskUpdateComponent, + TaskDeletePopupComponent, + TaskDeleteDialogComponent, + taskRoute, + taskPopupRoute +} from './'; + +const ENTITY_STATES = [...taskRoute, ...taskPopupRoute]; + +@NgModule({ + imports: [VisioSharedModule, RouterModule.forChild(ENTITY_STATES)], + declarations: [TaskComponent, TaskDetailComponent, TaskUpdateComponent, TaskDeleteDialogComponent, TaskDeletePopupComponent], + entryComponents: [TaskComponent, TaskUpdateComponent, TaskDeleteDialogComponent, TaskDeletePopupComponent], + schemas: [CUSTOM_ELEMENTS_SCHEMA] +}) +export class VisioTaskModule {} diff --git a/src/main/webapp/app/entities/task/task.route.ts b/src/main/webapp/app/entities/task/task.route.ts new file mode 100644 index 0000000..fc93af2 --- /dev/null +++ b/src/main/webapp/app/entities/task/task.route.ts @@ -0,0 +1,93 @@ +import { Injectable } from '@angular/core'; +import { HttpResponse } from '@angular/common/http'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Routes } from '@angular/router'; +import { UserRouteAccessService } from 'app/core'; +import { Observable, of } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { Task } from 'app/shared/model/task.model'; +import { TaskService } from './task.service'; +import { TaskComponent } from './task.component'; +import { TaskDetailComponent } from './task-detail.component'; +import { TaskUpdateComponent } from './task-update.component'; +import { TaskDeletePopupComponent } from './task-delete-dialog.component'; +import { ITask } from 'app/shared/model/task.model'; + +@Injectable({ providedIn: 'root' }) +export class TaskResolve implements Resolve { + constructor(private service: TaskService) {} + + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + const id = route.params['id'] ? route.params['id'] : null; + if (id) { + return this.service.find(id).pipe( + filter((response: HttpResponse) => response.ok), + map((task: HttpResponse) => task.body) + ); + } + return of(new Task()); + } +} + +export const taskRoute: Routes = [ + { + path: '', + component: TaskComponent, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Tasks' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/view', + component: TaskDetailComponent, + resolve: { + task: TaskResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Tasks' + }, + canActivate: [UserRouteAccessService] + }, + { + path: 'new', + component: TaskUpdateComponent, + resolve: { + task: TaskResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Tasks' + }, + canActivate: [UserRouteAccessService] + }, + { + path: ':id/edit', + component: TaskUpdateComponent, + resolve: { + task: TaskResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Tasks' + }, + canActivate: [UserRouteAccessService] + } +]; + +export const taskPopupRoute: Routes = [ + { + path: ':id/delete', + component: TaskDeletePopupComponent, + resolve: { + task: TaskResolve + }, + data: { + authorities: ['ROLE_USER'], + pageTitle: 'Tasks' + }, + canActivate: [UserRouteAccessService], + outlet: 'popup' + } +]; diff --git a/src/main/webapp/app/entities/task/task.service.ts b/src/main/webapp/app/entities/task/task.service.ts new file mode 100644 index 0000000..f2f2bff --- /dev/null +++ b/src/main/webapp/app/entities/task/task.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'; +import { ITask } from 'app/shared/model/task.model'; + +type EntityResponseType = HttpResponse; +type EntityArrayResponseType = HttpResponse; + +@Injectable({ providedIn: 'root' }) +export class TaskService { + public resourceUrl = SERVER_API_URL + 'api/tasks'; + public resourceSearchUrl = SERVER_API_URL + 'api/_search/tasks'; + + constructor(protected http: HttpClient) {} + + create(task: ITask): Observable { + return this.http.post(this.resourceUrl, task, { observe: 'response' }); + } + + update(task: ITask): Observable { + return this.http.put(this.resourceUrl, task, { 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/layouts/navbar/navbar.component.html b/src/main/webapp/app/layouts/navbar/navbar.component.html index edc8347..fac18ff 100644 --- a/src/main/webapp/app/layouts/navbar/navbar.component.html +++ b/src/main/webapp/app/layouts/navbar/navbar.component.html @@ -27,6 +27,54 @@ diff --git a/src/main/webapp/app/shared/model/country.model.ts b/src/main/webapp/app/shared/model/country.model.ts new file mode 100644 index 0000000..e4cf885 --- /dev/null +++ b/src/main/webapp/app/shared/model/country.model.ts @@ -0,0 +1,9 @@ +export interface ICountry { + id?: number; + countryName?: string; + regionId?: number; +} + +export class Country implements ICountry { + constructor(public id?: number, public countryName?: string, public regionId?: number) {} +} diff --git a/src/main/webapp/app/shared/model/department.model.ts b/src/main/webapp/app/shared/model/department.model.ts new file mode 100644 index 0000000..a66b562 --- /dev/null +++ b/src/main/webapp/app/shared/model/department.model.ts @@ -0,0 +1,12 @@ +import { IEmployee } from 'app/shared/model/employee.model'; + +export interface IDepartment { + id?: number; + departmentName?: string; + locationId?: number; + employees?: IEmployee[]; +} + +export class Department implements IDepartment { + constructor(public id?: number, public departmentName?: string, public locationId?: number, public employees?: IEmployee[]) {} +} diff --git a/src/main/webapp/app/shared/model/employee.model.ts b/src/main/webapp/app/shared/model/employee.model.ts new file mode 100644 index 0000000..7afbbf9 --- /dev/null +++ b/src/main/webapp/app/shared/model/employee.model.ts @@ -0,0 +1,32 @@ +import { Moment } from 'moment'; +import { IJob } from 'app/shared/model/job.model'; + +export interface IEmployee { + id?: number; + firstName?: string; + lastName?: string; + email?: string; + phoneNumber?: string; + hireDate?: Moment; + salary?: number; + commissionPct?: number; + departmentId?: number; + jobs?: IJob[]; + managerId?: number; +} + +export class Employee implements IEmployee { + constructor( + public id?: number, + public firstName?: string, + public lastName?: string, + public email?: string, + public phoneNumber?: string, + public hireDate?: Moment, + public salary?: number, + public commissionPct?: number, + public departmentId?: number, + public jobs?: IJob[], + public managerId?: number + ) {} +} diff --git a/src/main/webapp/app/shared/model/job-history.model.ts b/src/main/webapp/app/shared/model/job-history.model.ts new file mode 100644 index 0000000..416906a --- /dev/null +++ b/src/main/webapp/app/shared/model/job-history.model.ts @@ -0,0 +1,29 @@ +import { Moment } from 'moment'; + +export const enum Language { + FRENCH = 'FRENCH', + ENGLISH = 'ENGLISH', + SPANISH = 'SPANISH' +} + +export interface IJobHistory { + id?: number; + startDate?: Moment; + endDate?: Moment; + language?: Language; + jobId?: number; + departmentId?: number; + employeeId?: number; +} + +export class JobHistory implements IJobHistory { + constructor( + public id?: number, + public startDate?: Moment, + public endDate?: Moment, + public language?: Language, + public jobId?: number, + public departmentId?: number, + public employeeId?: number + ) {} +} diff --git a/src/main/webapp/app/shared/model/job.model.ts b/src/main/webapp/app/shared/model/job.model.ts new file mode 100644 index 0000000..7390f97 --- /dev/null +++ b/src/main/webapp/app/shared/model/job.model.ts @@ -0,0 +1,21 @@ +import { ITask } from 'app/shared/model/task.model'; + +export interface IJob { + id?: number; + jobTitle?: string; + minSalary?: number; + maxSalary?: number; + employeeId?: number; + tasks?: ITask[]; +} + +export class Job implements IJob { + constructor( + public id?: number, + public jobTitle?: string, + public minSalary?: number, + public maxSalary?: number, + public employeeId?: number, + public tasks?: ITask[] + ) {} +} diff --git a/src/main/webapp/app/shared/model/location.model.ts b/src/main/webapp/app/shared/model/location.model.ts new file mode 100644 index 0000000..dda9b55 --- /dev/null +++ b/src/main/webapp/app/shared/model/location.model.ts @@ -0,0 +1,19 @@ +export interface ILocation { + id?: number; + streetAddress?: string; + postalCode?: string; + city?: string; + stateProvince?: string; + countryId?: number; +} + +export class Location implements ILocation { + constructor( + public id?: number, + public streetAddress?: string, + public postalCode?: string, + public city?: string, + public stateProvince?: string, + public countryId?: number + ) {} +} diff --git a/src/main/webapp/app/shared/model/region.model.ts b/src/main/webapp/app/shared/model/region.model.ts new file mode 100644 index 0000000..f707bf3 --- /dev/null +++ b/src/main/webapp/app/shared/model/region.model.ts @@ -0,0 +1,8 @@ +export interface IRegion { + id?: number; + regionName?: string; +} + +export class Region implements IRegion { + constructor(public id?: number, public regionName?: string) {} +} diff --git a/src/main/webapp/app/shared/model/task.model.ts b/src/main/webapp/app/shared/model/task.model.ts new file mode 100644 index 0000000..bd4ea18 --- /dev/null +++ b/src/main/webapp/app/shared/model/task.model.ts @@ -0,0 +1,12 @@ +import { IJob } from 'app/shared/model/job.model'; + +export interface ITask { + id?: number; + title?: string; + description?: string; + jobs?: IJob[]; +} + +export class Task implements ITask { + constructor(public id?: number, public title?: string, public description?: string, public jobs?: IJob[]) {} +} diff --git a/src/test/java/org/zdar/repository/search/CountrySearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/CountrySearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..0e95bc4 --- /dev/null +++ b/src/test/java/org/zdar/repository/search/CountrySearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link CountrySearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class CountrySearchRepositoryMockConfiguration { + + @MockBean + private CountrySearchRepository mockCountrySearchRepository; + +} diff --git a/src/test/java/org/zdar/repository/search/DepartmentSearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/DepartmentSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..31a7b4c --- /dev/null +++ b/src/test/java/org/zdar/repository/search/DepartmentSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link DepartmentSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class DepartmentSearchRepositoryMockConfiguration { + + @MockBean + private DepartmentSearchRepository mockDepartmentSearchRepository; + +} diff --git a/src/test/java/org/zdar/repository/search/EmployeeSearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/EmployeeSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..eaf59d6 --- /dev/null +++ b/src/test/java/org/zdar/repository/search/EmployeeSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link EmployeeSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class EmployeeSearchRepositoryMockConfiguration { + + @MockBean + private EmployeeSearchRepository mockEmployeeSearchRepository; + +} diff --git a/src/test/java/org/zdar/repository/search/JobHistorySearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/JobHistorySearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..23f00c1 --- /dev/null +++ b/src/test/java/org/zdar/repository/search/JobHistorySearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link JobHistorySearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class JobHistorySearchRepositoryMockConfiguration { + + @MockBean + private JobHistorySearchRepository mockJobHistorySearchRepository; + +} diff --git a/src/test/java/org/zdar/repository/search/JobSearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/JobSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..4c7a434 --- /dev/null +++ b/src/test/java/org/zdar/repository/search/JobSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link JobSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class JobSearchRepositoryMockConfiguration { + + @MockBean + private JobSearchRepository mockJobSearchRepository; + +} diff --git a/src/test/java/org/zdar/repository/search/LocationSearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/LocationSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..371754c --- /dev/null +++ b/src/test/java/org/zdar/repository/search/LocationSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link LocationSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class LocationSearchRepositoryMockConfiguration { + + @MockBean + private LocationSearchRepository mockLocationSearchRepository; + +} diff --git a/src/test/java/org/zdar/repository/search/RegionSearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/RegionSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..d0ec938 --- /dev/null +++ b/src/test/java/org/zdar/repository/search/RegionSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link RegionSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class RegionSearchRepositoryMockConfiguration { + + @MockBean + private RegionSearchRepository mockRegionSearchRepository; + +} diff --git a/src/test/java/org/zdar/repository/search/TaskSearchRepositoryMockConfiguration.java b/src/test/java/org/zdar/repository/search/TaskSearchRepositoryMockConfiguration.java new file mode 100644 index 0000000..deaa979 --- /dev/null +++ b/src/test/java/org/zdar/repository/search/TaskSearchRepositoryMockConfiguration.java @@ -0,0 +1,16 @@ +package org.zdar.repository.search; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure a Mock version of {@link TaskSearchRepository} to test the + * application without starting Elasticsearch. + */ +@Configuration +public class TaskSearchRepositoryMockConfiguration { + + @MockBean + private TaskSearchRepository mockTaskSearchRepository; + +} diff --git a/src/test/java/org/zdar/web/rest/CountryResourceIT.java b/src/test/java/org/zdar/web/rest/CountryResourceIT.java new file mode 100644 index 0000000..7fbe2a2 --- /dev/null +++ b/src/test/java/org/zdar/web/rest/CountryResourceIT.java @@ -0,0 +1,330 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.Country; +import org.zdar.repository.CountryRepository; +import org.zdar.repository.search.CountrySearchRepository; +import org.zdar.service.CountryService; +import org.zdar.service.dto.CountryDTO; +import org.zdar.service.mapper.CountryMapper; +import org.zdar.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.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 org.zdar.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 CountryResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class CountryResourceIT { + + private static final String DEFAULT_COUNTRY_NAME = "AAAAAAAAAA"; + private static final String UPDATED_COUNTRY_NAME = "BBBBBBBBBB"; + + @Autowired + private CountryRepository countryRepository; + + @Autowired + private CountryMapper countryMapper; + + @Autowired + private CountryService countryService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.CountrySearchRepositoryMockConfiguration + */ + @Autowired + private CountrySearchRepository mockCountrySearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restCountryMockMvc; + + private Country country; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final CountryResource countryResource = new CountryResource(countryService); + this.restCountryMockMvc = MockMvcBuilders.standaloneSetup(countryResource) + .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 Country createEntity(EntityManager em) { + Country country = new Country() + .countryName(DEFAULT_COUNTRY_NAME); + return country; + } + /** + * 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 Country createUpdatedEntity(EntityManager em) { + Country country = new Country() + .countryName(UPDATED_COUNTRY_NAME); + return country; + } + + @BeforeEach + public void initTest() { + country = createEntity(em); + } + + @Test + @Transactional + public void createCountry() throws Exception { + int databaseSizeBeforeCreate = countryRepository.findAll().size(); + + // Create the Country + CountryDTO countryDTO = countryMapper.toDto(country); + restCountryMockMvc.perform(post("/api/countries") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(countryDTO))) + .andExpect(status().isCreated()); + + // Validate the Country in the database + List countryList = countryRepository.findAll(); + assertThat(countryList).hasSize(databaseSizeBeforeCreate + 1); + Country testCountry = countryList.get(countryList.size() - 1); + assertThat(testCountry.getCountryName()).isEqualTo(DEFAULT_COUNTRY_NAME); + + // Validate the Country in Elasticsearch + verify(mockCountrySearchRepository, times(1)).save(testCountry); + } + + @Test + @Transactional + public void createCountryWithExistingId() throws Exception { + int databaseSizeBeforeCreate = countryRepository.findAll().size(); + + // Create the Country with an existing ID + country.setId(1L); + CountryDTO countryDTO = countryMapper.toDto(country); + + // An entity with an existing ID cannot be created, so this API call must fail + restCountryMockMvc.perform(post("/api/countries") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(countryDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Country in the database + List countryList = countryRepository.findAll(); + assertThat(countryList).hasSize(databaseSizeBeforeCreate); + + // Validate the Country in Elasticsearch + verify(mockCountrySearchRepository, times(0)).save(country); + } + + + @Test + @Transactional + public void getAllCountries() throws Exception { + // Initialize the database + countryRepository.saveAndFlush(country); + + // Get all the countryList + restCountryMockMvc.perform(get("/api/countries?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(country.getId().intValue()))) + .andExpect(jsonPath("$.[*].countryName").value(hasItem(DEFAULT_COUNTRY_NAME.toString()))); + } + + @Test + @Transactional + public void getCountry() throws Exception { + // Initialize the database + countryRepository.saveAndFlush(country); + + // Get the country + restCountryMockMvc.perform(get("/api/countries/{id}", country.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(country.getId().intValue())) + .andExpect(jsonPath("$.countryName").value(DEFAULT_COUNTRY_NAME.toString())); + } + + @Test + @Transactional + public void getNonExistingCountry() throws Exception { + // Get the country + restCountryMockMvc.perform(get("/api/countries/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateCountry() throws Exception { + // Initialize the database + countryRepository.saveAndFlush(country); + + int databaseSizeBeforeUpdate = countryRepository.findAll().size(); + + // Update the country + Country updatedCountry = countryRepository.findById(country.getId()).get(); + // Disconnect from session so that the updates on updatedCountry are not directly saved in db + em.detach(updatedCountry); + updatedCountry + .countryName(UPDATED_COUNTRY_NAME); + CountryDTO countryDTO = countryMapper.toDto(updatedCountry); + + restCountryMockMvc.perform(put("/api/countries") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(countryDTO))) + .andExpect(status().isOk()); + + // Validate the Country in the database + List countryList = countryRepository.findAll(); + assertThat(countryList).hasSize(databaseSizeBeforeUpdate); + Country testCountry = countryList.get(countryList.size() - 1); + assertThat(testCountry.getCountryName()).isEqualTo(UPDATED_COUNTRY_NAME); + + // Validate the Country in Elasticsearch + verify(mockCountrySearchRepository, times(1)).save(testCountry); + } + + @Test + @Transactional + public void updateNonExistingCountry() throws Exception { + int databaseSizeBeforeUpdate = countryRepository.findAll().size(); + + // Create the Country + CountryDTO countryDTO = countryMapper.toDto(country); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restCountryMockMvc.perform(put("/api/countries") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(countryDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Country in the database + List countryList = countryRepository.findAll(); + assertThat(countryList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Country in Elasticsearch + verify(mockCountrySearchRepository, times(0)).save(country); + } + + @Test + @Transactional + public void deleteCountry() throws Exception { + // Initialize the database + countryRepository.saveAndFlush(country); + + int databaseSizeBeforeDelete = countryRepository.findAll().size(); + + // Delete the country + restCountryMockMvc.perform(delete("/api/countries/{id}", country.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List countryList = countryRepository.findAll(); + assertThat(countryList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Country in Elasticsearch + verify(mockCountrySearchRepository, times(1)).deleteById(country.getId()); + } + + @Test + @Transactional + public void searchCountry() throws Exception { + // Initialize the database + countryRepository.saveAndFlush(country); + when(mockCountrySearchRepository.search(queryStringQuery("id:" + country.getId()))) + .thenReturn(Collections.singletonList(country)); + // Search the country + restCountryMockMvc.perform(get("/api/_search/countries?query=id:" + country.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(country.getId().intValue()))) + .andExpect(jsonPath("$.[*].countryName").value(hasItem(DEFAULT_COUNTRY_NAME))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Country.class); + Country country1 = new Country(); + country1.setId(1L); + Country country2 = new Country(); + country2.setId(country1.getId()); + assertThat(country1).isEqualTo(country2); + country2.setId(2L); + assertThat(country1).isNotEqualTo(country2); + country1.setId(null); + assertThat(country1).isNotEqualTo(country2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(CountryDTO.class); + CountryDTO countryDTO1 = new CountryDTO(); + countryDTO1.setId(1L); + CountryDTO countryDTO2 = new CountryDTO(); + assertThat(countryDTO1).isNotEqualTo(countryDTO2); + countryDTO2.setId(countryDTO1.getId()); + assertThat(countryDTO1).isEqualTo(countryDTO2); + countryDTO2.setId(2L); + assertThat(countryDTO1).isNotEqualTo(countryDTO2); + countryDTO1.setId(null); + assertThat(countryDTO1).isNotEqualTo(countryDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(countryMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(countryMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/org/zdar/web/rest/DepartmentResourceIT.java b/src/test/java/org/zdar/web/rest/DepartmentResourceIT.java new file mode 100644 index 0000000..6fc818d --- /dev/null +++ b/src/test/java/org/zdar/web/rest/DepartmentResourceIT.java @@ -0,0 +1,349 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.Department; +import org.zdar.repository.DepartmentRepository; +import org.zdar.repository.search.DepartmentSearchRepository; +import org.zdar.service.DepartmentService; +import org.zdar.service.dto.DepartmentDTO; +import org.zdar.service.mapper.DepartmentMapper; +import org.zdar.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.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 org.zdar.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 DepartmentResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class DepartmentResourceIT { + + private static final String DEFAULT_DEPARTMENT_NAME = "AAAAAAAAAA"; + private static final String UPDATED_DEPARTMENT_NAME = "BBBBBBBBBB"; + + @Autowired + private DepartmentRepository departmentRepository; + + @Autowired + private DepartmentMapper departmentMapper; + + @Autowired + private DepartmentService departmentService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.DepartmentSearchRepositoryMockConfiguration + */ + @Autowired + private DepartmentSearchRepository mockDepartmentSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restDepartmentMockMvc; + + private Department department; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final DepartmentResource departmentResource = new DepartmentResource(departmentService); + this.restDepartmentMockMvc = MockMvcBuilders.standaloneSetup(departmentResource) + .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 Department createEntity(EntityManager em) { + Department department = new Department() + .departmentName(DEFAULT_DEPARTMENT_NAME); + return department; + } + /** + * 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 Department createUpdatedEntity(EntityManager em) { + Department department = new Department() + .departmentName(UPDATED_DEPARTMENT_NAME); + return department; + } + + @BeforeEach + public void initTest() { + department = createEntity(em); + } + + @Test + @Transactional + public void createDepartment() throws Exception { + int databaseSizeBeforeCreate = departmentRepository.findAll().size(); + + // Create the Department + DepartmentDTO departmentDTO = departmentMapper.toDto(department); + restDepartmentMockMvc.perform(post("/api/departments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(departmentDTO))) + .andExpect(status().isCreated()); + + // Validate the Department in the database + List departmentList = departmentRepository.findAll(); + assertThat(departmentList).hasSize(databaseSizeBeforeCreate + 1); + Department testDepartment = departmentList.get(departmentList.size() - 1); + assertThat(testDepartment.getDepartmentName()).isEqualTo(DEFAULT_DEPARTMENT_NAME); + + // Validate the Department in Elasticsearch + verify(mockDepartmentSearchRepository, times(1)).save(testDepartment); + } + + @Test + @Transactional + public void createDepartmentWithExistingId() throws Exception { + int databaseSizeBeforeCreate = departmentRepository.findAll().size(); + + // Create the Department with an existing ID + department.setId(1L); + DepartmentDTO departmentDTO = departmentMapper.toDto(department); + + // An entity with an existing ID cannot be created, so this API call must fail + restDepartmentMockMvc.perform(post("/api/departments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(departmentDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Department in the database + List departmentList = departmentRepository.findAll(); + assertThat(departmentList).hasSize(databaseSizeBeforeCreate); + + // Validate the Department in Elasticsearch + verify(mockDepartmentSearchRepository, times(0)).save(department); + } + + + @Test + @Transactional + public void checkDepartmentNameIsRequired() throws Exception { + int databaseSizeBeforeTest = departmentRepository.findAll().size(); + // set the field null + department.setDepartmentName(null); + + // Create the Department, which fails. + DepartmentDTO departmentDTO = departmentMapper.toDto(department); + + restDepartmentMockMvc.perform(post("/api/departments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(departmentDTO))) + .andExpect(status().isBadRequest()); + + List departmentList = departmentRepository.findAll(); + assertThat(departmentList).hasSize(databaseSizeBeforeTest); + } + + @Test + @Transactional + public void getAllDepartments() throws Exception { + // Initialize the database + departmentRepository.saveAndFlush(department); + + // Get all the departmentList + restDepartmentMockMvc.perform(get("/api/departments?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(department.getId().intValue()))) + .andExpect(jsonPath("$.[*].departmentName").value(hasItem(DEFAULT_DEPARTMENT_NAME.toString()))); + } + + @Test + @Transactional + public void getDepartment() throws Exception { + // Initialize the database + departmentRepository.saveAndFlush(department); + + // Get the department + restDepartmentMockMvc.perform(get("/api/departments/{id}", department.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(department.getId().intValue())) + .andExpect(jsonPath("$.departmentName").value(DEFAULT_DEPARTMENT_NAME.toString())); + } + + @Test + @Transactional + public void getNonExistingDepartment() throws Exception { + // Get the department + restDepartmentMockMvc.perform(get("/api/departments/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateDepartment() throws Exception { + // Initialize the database + departmentRepository.saveAndFlush(department); + + int databaseSizeBeforeUpdate = departmentRepository.findAll().size(); + + // Update the department + Department updatedDepartment = departmentRepository.findById(department.getId()).get(); + // Disconnect from session so that the updates on updatedDepartment are not directly saved in db + em.detach(updatedDepartment); + updatedDepartment + .departmentName(UPDATED_DEPARTMENT_NAME); + DepartmentDTO departmentDTO = departmentMapper.toDto(updatedDepartment); + + restDepartmentMockMvc.perform(put("/api/departments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(departmentDTO))) + .andExpect(status().isOk()); + + // Validate the Department in the database + List departmentList = departmentRepository.findAll(); + assertThat(departmentList).hasSize(databaseSizeBeforeUpdate); + Department testDepartment = departmentList.get(departmentList.size() - 1); + assertThat(testDepartment.getDepartmentName()).isEqualTo(UPDATED_DEPARTMENT_NAME); + + // Validate the Department in Elasticsearch + verify(mockDepartmentSearchRepository, times(1)).save(testDepartment); + } + + @Test + @Transactional + public void updateNonExistingDepartment() throws Exception { + int databaseSizeBeforeUpdate = departmentRepository.findAll().size(); + + // Create the Department + DepartmentDTO departmentDTO = departmentMapper.toDto(department); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restDepartmentMockMvc.perform(put("/api/departments") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(departmentDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Department in the database + List departmentList = departmentRepository.findAll(); + assertThat(departmentList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Department in Elasticsearch + verify(mockDepartmentSearchRepository, times(0)).save(department); + } + + @Test + @Transactional + public void deleteDepartment() throws Exception { + // Initialize the database + departmentRepository.saveAndFlush(department); + + int databaseSizeBeforeDelete = departmentRepository.findAll().size(); + + // Delete the department + restDepartmentMockMvc.perform(delete("/api/departments/{id}", department.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List departmentList = departmentRepository.findAll(); + assertThat(departmentList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Department in Elasticsearch + verify(mockDepartmentSearchRepository, times(1)).deleteById(department.getId()); + } + + @Test + @Transactional + public void searchDepartment() throws Exception { + // Initialize the database + departmentRepository.saveAndFlush(department); + when(mockDepartmentSearchRepository.search(queryStringQuery("id:" + department.getId()))) + .thenReturn(Collections.singletonList(department)); + // Search the department + restDepartmentMockMvc.perform(get("/api/_search/departments?query=id:" + department.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(department.getId().intValue()))) + .andExpect(jsonPath("$.[*].departmentName").value(hasItem(DEFAULT_DEPARTMENT_NAME))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Department.class); + Department department1 = new Department(); + department1.setId(1L); + Department department2 = new Department(); + department2.setId(department1.getId()); + assertThat(department1).isEqualTo(department2); + department2.setId(2L); + assertThat(department1).isNotEqualTo(department2); + department1.setId(null); + assertThat(department1).isNotEqualTo(department2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(DepartmentDTO.class); + DepartmentDTO departmentDTO1 = new DepartmentDTO(); + departmentDTO1.setId(1L); + DepartmentDTO departmentDTO2 = new DepartmentDTO(); + assertThat(departmentDTO1).isNotEqualTo(departmentDTO2); + departmentDTO2.setId(departmentDTO1.getId()); + assertThat(departmentDTO1).isEqualTo(departmentDTO2); + departmentDTO2.setId(2L); + assertThat(departmentDTO1).isNotEqualTo(departmentDTO2); + departmentDTO1.setId(null); + assertThat(departmentDTO1).isNotEqualTo(departmentDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(departmentMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(departmentMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/org/zdar/web/rest/EmployeeResourceIT.java b/src/test/java/org/zdar/web/rest/EmployeeResourceIT.java new file mode 100644 index 0000000..49e8764 --- /dev/null +++ b/src/test/java/org/zdar/web/rest/EmployeeResourceIT.java @@ -0,0 +1,400 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.Employee; +import org.zdar.repository.EmployeeRepository; +import org.zdar.repository.search.EmployeeSearchRepository; +import org.zdar.service.EmployeeService; +import org.zdar.service.dto.EmployeeDTO; +import org.zdar.service.mapper.EmployeeMapper; +import org.zdar.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.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.List; + +import static org.zdar.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 EmployeeResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class EmployeeResourceIT { + + private static final String DEFAULT_FIRST_NAME = "AAAAAAAAAA"; + private static final String UPDATED_FIRST_NAME = "BBBBBBBBBB"; + + private static final String DEFAULT_LAST_NAME = "AAAAAAAAAA"; + private static final String UPDATED_LAST_NAME = "BBBBBBBBBB"; + + private static final String DEFAULT_EMAIL = "AAAAAAAAAA"; + private static final String UPDATED_EMAIL = "BBBBBBBBBB"; + + private static final String DEFAULT_PHONE_NUMBER = "AAAAAAAAAA"; + private static final String UPDATED_PHONE_NUMBER = "BBBBBBBBBB"; + + private static final Instant DEFAULT_HIRE_DATE = Instant.ofEpochMilli(0L); + private static final Instant UPDATED_HIRE_DATE = Instant.now().truncatedTo(ChronoUnit.MILLIS); + + private static final Long DEFAULT_SALARY = 1L; + private static final Long UPDATED_SALARY = 2L; + + private static final Long DEFAULT_COMMISSION_PCT = 1L; + private static final Long UPDATED_COMMISSION_PCT = 2L; + + @Autowired + private EmployeeRepository employeeRepository; + + @Autowired + private EmployeeMapper employeeMapper; + + @Autowired + private EmployeeService employeeService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.EmployeeSearchRepositoryMockConfiguration + */ + @Autowired + private EmployeeSearchRepository mockEmployeeSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restEmployeeMockMvc; + + private Employee employee; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final EmployeeResource employeeResource = new EmployeeResource(employeeService); + this.restEmployeeMockMvc = MockMvcBuilders.standaloneSetup(employeeResource) + .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 Employee createEntity(EntityManager em) { + Employee employee = new Employee() + .firstName(DEFAULT_FIRST_NAME) + .lastName(DEFAULT_LAST_NAME) + .email(DEFAULT_EMAIL) + .phoneNumber(DEFAULT_PHONE_NUMBER) + .hireDate(DEFAULT_HIRE_DATE) + .salary(DEFAULT_SALARY) + .commissionPct(DEFAULT_COMMISSION_PCT); + return employee; + } + /** + * 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 Employee createUpdatedEntity(EntityManager em) { + Employee employee = new Employee() + .firstName(UPDATED_FIRST_NAME) + .lastName(UPDATED_LAST_NAME) + .email(UPDATED_EMAIL) + .phoneNumber(UPDATED_PHONE_NUMBER) + .hireDate(UPDATED_HIRE_DATE) + .salary(UPDATED_SALARY) + .commissionPct(UPDATED_COMMISSION_PCT); + return employee; + } + + @BeforeEach + public void initTest() { + employee = createEntity(em); + } + + @Test + @Transactional + public void createEmployee() throws Exception { + int databaseSizeBeforeCreate = employeeRepository.findAll().size(); + + // Create the Employee + EmployeeDTO employeeDTO = employeeMapper.toDto(employee); + restEmployeeMockMvc.perform(post("/api/employees") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(employeeDTO))) + .andExpect(status().isCreated()); + + // Validate the Employee in the database + List employeeList = employeeRepository.findAll(); + assertThat(employeeList).hasSize(databaseSizeBeforeCreate + 1); + Employee testEmployee = employeeList.get(employeeList.size() - 1); + assertThat(testEmployee.getFirstName()).isEqualTo(DEFAULT_FIRST_NAME); + assertThat(testEmployee.getLastName()).isEqualTo(DEFAULT_LAST_NAME); + assertThat(testEmployee.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(testEmployee.getPhoneNumber()).isEqualTo(DEFAULT_PHONE_NUMBER); + assertThat(testEmployee.getHireDate()).isEqualTo(DEFAULT_HIRE_DATE); + assertThat(testEmployee.getSalary()).isEqualTo(DEFAULT_SALARY); + assertThat(testEmployee.getCommissionPct()).isEqualTo(DEFAULT_COMMISSION_PCT); + + // Validate the Employee in Elasticsearch + verify(mockEmployeeSearchRepository, times(1)).save(testEmployee); + } + + @Test + @Transactional + public void createEmployeeWithExistingId() throws Exception { + int databaseSizeBeforeCreate = employeeRepository.findAll().size(); + + // Create the Employee with an existing ID + employee.setId(1L); + EmployeeDTO employeeDTO = employeeMapper.toDto(employee); + + // An entity with an existing ID cannot be created, so this API call must fail + restEmployeeMockMvc.perform(post("/api/employees") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(employeeDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Employee in the database + List employeeList = employeeRepository.findAll(); + assertThat(employeeList).hasSize(databaseSizeBeforeCreate); + + // Validate the Employee in Elasticsearch + verify(mockEmployeeSearchRepository, times(0)).save(employee); + } + + + @Test + @Transactional + public void getAllEmployees() throws Exception { + // Initialize the database + employeeRepository.saveAndFlush(employee); + + // Get all the employeeList + restEmployeeMockMvc.perform(get("/api/employees?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(employee.getId().intValue()))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRST_NAME.toString()))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME.toString()))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL.toString()))) + .andExpect(jsonPath("$.[*].phoneNumber").value(hasItem(DEFAULT_PHONE_NUMBER.toString()))) + .andExpect(jsonPath("$.[*].hireDate").value(hasItem(DEFAULT_HIRE_DATE.toString()))) + .andExpect(jsonPath("$.[*].salary").value(hasItem(DEFAULT_SALARY.intValue()))) + .andExpect(jsonPath("$.[*].commissionPct").value(hasItem(DEFAULT_COMMISSION_PCT.intValue()))); + } + + @Test + @Transactional + public void getEmployee() throws Exception { + // Initialize the database + employeeRepository.saveAndFlush(employee); + + // Get the employee + restEmployeeMockMvc.perform(get("/api/employees/{id}", employee.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(employee.getId().intValue())) + .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRST_NAME.toString())) + .andExpect(jsonPath("$.lastName").value(DEFAULT_LAST_NAME.toString())) + .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL.toString())) + .andExpect(jsonPath("$.phoneNumber").value(DEFAULT_PHONE_NUMBER.toString())) + .andExpect(jsonPath("$.hireDate").value(DEFAULT_HIRE_DATE.toString())) + .andExpect(jsonPath("$.salary").value(DEFAULT_SALARY.intValue())) + .andExpect(jsonPath("$.commissionPct").value(DEFAULT_COMMISSION_PCT.intValue())); + } + + @Test + @Transactional + public void getNonExistingEmployee() throws Exception { + // Get the employee + restEmployeeMockMvc.perform(get("/api/employees/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateEmployee() throws Exception { + // Initialize the database + employeeRepository.saveAndFlush(employee); + + int databaseSizeBeforeUpdate = employeeRepository.findAll().size(); + + // Update the employee + Employee updatedEmployee = employeeRepository.findById(employee.getId()).get(); + // Disconnect from session so that the updates on updatedEmployee are not directly saved in db + em.detach(updatedEmployee); + updatedEmployee + .firstName(UPDATED_FIRST_NAME) + .lastName(UPDATED_LAST_NAME) + .email(UPDATED_EMAIL) + .phoneNumber(UPDATED_PHONE_NUMBER) + .hireDate(UPDATED_HIRE_DATE) + .salary(UPDATED_SALARY) + .commissionPct(UPDATED_COMMISSION_PCT); + EmployeeDTO employeeDTO = employeeMapper.toDto(updatedEmployee); + + restEmployeeMockMvc.perform(put("/api/employees") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(employeeDTO))) + .andExpect(status().isOk()); + + // Validate the Employee in the database + List employeeList = employeeRepository.findAll(); + assertThat(employeeList).hasSize(databaseSizeBeforeUpdate); + Employee testEmployee = employeeList.get(employeeList.size() - 1); + assertThat(testEmployee.getFirstName()).isEqualTo(UPDATED_FIRST_NAME); + assertThat(testEmployee.getLastName()).isEqualTo(UPDATED_LAST_NAME); + assertThat(testEmployee.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testEmployee.getPhoneNumber()).isEqualTo(UPDATED_PHONE_NUMBER); + assertThat(testEmployee.getHireDate()).isEqualTo(UPDATED_HIRE_DATE); + assertThat(testEmployee.getSalary()).isEqualTo(UPDATED_SALARY); + assertThat(testEmployee.getCommissionPct()).isEqualTo(UPDATED_COMMISSION_PCT); + + // Validate the Employee in Elasticsearch + verify(mockEmployeeSearchRepository, times(1)).save(testEmployee); + } + + @Test + @Transactional + public void updateNonExistingEmployee() throws Exception { + int databaseSizeBeforeUpdate = employeeRepository.findAll().size(); + + // Create the Employee + EmployeeDTO employeeDTO = employeeMapper.toDto(employee); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restEmployeeMockMvc.perform(put("/api/employees") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(employeeDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Employee in the database + List employeeList = employeeRepository.findAll(); + assertThat(employeeList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Employee in Elasticsearch + verify(mockEmployeeSearchRepository, times(0)).save(employee); + } + + @Test + @Transactional + public void deleteEmployee() throws Exception { + // Initialize the database + employeeRepository.saveAndFlush(employee); + + int databaseSizeBeforeDelete = employeeRepository.findAll().size(); + + // Delete the employee + restEmployeeMockMvc.perform(delete("/api/employees/{id}", employee.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List employeeList = employeeRepository.findAll(); + assertThat(employeeList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Employee in Elasticsearch + verify(mockEmployeeSearchRepository, times(1)).deleteById(employee.getId()); + } + + @Test + @Transactional + public void searchEmployee() throws Exception { + // Initialize the database + employeeRepository.saveAndFlush(employee); + when(mockEmployeeSearchRepository.search(queryStringQuery("id:" + employee.getId()), PageRequest.of(0, 20))) + .thenReturn(new PageImpl<>(Collections.singletonList(employee), PageRequest.of(0, 1), 1)); + // Search the employee + restEmployeeMockMvc.perform(get("/api/_search/employees?query=id:" + employee.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(employee.getId().intValue()))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRST_NAME))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) + .andExpect(jsonPath("$.[*].phoneNumber").value(hasItem(DEFAULT_PHONE_NUMBER))) + .andExpect(jsonPath("$.[*].hireDate").value(hasItem(DEFAULT_HIRE_DATE.toString()))) + .andExpect(jsonPath("$.[*].salary").value(hasItem(DEFAULT_SALARY.intValue()))) + .andExpect(jsonPath("$.[*].commissionPct").value(hasItem(DEFAULT_COMMISSION_PCT.intValue()))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Employee.class); + Employee employee1 = new Employee(); + employee1.setId(1L); + Employee employee2 = new Employee(); + employee2.setId(employee1.getId()); + assertThat(employee1).isEqualTo(employee2); + employee2.setId(2L); + assertThat(employee1).isNotEqualTo(employee2); + employee1.setId(null); + assertThat(employee1).isNotEqualTo(employee2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(EmployeeDTO.class); + EmployeeDTO employeeDTO1 = new EmployeeDTO(); + employeeDTO1.setId(1L); + EmployeeDTO employeeDTO2 = new EmployeeDTO(); + assertThat(employeeDTO1).isNotEqualTo(employeeDTO2); + employeeDTO2.setId(employeeDTO1.getId()); + assertThat(employeeDTO1).isEqualTo(employeeDTO2); + employeeDTO2.setId(2L); + assertThat(employeeDTO1).isNotEqualTo(employeeDTO2); + employeeDTO1.setId(null); + assertThat(employeeDTO1).isNotEqualTo(employeeDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(employeeMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(employeeMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/org/zdar/web/rest/JobHistoryResourceIT.java b/src/test/java/org/zdar/web/rest/JobHistoryResourceIT.java new file mode 100644 index 0000000..ad5c681 --- /dev/null +++ b/src/test/java/org/zdar/web/rest/JobHistoryResourceIT.java @@ -0,0 +1,357 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.JobHistory; +import org.zdar.repository.JobHistoryRepository; +import org.zdar.repository.search.JobHistorySearchRepository; +import org.zdar.service.JobHistoryService; +import org.zdar.service.dto.JobHistoryDTO; +import org.zdar.service.mapper.JobHistoryMapper; +import org.zdar.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.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.List; + +import static org.zdar.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.*; + +import org.zdar.domain.enumeration.Language; +/** + * Integration tests for the {@Link JobHistoryResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class JobHistoryResourceIT { + + private static final Instant DEFAULT_START_DATE = Instant.ofEpochMilli(0L); + private static final Instant UPDATED_START_DATE = Instant.now().truncatedTo(ChronoUnit.MILLIS); + + private static final Instant DEFAULT_END_DATE = Instant.ofEpochMilli(0L); + private static final Instant UPDATED_END_DATE = Instant.now().truncatedTo(ChronoUnit.MILLIS); + + private static final Language DEFAULT_LANGUAGE = Language.FRENCH; + private static final Language UPDATED_LANGUAGE = Language.ENGLISH; + + @Autowired + private JobHistoryRepository jobHistoryRepository; + + @Autowired + private JobHistoryMapper jobHistoryMapper; + + @Autowired + private JobHistoryService jobHistoryService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.JobHistorySearchRepositoryMockConfiguration + */ + @Autowired + private JobHistorySearchRepository mockJobHistorySearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restJobHistoryMockMvc; + + private JobHistory jobHistory; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final JobHistoryResource jobHistoryResource = new JobHistoryResource(jobHistoryService); + this.restJobHistoryMockMvc = MockMvcBuilders.standaloneSetup(jobHistoryResource) + .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 JobHistory createEntity(EntityManager em) { + JobHistory jobHistory = new JobHistory() + .startDate(DEFAULT_START_DATE) + .endDate(DEFAULT_END_DATE) + .language(DEFAULT_LANGUAGE); + return jobHistory; + } + /** + * 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 JobHistory createUpdatedEntity(EntityManager em) { + JobHistory jobHistory = new JobHistory() + .startDate(UPDATED_START_DATE) + .endDate(UPDATED_END_DATE) + .language(UPDATED_LANGUAGE); + return jobHistory; + } + + @BeforeEach + public void initTest() { + jobHistory = createEntity(em); + } + + @Test + @Transactional + public void createJobHistory() throws Exception { + int databaseSizeBeforeCreate = jobHistoryRepository.findAll().size(); + + // Create the JobHistory + JobHistoryDTO jobHistoryDTO = jobHistoryMapper.toDto(jobHistory); + restJobHistoryMockMvc.perform(post("/api/job-histories") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobHistoryDTO))) + .andExpect(status().isCreated()); + + // Validate the JobHistory in the database + List jobHistoryList = jobHistoryRepository.findAll(); + assertThat(jobHistoryList).hasSize(databaseSizeBeforeCreate + 1); + JobHistory testJobHistory = jobHistoryList.get(jobHistoryList.size() - 1); + assertThat(testJobHistory.getStartDate()).isEqualTo(DEFAULT_START_DATE); + assertThat(testJobHistory.getEndDate()).isEqualTo(DEFAULT_END_DATE); + assertThat(testJobHistory.getLanguage()).isEqualTo(DEFAULT_LANGUAGE); + + // Validate the JobHistory in Elasticsearch + verify(mockJobHistorySearchRepository, times(1)).save(testJobHistory); + } + + @Test + @Transactional + public void createJobHistoryWithExistingId() throws Exception { + int databaseSizeBeforeCreate = jobHistoryRepository.findAll().size(); + + // Create the JobHistory with an existing ID + jobHistory.setId(1L); + JobHistoryDTO jobHistoryDTO = jobHistoryMapper.toDto(jobHistory); + + // An entity with an existing ID cannot be created, so this API call must fail + restJobHistoryMockMvc.perform(post("/api/job-histories") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobHistoryDTO))) + .andExpect(status().isBadRequest()); + + // Validate the JobHistory in the database + List jobHistoryList = jobHistoryRepository.findAll(); + assertThat(jobHistoryList).hasSize(databaseSizeBeforeCreate); + + // Validate the JobHistory in Elasticsearch + verify(mockJobHistorySearchRepository, times(0)).save(jobHistory); + } + + + @Test + @Transactional + public void getAllJobHistories() throws Exception { + // Initialize the database + jobHistoryRepository.saveAndFlush(jobHistory); + + // Get all the jobHistoryList + restJobHistoryMockMvc.perform(get("/api/job-histories?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(jobHistory.getId().intValue()))) + .andExpect(jsonPath("$.[*].startDate").value(hasItem(DEFAULT_START_DATE.toString()))) + .andExpect(jsonPath("$.[*].endDate").value(hasItem(DEFAULT_END_DATE.toString()))) + .andExpect(jsonPath("$.[*].language").value(hasItem(DEFAULT_LANGUAGE.toString()))); + } + + @Test + @Transactional + public void getJobHistory() throws Exception { + // Initialize the database + jobHistoryRepository.saveAndFlush(jobHistory); + + // Get the jobHistory + restJobHistoryMockMvc.perform(get("/api/job-histories/{id}", jobHistory.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(jobHistory.getId().intValue())) + .andExpect(jsonPath("$.startDate").value(DEFAULT_START_DATE.toString())) + .andExpect(jsonPath("$.endDate").value(DEFAULT_END_DATE.toString())) + .andExpect(jsonPath("$.language").value(DEFAULT_LANGUAGE.toString())); + } + + @Test + @Transactional + public void getNonExistingJobHistory() throws Exception { + // Get the jobHistory + restJobHistoryMockMvc.perform(get("/api/job-histories/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateJobHistory() throws Exception { + // Initialize the database + jobHistoryRepository.saveAndFlush(jobHistory); + + int databaseSizeBeforeUpdate = jobHistoryRepository.findAll().size(); + + // Update the jobHistory + JobHistory updatedJobHistory = jobHistoryRepository.findById(jobHistory.getId()).get(); + // Disconnect from session so that the updates on updatedJobHistory are not directly saved in db + em.detach(updatedJobHistory); + updatedJobHistory + .startDate(UPDATED_START_DATE) + .endDate(UPDATED_END_DATE) + .language(UPDATED_LANGUAGE); + JobHistoryDTO jobHistoryDTO = jobHistoryMapper.toDto(updatedJobHistory); + + restJobHistoryMockMvc.perform(put("/api/job-histories") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobHistoryDTO))) + .andExpect(status().isOk()); + + // Validate the JobHistory in the database + List jobHistoryList = jobHistoryRepository.findAll(); + assertThat(jobHistoryList).hasSize(databaseSizeBeforeUpdate); + JobHistory testJobHistory = jobHistoryList.get(jobHistoryList.size() - 1); + assertThat(testJobHistory.getStartDate()).isEqualTo(UPDATED_START_DATE); + assertThat(testJobHistory.getEndDate()).isEqualTo(UPDATED_END_DATE); + assertThat(testJobHistory.getLanguage()).isEqualTo(UPDATED_LANGUAGE); + + // Validate the JobHistory in Elasticsearch + verify(mockJobHistorySearchRepository, times(1)).save(testJobHistory); + } + + @Test + @Transactional + public void updateNonExistingJobHistory() throws Exception { + int databaseSizeBeforeUpdate = jobHistoryRepository.findAll().size(); + + // Create the JobHistory + JobHistoryDTO jobHistoryDTO = jobHistoryMapper.toDto(jobHistory); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restJobHistoryMockMvc.perform(put("/api/job-histories") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobHistoryDTO))) + .andExpect(status().isBadRequest()); + + // Validate the JobHistory in the database + List jobHistoryList = jobHistoryRepository.findAll(); + assertThat(jobHistoryList).hasSize(databaseSizeBeforeUpdate); + + // Validate the JobHistory in Elasticsearch + verify(mockJobHistorySearchRepository, times(0)).save(jobHistory); + } + + @Test + @Transactional + public void deleteJobHistory() throws Exception { + // Initialize the database + jobHistoryRepository.saveAndFlush(jobHistory); + + int databaseSizeBeforeDelete = jobHistoryRepository.findAll().size(); + + // Delete the jobHistory + restJobHistoryMockMvc.perform(delete("/api/job-histories/{id}", jobHistory.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List jobHistoryList = jobHistoryRepository.findAll(); + assertThat(jobHistoryList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the JobHistory in Elasticsearch + verify(mockJobHistorySearchRepository, times(1)).deleteById(jobHistory.getId()); + } + + @Test + @Transactional + public void searchJobHistory() throws Exception { + // Initialize the database + jobHistoryRepository.saveAndFlush(jobHistory); + when(mockJobHistorySearchRepository.search(queryStringQuery("id:" + jobHistory.getId()), PageRequest.of(0, 20))) + .thenReturn(new PageImpl<>(Collections.singletonList(jobHistory), PageRequest.of(0, 1), 1)); + // Search the jobHistory + restJobHistoryMockMvc.perform(get("/api/_search/job-histories?query=id:" + jobHistory.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(jobHistory.getId().intValue()))) + .andExpect(jsonPath("$.[*].startDate").value(hasItem(DEFAULT_START_DATE.toString()))) + .andExpect(jsonPath("$.[*].endDate").value(hasItem(DEFAULT_END_DATE.toString()))) + .andExpect(jsonPath("$.[*].language").value(hasItem(DEFAULT_LANGUAGE.toString()))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(JobHistory.class); + JobHistory jobHistory1 = new JobHistory(); + jobHistory1.setId(1L); + JobHistory jobHistory2 = new JobHistory(); + jobHistory2.setId(jobHistory1.getId()); + assertThat(jobHistory1).isEqualTo(jobHistory2); + jobHistory2.setId(2L); + assertThat(jobHistory1).isNotEqualTo(jobHistory2); + jobHistory1.setId(null); + assertThat(jobHistory1).isNotEqualTo(jobHistory2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(JobHistoryDTO.class); + JobHistoryDTO jobHistoryDTO1 = new JobHistoryDTO(); + jobHistoryDTO1.setId(1L); + JobHistoryDTO jobHistoryDTO2 = new JobHistoryDTO(); + assertThat(jobHistoryDTO1).isNotEqualTo(jobHistoryDTO2); + jobHistoryDTO2.setId(jobHistoryDTO1.getId()); + assertThat(jobHistoryDTO1).isEqualTo(jobHistoryDTO2); + jobHistoryDTO2.setId(2L); + assertThat(jobHistoryDTO1).isNotEqualTo(jobHistoryDTO2); + jobHistoryDTO1.setId(null); + assertThat(jobHistoryDTO1).isNotEqualTo(jobHistoryDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(jobHistoryMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(jobHistoryMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/org/zdar/web/rest/JobResourceIT.java b/src/test/java/org/zdar/web/rest/JobResourceIT.java new file mode 100644 index 0000000..2395581 --- /dev/null +++ b/src/test/java/org/zdar/web/rest/JobResourceIT.java @@ -0,0 +1,395 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.Job; +import org.zdar.repository.JobRepository; +import org.zdar.repository.search.JobSearchRepository; +import org.zdar.service.JobService; +import org.zdar.service.dto.JobDTO; +import org.zdar.service.mapper.JobMapper; +import org.zdar.web.rest.errors.ExceptionTranslator; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +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.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.zdar.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 JobResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class JobResourceIT { + + private static final String DEFAULT_JOB_TITLE = "AAAAAAAAAA"; + private static final String UPDATED_JOB_TITLE = "BBBBBBBBBB"; + + private static final Long DEFAULT_MIN_SALARY = 1L; + private static final Long UPDATED_MIN_SALARY = 2L; + + private static final Long DEFAULT_MAX_SALARY = 1L; + private static final Long UPDATED_MAX_SALARY = 2L; + + @Autowired + private JobRepository jobRepository; + + @Mock + private JobRepository jobRepositoryMock; + + @Autowired + private JobMapper jobMapper; + + @Mock + private JobService jobServiceMock; + + @Autowired + private JobService jobService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.JobSearchRepositoryMockConfiguration + */ + @Autowired + private JobSearchRepository mockJobSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restJobMockMvc; + + private Job job; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final JobResource jobResource = new JobResource(jobService); + this.restJobMockMvc = MockMvcBuilders.standaloneSetup(jobResource) + .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 Job createEntity(EntityManager em) { + Job job = new Job() + .jobTitle(DEFAULT_JOB_TITLE) + .minSalary(DEFAULT_MIN_SALARY) + .maxSalary(DEFAULT_MAX_SALARY); + return job; + } + /** + * 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 Job createUpdatedEntity(EntityManager em) { + Job job = new Job() + .jobTitle(UPDATED_JOB_TITLE) + .minSalary(UPDATED_MIN_SALARY) + .maxSalary(UPDATED_MAX_SALARY); + return job; + } + + @BeforeEach + public void initTest() { + job = createEntity(em); + } + + @Test + @Transactional + public void createJob() throws Exception { + int databaseSizeBeforeCreate = jobRepository.findAll().size(); + + // Create the Job + JobDTO jobDTO = jobMapper.toDto(job); + restJobMockMvc.perform(post("/api/jobs") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobDTO))) + .andExpect(status().isCreated()); + + // Validate the Job in the database + List jobList = jobRepository.findAll(); + assertThat(jobList).hasSize(databaseSizeBeforeCreate + 1); + Job testJob = jobList.get(jobList.size() - 1); + assertThat(testJob.getJobTitle()).isEqualTo(DEFAULT_JOB_TITLE); + assertThat(testJob.getMinSalary()).isEqualTo(DEFAULT_MIN_SALARY); + assertThat(testJob.getMaxSalary()).isEqualTo(DEFAULT_MAX_SALARY); + + // Validate the Job in Elasticsearch + verify(mockJobSearchRepository, times(1)).save(testJob); + } + + @Test + @Transactional + public void createJobWithExistingId() throws Exception { + int databaseSizeBeforeCreate = jobRepository.findAll().size(); + + // Create the Job with an existing ID + job.setId(1L); + JobDTO jobDTO = jobMapper.toDto(job); + + // An entity with an existing ID cannot be created, so this API call must fail + restJobMockMvc.perform(post("/api/jobs") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Job in the database + List jobList = jobRepository.findAll(); + assertThat(jobList).hasSize(databaseSizeBeforeCreate); + + // Validate the Job in Elasticsearch + verify(mockJobSearchRepository, times(0)).save(job); + } + + + @Test + @Transactional + public void getAllJobs() throws Exception { + // Initialize the database + jobRepository.saveAndFlush(job); + + // Get all the jobList + restJobMockMvc.perform(get("/api/jobs?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(job.getId().intValue()))) + .andExpect(jsonPath("$.[*].jobTitle").value(hasItem(DEFAULT_JOB_TITLE.toString()))) + .andExpect(jsonPath("$.[*].minSalary").value(hasItem(DEFAULT_MIN_SALARY.intValue()))) + .andExpect(jsonPath("$.[*].maxSalary").value(hasItem(DEFAULT_MAX_SALARY.intValue()))); + } + + @SuppressWarnings({"unchecked"}) + public void getAllJobsWithEagerRelationshipsIsEnabled() throws Exception { + JobResource jobResource = new JobResource(jobServiceMock); + when(jobServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>())); + + MockMvc restJobMockMvc = MockMvcBuilders.standaloneSetup(jobResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter).build(); + + restJobMockMvc.perform(get("/api/jobs?eagerload=true")) + .andExpect(status().isOk()); + + verify(jobServiceMock, times(1)).findAllWithEagerRelationships(any()); + } + + @SuppressWarnings({"unchecked"}) + public void getAllJobsWithEagerRelationshipsIsNotEnabled() throws Exception { + JobResource jobResource = new JobResource(jobServiceMock); + when(jobServiceMock.findAllWithEagerRelationships(any())).thenReturn(new PageImpl(new ArrayList<>())); + MockMvc restJobMockMvc = MockMvcBuilders.standaloneSetup(jobResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter).build(); + + restJobMockMvc.perform(get("/api/jobs?eagerload=true")) + .andExpect(status().isOk()); + + verify(jobServiceMock, times(1)).findAllWithEagerRelationships(any()); + } + + @Test + @Transactional + public void getJob() throws Exception { + // Initialize the database + jobRepository.saveAndFlush(job); + + // Get the job + restJobMockMvc.perform(get("/api/jobs/{id}", job.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(job.getId().intValue())) + .andExpect(jsonPath("$.jobTitle").value(DEFAULT_JOB_TITLE.toString())) + .andExpect(jsonPath("$.minSalary").value(DEFAULT_MIN_SALARY.intValue())) + .andExpect(jsonPath("$.maxSalary").value(DEFAULT_MAX_SALARY.intValue())); + } + + @Test + @Transactional + public void getNonExistingJob() throws Exception { + // Get the job + restJobMockMvc.perform(get("/api/jobs/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateJob() throws Exception { + // Initialize the database + jobRepository.saveAndFlush(job); + + int databaseSizeBeforeUpdate = jobRepository.findAll().size(); + + // Update the job + Job updatedJob = jobRepository.findById(job.getId()).get(); + // Disconnect from session so that the updates on updatedJob are not directly saved in db + em.detach(updatedJob); + updatedJob + .jobTitle(UPDATED_JOB_TITLE) + .minSalary(UPDATED_MIN_SALARY) + .maxSalary(UPDATED_MAX_SALARY); + JobDTO jobDTO = jobMapper.toDto(updatedJob); + + restJobMockMvc.perform(put("/api/jobs") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobDTO))) + .andExpect(status().isOk()); + + // Validate the Job in the database + List jobList = jobRepository.findAll(); + assertThat(jobList).hasSize(databaseSizeBeforeUpdate); + Job testJob = jobList.get(jobList.size() - 1); + assertThat(testJob.getJobTitle()).isEqualTo(UPDATED_JOB_TITLE); + assertThat(testJob.getMinSalary()).isEqualTo(UPDATED_MIN_SALARY); + assertThat(testJob.getMaxSalary()).isEqualTo(UPDATED_MAX_SALARY); + + // Validate the Job in Elasticsearch + verify(mockJobSearchRepository, times(1)).save(testJob); + } + + @Test + @Transactional + public void updateNonExistingJob() throws Exception { + int databaseSizeBeforeUpdate = jobRepository.findAll().size(); + + // Create the Job + JobDTO jobDTO = jobMapper.toDto(job); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restJobMockMvc.perform(put("/api/jobs") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(jobDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Job in the database + List jobList = jobRepository.findAll(); + assertThat(jobList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Job in Elasticsearch + verify(mockJobSearchRepository, times(0)).save(job); + } + + @Test + @Transactional + public void deleteJob() throws Exception { + // Initialize the database + jobRepository.saveAndFlush(job); + + int databaseSizeBeforeDelete = jobRepository.findAll().size(); + + // Delete the job + restJobMockMvc.perform(delete("/api/jobs/{id}", job.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List jobList = jobRepository.findAll(); + assertThat(jobList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Job in Elasticsearch + verify(mockJobSearchRepository, times(1)).deleteById(job.getId()); + } + + @Test + @Transactional + public void searchJob() throws Exception { + // Initialize the database + jobRepository.saveAndFlush(job); + when(mockJobSearchRepository.search(queryStringQuery("id:" + job.getId()), PageRequest.of(0, 20))) + .thenReturn(new PageImpl<>(Collections.singletonList(job), PageRequest.of(0, 1), 1)); + // Search the job + restJobMockMvc.perform(get("/api/_search/jobs?query=id:" + job.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(job.getId().intValue()))) + .andExpect(jsonPath("$.[*].jobTitle").value(hasItem(DEFAULT_JOB_TITLE))) + .andExpect(jsonPath("$.[*].minSalary").value(hasItem(DEFAULT_MIN_SALARY.intValue()))) + .andExpect(jsonPath("$.[*].maxSalary").value(hasItem(DEFAULT_MAX_SALARY.intValue()))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Job.class); + Job job1 = new Job(); + job1.setId(1L); + Job job2 = new Job(); + job2.setId(job1.getId()); + assertThat(job1).isEqualTo(job2); + job2.setId(2L); + assertThat(job1).isNotEqualTo(job2); + job1.setId(null); + assertThat(job1).isNotEqualTo(job2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(JobDTO.class); + JobDTO jobDTO1 = new JobDTO(); + jobDTO1.setId(1L); + JobDTO jobDTO2 = new JobDTO(); + assertThat(jobDTO1).isNotEqualTo(jobDTO2); + jobDTO2.setId(jobDTO1.getId()); + assertThat(jobDTO1).isEqualTo(jobDTO2); + jobDTO2.setId(2L); + assertThat(jobDTO1).isNotEqualTo(jobDTO2); + jobDTO1.setId(null); + assertThat(jobDTO1).isNotEqualTo(jobDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(jobMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(jobMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/org/zdar/web/rest/LocationResourceIT.java b/src/test/java/org/zdar/web/rest/LocationResourceIT.java new file mode 100644 index 0000000..9eac472 --- /dev/null +++ b/src/test/java/org/zdar/web/rest/LocationResourceIT.java @@ -0,0 +1,363 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.Location; +import org.zdar.repository.LocationRepository; +import org.zdar.repository.search.LocationSearchRepository; +import org.zdar.service.LocationService; +import org.zdar.service.dto.LocationDTO; +import org.zdar.service.mapper.LocationMapper; +import org.zdar.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.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 org.zdar.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 LocationResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class LocationResourceIT { + + private static final String DEFAULT_STREET_ADDRESS = "AAAAAAAAAA"; + private static final String UPDATED_STREET_ADDRESS = "BBBBBBBBBB"; + + private static final String DEFAULT_POSTAL_CODE = "AAAAAAAAAA"; + private static final String UPDATED_POSTAL_CODE = "BBBBBBBBBB"; + + private static final String DEFAULT_CITY = "AAAAAAAAAA"; + private static final String UPDATED_CITY = "BBBBBBBBBB"; + + private static final String DEFAULT_STATE_PROVINCE = "AAAAAAAAAA"; + private static final String UPDATED_STATE_PROVINCE = "BBBBBBBBBB"; + + @Autowired + private LocationRepository locationRepository; + + @Autowired + private LocationMapper locationMapper; + + @Autowired + private LocationService locationService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.LocationSearchRepositoryMockConfiguration + */ + @Autowired + private LocationSearchRepository mockLocationSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restLocationMockMvc; + + private Location location; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final LocationResource locationResource = new LocationResource(locationService); + this.restLocationMockMvc = MockMvcBuilders.standaloneSetup(locationResource) + .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 Location createEntity(EntityManager em) { + Location location = new Location() + .streetAddress(DEFAULT_STREET_ADDRESS) + .postalCode(DEFAULT_POSTAL_CODE) + .city(DEFAULT_CITY) + .stateProvince(DEFAULT_STATE_PROVINCE); + return location; + } + /** + * 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 Location createUpdatedEntity(EntityManager em) { + Location location = new Location() + .streetAddress(UPDATED_STREET_ADDRESS) + .postalCode(UPDATED_POSTAL_CODE) + .city(UPDATED_CITY) + .stateProvince(UPDATED_STATE_PROVINCE); + return location; + } + + @BeforeEach + public void initTest() { + location = createEntity(em); + } + + @Test + @Transactional + public void createLocation() throws Exception { + int databaseSizeBeforeCreate = locationRepository.findAll().size(); + + // Create the Location + LocationDTO locationDTO = locationMapper.toDto(location); + restLocationMockMvc.perform(post("/api/locations") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(locationDTO))) + .andExpect(status().isCreated()); + + // Validate the Location in the database + List locationList = locationRepository.findAll(); + assertThat(locationList).hasSize(databaseSizeBeforeCreate + 1); + Location testLocation = locationList.get(locationList.size() - 1); + assertThat(testLocation.getStreetAddress()).isEqualTo(DEFAULT_STREET_ADDRESS); + assertThat(testLocation.getPostalCode()).isEqualTo(DEFAULT_POSTAL_CODE); + assertThat(testLocation.getCity()).isEqualTo(DEFAULT_CITY); + assertThat(testLocation.getStateProvince()).isEqualTo(DEFAULT_STATE_PROVINCE); + + // Validate the Location in Elasticsearch + verify(mockLocationSearchRepository, times(1)).save(testLocation); + } + + @Test + @Transactional + public void createLocationWithExistingId() throws Exception { + int databaseSizeBeforeCreate = locationRepository.findAll().size(); + + // Create the Location with an existing ID + location.setId(1L); + LocationDTO locationDTO = locationMapper.toDto(location); + + // An entity with an existing ID cannot be created, so this API call must fail + restLocationMockMvc.perform(post("/api/locations") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(locationDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Location in the database + List locationList = locationRepository.findAll(); + assertThat(locationList).hasSize(databaseSizeBeforeCreate); + + // Validate the Location in Elasticsearch + verify(mockLocationSearchRepository, times(0)).save(location); + } + + + @Test + @Transactional + public void getAllLocations() throws Exception { + // Initialize the database + locationRepository.saveAndFlush(location); + + // Get all the locationList + restLocationMockMvc.perform(get("/api/locations?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(location.getId().intValue()))) + .andExpect(jsonPath("$.[*].streetAddress").value(hasItem(DEFAULT_STREET_ADDRESS.toString()))) + .andExpect(jsonPath("$.[*].postalCode").value(hasItem(DEFAULT_POSTAL_CODE.toString()))) + .andExpect(jsonPath("$.[*].city").value(hasItem(DEFAULT_CITY.toString()))) + .andExpect(jsonPath("$.[*].stateProvince").value(hasItem(DEFAULT_STATE_PROVINCE.toString()))); + } + + @Test + @Transactional + public void getLocation() throws Exception { + // Initialize the database + locationRepository.saveAndFlush(location); + + // Get the location + restLocationMockMvc.perform(get("/api/locations/{id}", location.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(location.getId().intValue())) + .andExpect(jsonPath("$.streetAddress").value(DEFAULT_STREET_ADDRESS.toString())) + .andExpect(jsonPath("$.postalCode").value(DEFAULT_POSTAL_CODE.toString())) + .andExpect(jsonPath("$.city").value(DEFAULT_CITY.toString())) + .andExpect(jsonPath("$.stateProvince").value(DEFAULT_STATE_PROVINCE.toString())); + } + + @Test + @Transactional + public void getNonExistingLocation() throws Exception { + // Get the location + restLocationMockMvc.perform(get("/api/locations/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateLocation() throws Exception { + // Initialize the database + locationRepository.saveAndFlush(location); + + int databaseSizeBeforeUpdate = locationRepository.findAll().size(); + + // Update the location + Location updatedLocation = locationRepository.findById(location.getId()).get(); + // Disconnect from session so that the updates on updatedLocation are not directly saved in db + em.detach(updatedLocation); + updatedLocation + .streetAddress(UPDATED_STREET_ADDRESS) + .postalCode(UPDATED_POSTAL_CODE) + .city(UPDATED_CITY) + .stateProvince(UPDATED_STATE_PROVINCE); + LocationDTO locationDTO = locationMapper.toDto(updatedLocation); + + restLocationMockMvc.perform(put("/api/locations") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(locationDTO))) + .andExpect(status().isOk()); + + // Validate the Location in the database + List locationList = locationRepository.findAll(); + assertThat(locationList).hasSize(databaseSizeBeforeUpdate); + Location testLocation = locationList.get(locationList.size() - 1); + assertThat(testLocation.getStreetAddress()).isEqualTo(UPDATED_STREET_ADDRESS); + assertThat(testLocation.getPostalCode()).isEqualTo(UPDATED_POSTAL_CODE); + assertThat(testLocation.getCity()).isEqualTo(UPDATED_CITY); + assertThat(testLocation.getStateProvince()).isEqualTo(UPDATED_STATE_PROVINCE); + + // Validate the Location in Elasticsearch + verify(mockLocationSearchRepository, times(1)).save(testLocation); + } + + @Test + @Transactional + public void updateNonExistingLocation() throws Exception { + int databaseSizeBeforeUpdate = locationRepository.findAll().size(); + + // Create the Location + LocationDTO locationDTO = locationMapper.toDto(location); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restLocationMockMvc.perform(put("/api/locations") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(locationDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Location in the database + List locationList = locationRepository.findAll(); + assertThat(locationList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Location in Elasticsearch + verify(mockLocationSearchRepository, times(0)).save(location); + } + + @Test + @Transactional + public void deleteLocation() throws Exception { + // Initialize the database + locationRepository.saveAndFlush(location); + + int databaseSizeBeforeDelete = locationRepository.findAll().size(); + + // Delete the location + restLocationMockMvc.perform(delete("/api/locations/{id}", location.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List locationList = locationRepository.findAll(); + assertThat(locationList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Location in Elasticsearch + verify(mockLocationSearchRepository, times(1)).deleteById(location.getId()); + } + + @Test + @Transactional + public void searchLocation() throws Exception { + // Initialize the database + locationRepository.saveAndFlush(location); + when(mockLocationSearchRepository.search(queryStringQuery("id:" + location.getId()))) + .thenReturn(Collections.singletonList(location)); + // Search the location + restLocationMockMvc.perform(get("/api/_search/locations?query=id:" + location.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(location.getId().intValue()))) + .andExpect(jsonPath("$.[*].streetAddress").value(hasItem(DEFAULT_STREET_ADDRESS))) + .andExpect(jsonPath("$.[*].postalCode").value(hasItem(DEFAULT_POSTAL_CODE))) + .andExpect(jsonPath("$.[*].city").value(hasItem(DEFAULT_CITY))) + .andExpect(jsonPath("$.[*].stateProvince").value(hasItem(DEFAULT_STATE_PROVINCE))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Location.class); + Location location1 = new Location(); + location1.setId(1L); + Location location2 = new Location(); + location2.setId(location1.getId()); + assertThat(location1).isEqualTo(location2); + location2.setId(2L); + assertThat(location1).isNotEqualTo(location2); + location1.setId(null); + assertThat(location1).isNotEqualTo(location2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(LocationDTO.class); + LocationDTO locationDTO1 = new LocationDTO(); + locationDTO1.setId(1L); + LocationDTO locationDTO2 = new LocationDTO(); + assertThat(locationDTO1).isNotEqualTo(locationDTO2); + locationDTO2.setId(locationDTO1.getId()); + assertThat(locationDTO1).isEqualTo(locationDTO2); + locationDTO2.setId(2L); + assertThat(locationDTO1).isNotEqualTo(locationDTO2); + locationDTO1.setId(null); + assertThat(locationDTO1).isNotEqualTo(locationDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(locationMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(locationMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/org/zdar/web/rest/RegionResourceIT.java b/src/test/java/org/zdar/web/rest/RegionResourceIT.java new file mode 100644 index 0000000..3b3872c --- /dev/null +++ b/src/test/java/org/zdar/web/rest/RegionResourceIT.java @@ -0,0 +1,330 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.Region; +import org.zdar.repository.RegionRepository; +import org.zdar.repository.search.RegionSearchRepository; +import org.zdar.service.RegionService; +import org.zdar.service.dto.RegionDTO; +import org.zdar.service.mapper.RegionMapper; +import org.zdar.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.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 org.zdar.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 RegionResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class RegionResourceIT { + + private static final String DEFAULT_REGION_NAME = "AAAAAAAAAA"; + private static final String UPDATED_REGION_NAME = "BBBBBBBBBB"; + + @Autowired + private RegionRepository regionRepository; + + @Autowired + private RegionMapper regionMapper; + + @Autowired + private RegionService regionService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.RegionSearchRepositoryMockConfiguration + */ + @Autowired + private RegionSearchRepository mockRegionSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restRegionMockMvc; + + private Region region; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final RegionResource regionResource = new RegionResource(regionService); + this.restRegionMockMvc = MockMvcBuilders.standaloneSetup(regionResource) + .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 Region createEntity(EntityManager em) { + Region region = new Region() + .regionName(DEFAULT_REGION_NAME); + return region; + } + /** + * 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 Region createUpdatedEntity(EntityManager em) { + Region region = new Region() + .regionName(UPDATED_REGION_NAME); + return region; + } + + @BeforeEach + public void initTest() { + region = createEntity(em); + } + + @Test + @Transactional + public void createRegion() throws Exception { + int databaseSizeBeforeCreate = regionRepository.findAll().size(); + + // Create the Region + RegionDTO regionDTO = regionMapper.toDto(region); + restRegionMockMvc.perform(post("/api/regions") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(regionDTO))) + .andExpect(status().isCreated()); + + // Validate the Region in the database + List regionList = regionRepository.findAll(); + assertThat(regionList).hasSize(databaseSizeBeforeCreate + 1); + Region testRegion = regionList.get(regionList.size() - 1); + assertThat(testRegion.getRegionName()).isEqualTo(DEFAULT_REGION_NAME); + + // Validate the Region in Elasticsearch + verify(mockRegionSearchRepository, times(1)).save(testRegion); + } + + @Test + @Transactional + public void createRegionWithExistingId() throws Exception { + int databaseSizeBeforeCreate = regionRepository.findAll().size(); + + // Create the Region with an existing ID + region.setId(1L); + RegionDTO regionDTO = regionMapper.toDto(region); + + // An entity with an existing ID cannot be created, so this API call must fail + restRegionMockMvc.perform(post("/api/regions") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(regionDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Region in the database + List regionList = regionRepository.findAll(); + assertThat(regionList).hasSize(databaseSizeBeforeCreate); + + // Validate the Region in Elasticsearch + verify(mockRegionSearchRepository, times(0)).save(region); + } + + + @Test + @Transactional + public void getAllRegions() throws Exception { + // Initialize the database + regionRepository.saveAndFlush(region); + + // Get all the regionList + restRegionMockMvc.perform(get("/api/regions?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(region.getId().intValue()))) + .andExpect(jsonPath("$.[*].regionName").value(hasItem(DEFAULT_REGION_NAME.toString()))); + } + + @Test + @Transactional + public void getRegion() throws Exception { + // Initialize the database + regionRepository.saveAndFlush(region); + + // Get the region + restRegionMockMvc.perform(get("/api/regions/{id}", region.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(region.getId().intValue())) + .andExpect(jsonPath("$.regionName").value(DEFAULT_REGION_NAME.toString())); + } + + @Test + @Transactional + public void getNonExistingRegion() throws Exception { + // Get the region + restRegionMockMvc.perform(get("/api/regions/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateRegion() throws Exception { + // Initialize the database + regionRepository.saveAndFlush(region); + + int databaseSizeBeforeUpdate = regionRepository.findAll().size(); + + // Update the region + Region updatedRegion = regionRepository.findById(region.getId()).get(); + // Disconnect from session so that the updates on updatedRegion are not directly saved in db + em.detach(updatedRegion); + updatedRegion + .regionName(UPDATED_REGION_NAME); + RegionDTO regionDTO = regionMapper.toDto(updatedRegion); + + restRegionMockMvc.perform(put("/api/regions") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(regionDTO))) + .andExpect(status().isOk()); + + // Validate the Region in the database + List regionList = regionRepository.findAll(); + assertThat(regionList).hasSize(databaseSizeBeforeUpdate); + Region testRegion = regionList.get(regionList.size() - 1); + assertThat(testRegion.getRegionName()).isEqualTo(UPDATED_REGION_NAME); + + // Validate the Region in Elasticsearch + verify(mockRegionSearchRepository, times(1)).save(testRegion); + } + + @Test + @Transactional + public void updateNonExistingRegion() throws Exception { + int databaseSizeBeforeUpdate = regionRepository.findAll().size(); + + // Create the Region + RegionDTO regionDTO = regionMapper.toDto(region); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restRegionMockMvc.perform(put("/api/regions") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(regionDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Region in the database + List regionList = regionRepository.findAll(); + assertThat(regionList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Region in Elasticsearch + verify(mockRegionSearchRepository, times(0)).save(region); + } + + @Test + @Transactional + public void deleteRegion() throws Exception { + // Initialize the database + regionRepository.saveAndFlush(region); + + int databaseSizeBeforeDelete = regionRepository.findAll().size(); + + // Delete the region + restRegionMockMvc.perform(delete("/api/regions/{id}", region.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List regionList = regionRepository.findAll(); + assertThat(regionList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Region in Elasticsearch + verify(mockRegionSearchRepository, times(1)).deleteById(region.getId()); + } + + @Test + @Transactional + public void searchRegion() throws Exception { + // Initialize the database + regionRepository.saveAndFlush(region); + when(mockRegionSearchRepository.search(queryStringQuery("id:" + region.getId()))) + .thenReturn(Collections.singletonList(region)); + // Search the region + restRegionMockMvc.perform(get("/api/_search/regions?query=id:" + region.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(region.getId().intValue()))) + .andExpect(jsonPath("$.[*].regionName").value(hasItem(DEFAULT_REGION_NAME))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Region.class); + Region region1 = new Region(); + region1.setId(1L); + Region region2 = new Region(); + region2.setId(region1.getId()); + assertThat(region1).isEqualTo(region2); + region2.setId(2L); + assertThat(region1).isNotEqualTo(region2); + region1.setId(null); + assertThat(region1).isNotEqualTo(region2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(RegionDTO.class); + RegionDTO regionDTO1 = new RegionDTO(); + regionDTO1.setId(1L); + RegionDTO regionDTO2 = new RegionDTO(); + assertThat(regionDTO1).isNotEqualTo(regionDTO2); + regionDTO2.setId(regionDTO1.getId()); + assertThat(regionDTO1).isEqualTo(regionDTO2); + regionDTO2.setId(2L); + assertThat(regionDTO1).isNotEqualTo(regionDTO2); + regionDTO1.setId(null); + assertThat(regionDTO1).isNotEqualTo(regionDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(regionMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(regionMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/java/org/zdar/web/rest/TaskResourceIT.java b/src/test/java/org/zdar/web/rest/TaskResourceIT.java new file mode 100644 index 0000000..32cfa43 --- /dev/null +++ b/src/test/java/org/zdar/web/rest/TaskResourceIT.java @@ -0,0 +1,341 @@ +package org.zdar.web.rest; + +import org.zdar.VisioApp; +import org.zdar.domain.Task; +import org.zdar.repository.TaskRepository; +import org.zdar.repository.search.TaskSearchRepository; +import org.zdar.service.TaskService; +import org.zdar.service.dto.TaskDTO; +import org.zdar.service.mapper.TaskMapper; +import org.zdar.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.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 org.zdar.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 TaskResource} REST controller. + */ +@SpringBootTest(classes = VisioApp.class) +public class TaskResourceIT { + + private static final String DEFAULT_TITLE = "AAAAAAAAAA"; + private static final String UPDATED_TITLE = "BBBBBBBBBB"; + + private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAA"; + private static final String UPDATED_DESCRIPTION = "BBBBBBBBBB"; + + @Autowired + private TaskRepository taskRepository; + + @Autowired + private TaskMapper taskMapper; + + @Autowired + private TaskService taskService; + + /** + * This repository is mocked in the org.zdar.repository.search test package. + * + * @see org.zdar.repository.search.TaskSearchRepositoryMockConfiguration + */ + @Autowired + private TaskSearchRepository mockTaskSearchRepository; + + @Autowired + private MappingJackson2HttpMessageConverter jacksonMessageConverter; + + @Autowired + private PageableHandlerMethodArgumentResolver pageableArgumentResolver; + + @Autowired + private ExceptionTranslator exceptionTranslator; + + @Autowired + private EntityManager em; + + @Autowired + private Validator validator; + + private MockMvc restTaskMockMvc; + + private Task task; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + final TaskResource taskResource = new TaskResource(taskService); + this.restTaskMockMvc = MockMvcBuilders.standaloneSetup(taskResource) + .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 Task createEntity(EntityManager em) { + Task task = new Task() + .title(DEFAULT_TITLE) + .description(DEFAULT_DESCRIPTION); + return task; + } + /** + * 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 Task createUpdatedEntity(EntityManager em) { + Task task = new Task() + .title(UPDATED_TITLE) + .description(UPDATED_DESCRIPTION); + return task; + } + + @BeforeEach + public void initTest() { + task = createEntity(em); + } + + @Test + @Transactional + public void createTask() throws Exception { + int databaseSizeBeforeCreate = taskRepository.findAll().size(); + + // Create the Task + TaskDTO taskDTO = taskMapper.toDto(task); + restTaskMockMvc.perform(post("/api/tasks") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(taskDTO))) + .andExpect(status().isCreated()); + + // Validate the Task in the database + List taskList = taskRepository.findAll(); + assertThat(taskList).hasSize(databaseSizeBeforeCreate + 1); + Task testTask = taskList.get(taskList.size() - 1); + assertThat(testTask.getTitle()).isEqualTo(DEFAULT_TITLE); + assertThat(testTask.getDescription()).isEqualTo(DEFAULT_DESCRIPTION); + + // Validate the Task in Elasticsearch + verify(mockTaskSearchRepository, times(1)).save(testTask); + } + + @Test + @Transactional + public void createTaskWithExistingId() throws Exception { + int databaseSizeBeforeCreate = taskRepository.findAll().size(); + + // Create the Task with an existing ID + task.setId(1L); + TaskDTO taskDTO = taskMapper.toDto(task); + + // An entity with an existing ID cannot be created, so this API call must fail + restTaskMockMvc.perform(post("/api/tasks") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(taskDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Task in the database + List taskList = taskRepository.findAll(); + assertThat(taskList).hasSize(databaseSizeBeforeCreate); + + // Validate the Task in Elasticsearch + verify(mockTaskSearchRepository, times(0)).save(task); + } + + + @Test + @Transactional + public void getAllTasks() throws Exception { + // Initialize the database + taskRepository.saveAndFlush(task); + + // Get all the taskList + restTaskMockMvc.perform(get("/api/tasks?sort=id,desc")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(task.getId().intValue()))) + .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString()))) + .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString()))); + } + + @Test + @Transactional + public void getTask() throws Exception { + // Initialize the database + taskRepository.saveAndFlush(task); + + // Get the task + restTaskMockMvc.perform(get("/api/tasks/{id}", task.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(task.getId().intValue())) + .andExpect(jsonPath("$.title").value(DEFAULT_TITLE.toString())) + .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString())); + } + + @Test + @Transactional + public void getNonExistingTask() throws Exception { + // Get the task + restTaskMockMvc.perform(get("/api/tasks/{id}", Long.MAX_VALUE)) + .andExpect(status().isNotFound()); + } + + @Test + @Transactional + public void updateTask() throws Exception { + // Initialize the database + taskRepository.saveAndFlush(task); + + int databaseSizeBeforeUpdate = taskRepository.findAll().size(); + + // Update the task + Task updatedTask = taskRepository.findById(task.getId()).get(); + // Disconnect from session so that the updates on updatedTask are not directly saved in db + em.detach(updatedTask); + updatedTask + .title(UPDATED_TITLE) + .description(UPDATED_DESCRIPTION); + TaskDTO taskDTO = taskMapper.toDto(updatedTask); + + restTaskMockMvc.perform(put("/api/tasks") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(taskDTO))) + .andExpect(status().isOk()); + + // Validate the Task in the database + List taskList = taskRepository.findAll(); + assertThat(taskList).hasSize(databaseSizeBeforeUpdate); + Task testTask = taskList.get(taskList.size() - 1); + assertThat(testTask.getTitle()).isEqualTo(UPDATED_TITLE); + assertThat(testTask.getDescription()).isEqualTo(UPDATED_DESCRIPTION); + + // Validate the Task in Elasticsearch + verify(mockTaskSearchRepository, times(1)).save(testTask); + } + + @Test + @Transactional + public void updateNonExistingTask() throws Exception { + int databaseSizeBeforeUpdate = taskRepository.findAll().size(); + + // Create the Task + TaskDTO taskDTO = taskMapper.toDto(task); + + // If the entity doesn't have an ID, it will throw BadRequestAlertException + restTaskMockMvc.perform(put("/api/tasks") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(taskDTO))) + .andExpect(status().isBadRequest()); + + // Validate the Task in the database + List taskList = taskRepository.findAll(); + assertThat(taskList).hasSize(databaseSizeBeforeUpdate); + + // Validate the Task in Elasticsearch + verify(mockTaskSearchRepository, times(0)).save(task); + } + + @Test + @Transactional + public void deleteTask() throws Exception { + // Initialize the database + taskRepository.saveAndFlush(task); + + int databaseSizeBeforeDelete = taskRepository.findAll().size(); + + // Delete the task + restTaskMockMvc.perform(delete("/api/tasks/{id}", task.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isNoContent()); + + // Validate the database is empty + List taskList = taskRepository.findAll(); + assertThat(taskList).hasSize(databaseSizeBeforeDelete - 1); + + // Validate the Task in Elasticsearch + verify(mockTaskSearchRepository, times(1)).deleteById(task.getId()); + } + + @Test + @Transactional + public void searchTask() throws Exception { + // Initialize the database + taskRepository.saveAndFlush(task); + when(mockTaskSearchRepository.search(queryStringQuery("id:" + task.getId()))) + .thenReturn(Collections.singletonList(task)); + // Search the task + restTaskMockMvc.perform(get("/api/_search/tasks?query=id:" + task.getId())) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(task.getId().intValue()))) + .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE))) + .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION))); + } + + @Test + @Transactional + public void equalsVerifier() throws Exception { + TestUtil.equalsVerifier(Task.class); + Task task1 = new Task(); + task1.setId(1L); + Task task2 = new Task(); + task2.setId(task1.getId()); + assertThat(task1).isEqualTo(task2); + task2.setId(2L); + assertThat(task1).isNotEqualTo(task2); + task1.setId(null); + assertThat(task1).isNotEqualTo(task2); + } + + @Test + @Transactional + public void dtoEqualsVerifier() throws Exception { + TestUtil.equalsVerifier(TaskDTO.class); + TaskDTO taskDTO1 = new TaskDTO(); + taskDTO1.setId(1L); + TaskDTO taskDTO2 = new TaskDTO(); + assertThat(taskDTO1).isNotEqualTo(taskDTO2); + taskDTO2.setId(taskDTO1.getId()); + assertThat(taskDTO1).isEqualTo(taskDTO2); + taskDTO2.setId(2L); + assertThat(taskDTO1).isNotEqualTo(taskDTO2); + taskDTO1.setId(null); + assertThat(taskDTO1).isNotEqualTo(taskDTO2); + } + + @Test + @Transactional + public void testEntityFromId() { + assertThat(taskMapper.fromId(42L).getId()).isEqualTo(42); + assertThat(taskMapper.fromId(null)).isNull(); + } +} diff --git a/src/test/javascript/e2e/entities/country/country.page-object.ts b/src/test/javascript/e2e/entities/country/country.page-object.ts new file mode 100644 index 0000000..143442f --- /dev/null +++ b/src/test/javascript/e2e/entities/country/country.page-object.ts @@ -0,0 +1,87 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class CountryComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-country div table .btn-danger')); + title = element.all(by.css('jhi-country div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class CountryUpdatePage { + pageTitle = element(by.id('jhi-country-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + countryNameInput = element(by.id('field_countryName')); + regionSelect = element(by.id('field_region')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setCountryNameInput(countryName) { + await this.countryNameInput.sendKeys(countryName); + } + + async getCountryNameInput() { + return await this.countryNameInput.getAttribute('value'); + } + + async regionSelectLastOption(timeout?: number) { + await this.regionSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async regionSelectOption(option) { + await this.regionSelect.sendKeys(option); + } + + getRegionSelect(): ElementFinder { + return this.regionSelect; + } + + async getRegionSelectedOption() { + return await this.regionSelect.element(by.css('option:checked')).getText(); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class CountryDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-country-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-country')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/country/country.spec.ts b/src/test/javascript/e2e/entities/country/country.spec.ts new file mode 100644 index 0000000..09b1df7 --- /dev/null +++ b/src/test/javascript/e2e/entities/country/country.spec.ts @@ -0,0 +1,64 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { CountryComponentsPage, CountryDeleteDialog, CountryUpdatePage } from './country.page-object'; + +const expect = chai.expect; + +describe('Country e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let countryUpdatePage: CountryUpdatePage; + let countryComponentsPage: CountryComponentsPage; + let countryDeleteDialog: CountryDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load Countries', async () => { + await navBarPage.goToEntity('country'); + countryComponentsPage = new CountryComponentsPage(); + await browser.wait(ec.visibilityOf(countryComponentsPage.title), 5000); + expect(await countryComponentsPage.getTitle()).to.eq('Countries'); + }); + + it('should load create Country page', async () => { + await countryComponentsPage.clickOnCreateButton(); + countryUpdatePage = new CountryUpdatePage(); + expect(await countryUpdatePage.getPageTitle()).to.eq('Create or edit a Country'); + await countryUpdatePage.cancel(); + }); + + it('should create and save Countries', async () => { + const nbButtonsBeforeCreate = await countryComponentsPage.countDeleteButtons(); + + await countryComponentsPage.clickOnCreateButton(); + await promise.all([countryUpdatePage.setCountryNameInput('countryName'), countryUpdatePage.regionSelectLastOption()]); + expect(await countryUpdatePage.getCountryNameInput()).to.eq('countryName', 'Expected CountryName value to be equals to countryName'); + await countryUpdatePage.save(); + expect(await countryUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await countryComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last Country', async () => { + const nbButtonsBeforeDelete = await countryComponentsPage.countDeleteButtons(); + await countryComponentsPage.clickOnLastDeleteButton(); + + countryDeleteDialog = new CountryDeleteDialog(); + expect(await countryDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Country?'); + await countryDeleteDialog.clickOnConfirmButton(); + + expect(await countryComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/e2e/entities/department/department.page-object.ts b/src/test/javascript/e2e/entities/department/department.page-object.ts new file mode 100644 index 0000000..8049c05 --- /dev/null +++ b/src/test/javascript/e2e/entities/department/department.page-object.ts @@ -0,0 +1,87 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class DepartmentComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-department div table .btn-danger')); + title = element.all(by.css('jhi-department div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class DepartmentUpdatePage { + pageTitle = element(by.id('jhi-department-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + departmentNameInput = element(by.id('field_departmentName')); + locationSelect = element(by.id('field_location')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setDepartmentNameInput(departmentName) { + await this.departmentNameInput.sendKeys(departmentName); + } + + async getDepartmentNameInput() { + return await this.departmentNameInput.getAttribute('value'); + } + + async locationSelectLastOption(timeout?: number) { + await this.locationSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async locationSelectOption(option) { + await this.locationSelect.sendKeys(option); + } + + getLocationSelect(): ElementFinder { + return this.locationSelect; + } + + async getLocationSelectedOption() { + return await this.locationSelect.element(by.css('option:checked')).getText(); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class DepartmentDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-department-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-department')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/department/department.spec.ts b/src/test/javascript/e2e/entities/department/department.spec.ts new file mode 100644 index 0000000..a6993eb --- /dev/null +++ b/src/test/javascript/e2e/entities/department/department.spec.ts @@ -0,0 +1,67 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { DepartmentComponentsPage, DepartmentDeleteDialog, DepartmentUpdatePage } from './department.page-object'; + +const expect = chai.expect; + +describe('Department e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let departmentUpdatePage: DepartmentUpdatePage; + let departmentComponentsPage: DepartmentComponentsPage; + let departmentDeleteDialog: DepartmentDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load Departments', async () => { + await navBarPage.goToEntity('department'); + departmentComponentsPage = new DepartmentComponentsPage(); + await browser.wait(ec.visibilityOf(departmentComponentsPage.title), 5000); + expect(await departmentComponentsPage.getTitle()).to.eq('Departments'); + }); + + it('should load create Department page', async () => { + await departmentComponentsPage.clickOnCreateButton(); + departmentUpdatePage = new DepartmentUpdatePage(); + expect(await departmentUpdatePage.getPageTitle()).to.eq('Create or edit a Department'); + await departmentUpdatePage.cancel(); + }); + + it('should create and save Departments', async () => { + const nbButtonsBeforeCreate = await departmentComponentsPage.countDeleteButtons(); + + await departmentComponentsPage.clickOnCreateButton(); + await promise.all([departmentUpdatePage.setDepartmentNameInput('departmentName'), departmentUpdatePage.locationSelectLastOption()]); + expect(await departmentUpdatePage.getDepartmentNameInput()).to.eq( + 'departmentName', + 'Expected DepartmentName value to be equals to departmentName' + ); + await departmentUpdatePage.save(); + expect(await departmentUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await departmentComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last Department', async () => { + const nbButtonsBeforeDelete = await departmentComponentsPage.countDeleteButtons(); + await departmentComponentsPage.clickOnLastDeleteButton(); + + departmentDeleteDialog = new DepartmentDeleteDialog(); + expect(await departmentDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Department?'); + await departmentDeleteDialog.clickOnConfirmButton(); + + expect(await departmentComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/e2e/entities/employee/employee.page-object.ts b/src/test/javascript/e2e/entities/employee/employee.page-object.ts new file mode 100644 index 0000000..8d1cbda --- /dev/null +++ b/src/test/javascript/e2e/entities/employee/employee.page-object.ts @@ -0,0 +1,161 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class EmployeeComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-employee div table .btn-danger')); + title = element.all(by.css('jhi-employee div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class EmployeeUpdatePage { + pageTitle = element(by.id('jhi-employee-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + firstNameInput = element(by.id('field_firstName')); + lastNameInput = element(by.id('field_lastName')); + emailInput = element(by.id('field_email')); + phoneNumberInput = element(by.id('field_phoneNumber')); + hireDateInput = element(by.id('field_hireDate')); + salaryInput = element(by.id('field_salary')); + commissionPctInput = element(by.id('field_commissionPct')); + departmentSelect = element(by.id('field_department')); + managerSelect = element(by.id('field_manager')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setFirstNameInput(firstName) { + await this.firstNameInput.sendKeys(firstName); + } + + async getFirstNameInput() { + return await this.firstNameInput.getAttribute('value'); + } + + async setLastNameInput(lastName) { + await this.lastNameInput.sendKeys(lastName); + } + + async getLastNameInput() { + return await this.lastNameInput.getAttribute('value'); + } + + async setEmailInput(email) { + await this.emailInput.sendKeys(email); + } + + async getEmailInput() { + return await this.emailInput.getAttribute('value'); + } + + async setPhoneNumberInput(phoneNumber) { + await this.phoneNumberInput.sendKeys(phoneNumber); + } + + async getPhoneNumberInput() { + return await this.phoneNumberInput.getAttribute('value'); + } + + async setHireDateInput(hireDate) { + await this.hireDateInput.sendKeys(hireDate); + } + + async getHireDateInput() { + return await this.hireDateInput.getAttribute('value'); + } + + async setSalaryInput(salary) { + await this.salaryInput.sendKeys(salary); + } + + async getSalaryInput() { + return await this.salaryInput.getAttribute('value'); + } + + async setCommissionPctInput(commissionPct) { + await this.commissionPctInput.sendKeys(commissionPct); + } + + async getCommissionPctInput() { + return await this.commissionPctInput.getAttribute('value'); + } + + async departmentSelectLastOption(timeout?: number) { + await this.departmentSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async departmentSelectOption(option) { + await this.departmentSelect.sendKeys(option); + } + + getDepartmentSelect(): ElementFinder { + return this.departmentSelect; + } + + async getDepartmentSelectedOption() { + return await this.departmentSelect.element(by.css('option:checked')).getText(); + } + + async managerSelectLastOption(timeout?: number) { + await this.managerSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async managerSelectOption(option) { + await this.managerSelect.sendKeys(option); + } + + getManagerSelect(): ElementFinder { + return this.managerSelect; + } + + async getManagerSelectedOption() { + return await this.managerSelect.element(by.css('option:checked')).getText(); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class EmployeeDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-employee-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-employee')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/employee/employee.spec.ts b/src/test/javascript/e2e/entities/employee/employee.spec.ts new file mode 100644 index 0000000..237c5da --- /dev/null +++ b/src/test/javascript/e2e/entities/employee/employee.spec.ts @@ -0,0 +1,83 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, protractor, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { EmployeeComponentsPage, EmployeeDeleteDialog, EmployeeUpdatePage } from './employee.page-object'; + +const expect = chai.expect; + +describe('Employee e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let employeeUpdatePage: EmployeeUpdatePage; + let employeeComponentsPage: EmployeeComponentsPage; + let employeeDeleteDialog: EmployeeDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load Employees', async () => { + await navBarPage.goToEntity('employee'); + employeeComponentsPage = new EmployeeComponentsPage(); + await browser.wait(ec.visibilityOf(employeeComponentsPage.title), 5000); + expect(await employeeComponentsPage.getTitle()).to.eq('Employees'); + }); + + it('should load create Employee page', async () => { + await employeeComponentsPage.clickOnCreateButton(); + employeeUpdatePage = new EmployeeUpdatePage(); + expect(await employeeUpdatePage.getPageTitle()).to.eq('Create or edit a Employee'); + await employeeUpdatePage.cancel(); + }); + + it('should create and save Employees', async () => { + const nbButtonsBeforeCreate = await employeeComponentsPage.countDeleteButtons(); + + await employeeComponentsPage.clickOnCreateButton(); + await promise.all([ + employeeUpdatePage.setFirstNameInput('firstName'), + employeeUpdatePage.setLastNameInput('lastName'), + employeeUpdatePage.setEmailInput('email'), + employeeUpdatePage.setPhoneNumberInput('phoneNumber'), + employeeUpdatePage.setHireDateInput('01/01/2001' + protractor.Key.TAB + '02:30AM'), + employeeUpdatePage.setSalaryInput('5'), + employeeUpdatePage.setCommissionPctInput('5'), + employeeUpdatePage.departmentSelectLastOption(), + employeeUpdatePage.managerSelectLastOption() + ]); + expect(await employeeUpdatePage.getFirstNameInput()).to.eq('firstName', 'Expected FirstName value to be equals to firstName'); + expect(await employeeUpdatePage.getLastNameInput()).to.eq('lastName', 'Expected LastName value to be equals to lastName'); + expect(await employeeUpdatePage.getEmailInput()).to.eq('email', 'Expected Email value to be equals to email'); + expect(await employeeUpdatePage.getPhoneNumberInput()).to.eq('phoneNumber', 'Expected PhoneNumber value to be equals to phoneNumber'); + expect(await employeeUpdatePage.getHireDateInput()).to.contain( + '2001-01-01T02:30', + 'Expected hireDate value to be equals to 2000-12-31' + ); + expect(await employeeUpdatePage.getSalaryInput()).to.eq('5', 'Expected salary value to be equals to 5'); + expect(await employeeUpdatePage.getCommissionPctInput()).to.eq('5', 'Expected commissionPct value to be equals to 5'); + await employeeUpdatePage.save(); + expect(await employeeUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await employeeComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last Employee', async () => { + const nbButtonsBeforeDelete = await employeeComponentsPage.countDeleteButtons(); + await employeeComponentsPage.clickOnLastDeleteButton(); + + employeeDeleteDialog = new EmployeeDeleteDialog(); + expect(await employeeDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Employee?'); + await employeeDeleteDialog.clickOnConfirmButton(); + + expect(await employeeComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/e2e/entities/job-history/job-history.page-object.ts b/src/test/javascript/e2e/entities/job-history/job-history.page-object.ts new file mode 100644 index 0000000..516f480 --- /dev/null +++ b/src/test/javascript/e2e/entities/job-history/job-history.page-object.ts @@ -0,0 +1,152 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class JobHistoryComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-job-history div table .btn-danger')); + title = element.all(by.css('jhi-job-history div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class JobHistoryUpdatePage { + pageTitle = element(by.id('jhi-job-history-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + startDateInput = element(by.id('field_startDate')); + endDateInput = element(by.id('field_endDate')); + languageSelect = element(by.id('field_language')); + jobSelect = element(by.id('field_job')); + departmentSelect = element(by.id('field_department')); + employeeSelect = element(by.id('field_employee')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setStartDateInput(startDate) { + await this.startDateInput.sendKeys(startDate); + } + + async getStartDateInput() { + return await this.startDateInput.getAttribute('value'); + } + + async setEndDateInput(endDate) { + await this.endDateInput.sendKeys(endDate); + } + + async getEndDateInput() { + return await this.endDateInput.getAttribute('value'); + } + + async setLanguageSelect(language) { + await this.languageSelect.sendKeys(language); + } + + async getLanguageSelect() { + return await this.languageSelect.element(by.css('option:checked')).getText(); + } + + async languageSelectLastOption(timeout?: number) { + await this.languageSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async jobSelectLastOption(timeout?: number) { + await this.jobSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async jobSelectOption(option) { + await this.jobSelect.sendKeys(option); + } + + getJobSelect(): ElementFinder { + return this.jobSelect; + } + + async getJobSelectedOption() { + return await this.jobSelect.element(by.css('option:checked')).getText(); + } + + async departmentSelectLastOption(timeout?: number) { + await this.departmentSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async departmentSelectOption(option) { + await this.departmentSelect.sendKeys(option); + } + + getDepartmentSelect(): ElementFinder { + return this.departmentSelect; + } + + async getDepartmentSelectedOption() { + return await this.departmentSelect.element(by.css('option:checked')).getText(); + } + + async employeeSelectLastOption(timeout?: number) { + await this.employeeSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async employeeSelectOption(option) { + await this.employeeSelect.sendKeys(option); + } + + getEmployeeSelect(): ElementFinder { + return this.employeeSelect; + } + + async getEmployeeSelectedOption() { + return await this.employeeSelect.element(by.css('option:checked')).getText(); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class JobHistoryDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-jobHistory-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-jobHistory')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/job-history/job-history.spec.ts b/src/test/javascript/e2e/entities/job-history/job-history.spec.ts new file mode 100644 index 0000000..be37430 --- /dev/null +++ b/src/test/javascript/e2e/entities/job-history/job-history.spec.ts @@ -0,0 +1,78 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, protractor, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { JobHistoryComponentsPage, JobHistoryDeleteDialog, JobHistoryUpdatePage } from './job-history.page-object'; + +const expect = chai.expect; + +describe('JobHistory e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let jobHistoryUpdatePage: JobHistoryUpdatePage; + let jobHistoryComponentsPage: JobHistoryComponentsPage; + let jobHistoryDeleteDialog: JobHistoryDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load JobHistories', async () => { + await navBarPage.goToEntity('job-history'); + jobHistoryComponentsPage = new JobHistoryComponentsPage(); + await browser.wait(ec.visibilityOf(jobHistoryComponentsPage.title), 5000); + expect(await jobHistoryComponentsPage.getTitle()).to.eq('Job Histories'); + }); + + it('should load create JobHistory page', async () => { + await jobHistoryComponentsPage.clickOnCreateButton(); + jobHistoryUpdatePage = new JobHistoryUpdatePage(); + expect(await jobHistoryUpdatePage.getPageTitle()).to.eq('Create or edit a Job History'); + await jobHistoryUpdatePage.cancel(); + }); + + it('should create and save JobHistories', async () => { + const nbButtonsBeforeCreate = await jobHistoryComponentsPage.countDeleteButtons(); + + await jobHistoryComponentsPage.clickOnCreateButton(); + await promise.all([ + jobHistoryUpdatePage.setStartDateInput('01/01/2001' + protractor.Key.TAB + '02:30AM'), + jobHistoryUpdatePage.setEndDateInput('01/01/2001' + protractor.Key.TAB + '02:30AM'), + jobHistoryUpdatePage.languageSelectLastOption(), + jobHistoryUpdatePage.jobSelectLastOption(), + jobHistoryUpdatePage.departmentSelectLastOption(), + jobHistoryUpdatePage.employeeSelectLastOption() + ]); + expect(await jobHistoryUpdatePage.getStartDateInput()).to.contain( + '2001-01-01T02:30', + 'Expected startDate value to be equals to 2000-12-31' + ); + expect(await jobHistoryUpdatePage.getEndDateInput()).to.contain( + '2001-01-01T02:30', + 'Expected endDate value to be equals to 2000-12-31' + ); + await jobHistoryUpdatePage.save(); + expect(await jobHistoryUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await jobHistoryComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last JobHistory', async () => { + const nbButtonsBeforeDelete = await jobHistoryComponentsPage.countDeleteButtons(); + await jobHistoryComponentsPage.clickOnLastDeleteButton(); + + jobHistoryDeleteDialog = new JobHistoryDeleteDialog(); + expect(await jobHistoryDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Job History?'); + await jobHistoryDeleteDialog.clickOnConfirmButton(); + + expect(await jobHistoryComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/e2e/entities/job/job.page-object.ts b/src/test/javascript/e2e/entities/job/job.page-object.ts new file mode 100644 index 0000000..e067eca --- /dev/null +++ b/src/test/javascript/e2e/entities/job/job.page-object.ts @@ -0,0 +1,125 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class JobComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-job div table .btn-danger')); + title = element.all(by.css('jhi-job div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class JobUpdatePage { + pageTitle = element(by.id('jhi-job-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + jobTitleInput = element(by.id('field_jobTitle')); + minSalaryInput = element(by.id('field_minSalary')); + maxSalaryInput = element(by.id('field_maxSalary')); + employeeSelect = element(by.id('field_employee')); + taskSelect = element(by.id('field_task')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setJobTitleInput(jobTitle) { + await this.jobTitleInput.sendKeys(jobTitle); + } + + async getJobTitleInput() { + return await this.jobTitleInput.getAttribute('value'); + } + + async setMinSalaryInput(minSalary) { + await this.minSalaryInput.sendKeys(minSalary); + } + + async getMinSalaryInput() { + return await this.minSalaryInput.getAttribute('value'); + } + + async setMaxSalaryInput(maxSalary) { + await this.maxSalaryInput.sendKeys(maxSalary); + } + + async getMaxSalaryInput() { + return await this.maxSalaryInput.getAttribute('value'); + } + + async employeeSelectLastOption(timeout?: number) { + await this.employeeSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async employeeSelectOption(option) { + await this.employeeSelect.sendKeys(option); + } + + getEmployeeSelect(): ElementFinder { + return this.employeeSelect; + } + + async getEmployeeSelectedOption() { + return await this.employeeSelect.element(by.css('option:checked')).getText(); + } + + async taskSelectLastOption(timeout?: number) { + await this.taskSelect + .all(by.tagName('option')) + .last() + .click(); + } + + async taskSelectOption(option) { + await this.taskSelect.sendKeys(option); + } + + getTaskSelect(): ElementFinder { + return this.taskSelect; + } + + async getTaskSelectedOption() { + return await this.taskSelect.element(by.css('option:checked')).getText(); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class JobDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-job-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-job')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/job/job.spec.ts b/src/test/javascript/e2e/entities/job/job.spec.ts new file mode 100644 index 0000000..753e517 --- /dev/null +++ b/src/test/javascript/e2e/entities/job/job.spec.ts @@ -0,0 +1,72 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { JobComponentsPage, JobDeleteDialog, JobUpdatePage } from './job.page-object'; + +const expect = chai.expect; + +describe('Job e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let jobUpdatePage: JobUpdatePage; + let jobComponentsPage: JobComponentsPage; + let jobDeleteDialog: JobDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load Jobs', async () => { + await navBarPage.goToEntity('job'); + jobComponentsPage = new JobComponentsPage(); + await browser.wait(ec.visibilityOf(jobComponentsPage.title), 5000); + expect(await jobComponentsPage.getTitle()).to.eq('Jobs'); + }); + + it('should load create Job page', async () => { + await jobComponentsPage.clickOnCreateButton(); + jobUpdatePage = new JobUpdatePage(); + expect(await jobUpdatePage.getPageTitle()).to.eq('Create or edit a Job'); + await jobUpdatePage.cancel(); + }); + + it('should create and save Jobs', async () => { + const nbButtonsBeforeCreate = await jobComponentsPage.countDeleteButtons(); + + await jobComponentsPage.clickOnCreateButton(); + await promise.all([ + jobUpdatePage.setJobTitleInput('jobTitle'), + jobUpdatePage.setMinSalaryInput('5'), + jobUpdatePage.setMaxSalaryInput('5'), + jobUpdatePage.employeeSelectLastOption() + // jobUpdatePage.taskSelectLastOption(), + ]); + expect(await jobUpdatePage.getJobTitleInput()).to.eq('jobTitle', 'Expected JobTitle value to be equals to jobTitle'); + expect(await jobUpdatePage.getMinSalaryInput()).to.eq('5', 'Expected minSalary value to be equals to 5'); + expect(await jobUpdatePage.getMaxSalaryInput()).to.eq('5', 'Expected maxSalary value to be equals to 5'); + await jobUpdatePage.save(); + expect(await jobUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await jobComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last Job', async () => { + const nbButtonsBeforeDelete = await jobComponentsPage.countDeleteButtons(); + await jobComponentsPage.clickOnLastDeleteButton(); + + jobDeleteDialog = new JobDeleteDialog(); + expect(await jobDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Job?'); + await jobDeleteDialog.clickOnConfirmButton(); + + expect(await jobComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/e2e/entities/location/location.page-object.ts b/src/test/javascript/e2e/entities/location/location.page-object.ts new file mode 100644 index 0000000..df7286c --- /dev/null +++ b/src/test/javascript/e2e/entities/location/location.page-object.ts @@ -0,0 +1,114 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class LocationComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-location div table .btn-danger')); + title = element.all(by.css('jhi-location div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class LocationUpdatePage { + pageTitle = element(by.id('jhi-location-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + streetAddressInput = element(by.id('field_streetAddress')); + postalCodeInput = element(by.id('field_postalCode')); + cityInput = element(by.id('field_city')); + stateProvinceInput = element(by.id('field_stateProvince')); + countrySelect = element(by.id('field_country')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setStreetAddressInput(streetAddress) { + await this.streetAddressInput.sendKeys(streetAddress); + } + + async getStreetAddressInput() { + return await this.streetAddressInput.getAttribute('value'); + } + + async setPostalCodeInput(postalCode) { + await this.postalCodeInput.sendKeys(postalCode); + } + + async getPostalCodeInput() { + return await this.postalCodeInput.getAttribute('value'); + } + + async setCityInput(city) { + await this.cityInput.sendKeys(city); + } + + async getCityInput() { + return await this.cityInput.getAttribute('value'); + } + + async setStateProvinceInput(stateProvince) { + await this.stateProvinceInput.sendKeys(stateProvince); + } + + async getStateProvinceInput() { + return await this.stateProvinceInput.getAttribute('value'); + } + + async countrySelectLastOption(timeout?: number) { + await this.countrySelect + .all(by.tagName('option')) + .last() + .click(); + } + + async countrySelectOption(option) { + await this.countrySelect.sendKeys(option); + } + + getCountrySelect(): ElementFinder { + return this.countrySelect; + } + + async getCountrySelectedOption() { + return await this.countrySelect.element(by.css('option:checked')).getText(); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class LocationDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-location-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-location')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/location/location.spec.ts b/src/test/javascript/e2e/entities/location/location.spec.ts new file mode 100644 index 0000000..7cd2dc5 --- /dev/null +++ b/src/test/javascript/e2e/entities/location/location.spec.ts @@ -0,0 +1,79 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { LocationComponentsPage, LocationDeleteDialog, LocationUpdatePage } from './location.page-object'; + +const expect = chai.expect; + +describe('Location e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let locationUpdatePage: LocationUpdatePage; + let locationComponentsPage: LocationComponentsPage; + let locationDeleteDialog: LocationDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load Locations', async () => { + await navBarPage.goToEntity('location'); + locationComponentsPage = new LocationComponentsPage(); + await browser.wait(ec.visibilityOf(locationComponentsPage.title), 5000); + expect(await locationComponentsPage.getTitle()).to.eq('Locations'); + }); + + it('should load create Location page', async () => { + await locationComponentsPage.clickOnCreateButton(); + locationUpdatePage = new LocationUpdatePage(); + expect(await locationUpdatePage.getPageTitle()).to.eq('Create or edit a Location'); + await locationUpdatePage.cancel(); + }); + + it('should create and save Locations', async () => { + const nbButtonsBeforeCreate = await locationComponentsPage.countDeleteButtons(); + + await locationComponentsPage.clickOnCreateButton(); + await promise.all([ + locationUpdatePage.setStreetAddressInput('streetAddress'), + locationUpdatePage.setPostalCodeInput('postalCode'), + locationUpdatePage.setCityInput('city'), + locationUpdatePage.setStateProvinceInput('stateProvince'), + locationUpdatePage.countrySelectLastOption() + ]); + expect(await locationUpdatePage.getStreetAddressInput()).to.eq( + 'streetAddress', + 'Expected StreetAddress value to be equals to streetAddress' + ); + expect(await locationUpdatePage.getPostalCodeInput()).to.eq('postalCode', 'Expected PostalCode value to be equals to postalCode'); + expect(await locationUpdatePage.getCityInput()).to.eq('city', 'Expected City value to be equals to city'); + expect(await locationUpdatePage.getStateProvinceInput()).to.eq( + 'stateProvince', + 'Expected StateProvince value to be equals to stateProvince' + ); + await locationUpdatePage.save(); + expect(await locationUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await locationComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last Location', async () => { + const nbButtonsBeforeDelete = await locationComponentsPage.countDeleteButtons(); + await locationComponentsPage.clickOnLastDeleteButton(); + + locationDeleteDialog = new LocationDeleteDialog(); + expect(await locationDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Location?'); + await locationDeleteDialog.clickOnConfirmButton(); + + expect(await locationComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/e2e/entities/region/region.page-object.ts b/src/test/javascript/e2e/entities/region/region.page-object.ts new file mode 100644 index 0000000..fadae1f --- /dev/null +++ b/src/test/javascript/e2e/entities/region/region.page-object.ts @@ -0,0 +1,67 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class RegionComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-region div table .btn-danger')); + title = element.all(by.css('jhi-region div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class RegionUpdatePage { + pageTitle = element(by.id('jhi-region-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + regionNameInput = element(by.id('field_regionName')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setRegionNameInput(regionName) { + await this.regionNameInput.sendKeys(regionName); + } + + async getRegionNameInput() { + return await this.regionNameInput.getAttribute('value'); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class RegionDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-region-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-region')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/region/region.spec.ts b/src/test/javascript/e2e/entities/region/region.spec.ts new file mode 100644 index 0000000..183e053 --- /dev/null +++ b/src/test/javascript/e2e/entities/region/region.spec.ts @@ -0,0 +1,64 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { RegionComponentsPage, RegionDeleteDialog, RegionUpdatePage } from './region.page-object'; + +const expect = chai.expect; + +describe('Region e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let regionUpdatePage: RegionUpdatePage; + let regionComponentsPage: RegionComponentsPage; + let regionDeleteDialog: RegionDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load Regions', async () => { + await navBarPage.goToEntity('region'); + regionComponentsPage = new RegionComponentsPage(); + await browser.wait(ec.visibilityOf(regionComponentsPage.title), 5000); + expect(await regionComponentsPage.getTitle()).to.eq('Regions'); + }); + + it('should load create Region page', async () => { + await regionComponentsPage.clickOnCreateButton(); + regionUpdatePage = new RegionUpdatePage(); + expect(await regionUpdatePage.getPageTitle()).to.eq('Create or edit a Region'); + await regionUpdatePage.cancel(); + }); + + it('should create and save Regions', async () => { + const nbButtonsBeforeCreate = await regionComponentsPage.countDeleteButtons(); + + await regionComponentsPage.clickOnCreateButton(); + await promise.all([regionUpdatePage.setRegionNameInput('regionName')]); + expect(await regionUpdatePage.getRegionNameInput()).to.eq('regionName', 'Expected RegionName value to be equals to regionName'); + await regionUpdatePage.save(); + expect(await regionUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await regionComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last Region', async () => { + const nbButtonsBeforeDelete = await regionComponentsPage.countDeleteButtons(); + await regionComponentsPage.clickOnLastDeleteButton(); + + regionDeleteDialog = new RegionDeleteDialog(); + expect(await regionDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Region?'); + await regionDeleteDialog.clickOnConfirmButton(); + + expect(await regionComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/e2e/entities/task/task.page-object.ts b/src/test/javascript/e2e/entities/task/task.page-object.ts new file mode 100644 index 0000000..a44acf6 --- /dev/null +++ b/src/test/javascript/e2e/entities/task/task.page-object.ts @@ -0,0 +1,76 @@ +import { browser, ExpectedConditions, element, by, ElementFinder } from 'protractor'; + +export class TaskComponentsPage { + createButton = element(by.id('jh-create-entity')); + deleteButtons = element.all(by.css('jhi-task div table .btn-danger')); + title = element.all(by.css('jhi-task div h2#page-heading span')).first(); + + async clickOnCreateButton(timeout?: number) { + await this.createButton.click(); + } + + async clickOnLastDeleteButton(timeout?: number) { + await this.deleteButtons.last().click(); + } + + async countDeleteButtons() { + return this.deleteButtons.count(); + } + + async getTitle() { + return this.title.getText(); + } +} + +export class TaskUpdatePage { + pageTitle = element(by.id('jhi-task-heading')); + saveButton = element(by.id('save-entity')); + cancelButton = element(by.id('cancel-save')); + titleInput = element(by.id('field_title')); + descriptionInput = element(by.id('field_description')); + + async getPageTitle() { + return this.pageTitle.getText(); + } + + async setTitleInput(title) { + await this.titleInput.sendKeys(title); + } + + async getTitleInput() { + return await this.titleInput.getAttribute('value'); + } + + async setDescriptionInput(description) { + await this.descriptionInput.sendKeys(description); + } + + async getDescriptionInput() { + return await this.descriptionInput.getAttribute('value'); + } + + async save(timeout?: number) { + await this.saveButton.click(); + } + + async cancel(timeout?: number) { + await this.cancelButton.click(); + } + + getSaveButton(): ElementFinder { + return this.saveButton; + } +} + +export class TaskDeleteDialog { + private dialogTitle = element(by.id('jhi-delete-task-heading')); + private confirmButton = element(by.id('jhi-confirm-delete-task')); + + async getDialogTitle() { + return this.dialogTitle.getText(); + } + + async clickOnConfirmButton(timeout?: number) { + await this.confirmButton.click(); + } +} diff --git a/src/test/javascript/e2e/entities/task/task.spec.ts b/src/test/javascript/e2e/entities/task/task.spec.ts new file mode 100644 index 0000000..99873da --- /dev/null +++ b/src/test/javascript/e2e/entities/task/task.spec.ts @@ -0,0 +1,65 @@ +/* tslint:disable no-unused-expression */ +import { browser, ExpectedConditions as ec, promise } from 'protractor'; +import { NavBarPage, SignInPage } from '../../page-objects/jhi-page-objects'; + +import { TaskComponentsPage, TaskDeleteDialog, TaskUpdatePage } from './task.page-object'; + +const expect = chai.expect; + +describe('Task e2e test', () => { + let navBarPage: NavBarPage; + let signInPage: SignInPage; + let taskUpdatePage: TaskUpdatePage; + let taskComponentsPage: TaskComponentsPage; + let taskDeleteDialog: TaskDeleteDialog; + + before(async () => { + await browser.get('/'); + navBarPage = new NavBarPage(); + signInPage = await navBarPage.getSignInPage(); + await signInPage.autoSignInUsing('admin', 'admin'); + await browser.wait(ec.visibilityOf(navBarPage.entityMenu), 5000); + }); + + it('should load Tasks', async () => { + await navBarPage.goToEntity('task'); + taskComponentsPage = new TaskComponentsPage(); + await browser.wait(ec.visibilityOf(taskComponentsPage.title), 5000); + expect(await taskComponentsPage.getTitle()).to.eq('Tasks'); + }); + + it('should load create Task page', async () => { + await taskComponentsPage.clickOnCreateButton(); + taskUpdatePage = new TaskUpdatePage(); + expect(await taskUpdatePage.getPageTitle()).to.eq('Create or edit a Task'); + await taskUpdatePage.cancel(); + }); + + it('should create and save Tasks', async () => { + const nbButtonsBeforeCreate = await taskComponentsPage.countDeleteButtons(); + + await taskComponentsPage.clickOnCreateButton(); + await promise.all([taskUpdatePage.setTitleInput('title'), taskUpdatePage.setDescriptionInput('description')]); + expect(await taskUpdatePage.getTitleInput()).to.eq('title', 'Expected Title value to be equals to title'); + expect(await taskUpdatePage.getDescriptionInput()).to.eq('description', 'Expected Description value to be equals to description'); + await taskUpdatePage.save(); + expect(await taskUpdatePage.getSaveButton().isPresent(), 'Expected save button disappear').to.be.false; + + expect(await taskComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeCreate + 1, 'Expected one more entry in the table'); + }); + + it('should delete last Task', async () => { + const nbButtonsBeforeDelete = await taskComponentsPage.countDeleteButtons(); + await taskComponentsPage.clickOnLastDeleteButton(); + + taskDeleteDialog = new TaskDeleteDialog(); + expect(await taskDeleteDialog.getDialogTitle()).to.eq('Are you sure you want to delete this Task?'); + await taskDeleteDialog.clickOnConfirmButton(); + + expect(await taskComponentsPage.countDeleteButtons()).to.eq(nbButtonsBeforeDelete - 1); + }); + + after(async () => { + await navBarPage.autoSignOut(); + }); +}); diff --git a/src/test/javascript/spec/app/entities/country/country-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/country/country-delete-dialog.component.spec.ts new file mode 100644 index 0000000..790f3f7 --- /dev/null +++ b/src/test/javascript/spec/app/entities/country/country-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { CountryDeleteDialogComponent } from 'app/entities/country/country-delete-dialog.component'; +import { CountryService } from 'app/entities/country/country.service'; + +describe('Component Tests', () => { + describe('Country Management Delete Component', () => { + let comp: CountryDeleteDialogComponent; + let fixture: ComponentFixture; + let service: CountryService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [CountryDeleteDialogComponent] + }) + .overrideTemplate(CountryDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(CountryDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(CountryService); + 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/country/country-detail.component.spec.ts b/src/test/javascript/spec/app/entities/country/country-detail.component.spec.ts new file mode 100644 index 0000000..1ab31bb --- /dev/null +++ b/src/test/javascript/spec/app/entities/country/country-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { CountryDetailComponent } from 'app/entities/country/country-detail.component'; +import { Country } from 'app/shared/model/country.model'; + +describe('Component Tests', () => { + describe('Country Management Detail Component', () => { + let comp: CountryDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ country: new Country(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [CountryDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(CountryDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(CountryDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.country).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/country/country-update.component.spec.ts b/src/test/javascript/spec/app/entities/country/country-update.component.spec.ts new file mode 100644 index 0000000..9920fd8 --- /dev/null +++ b/src/test/javascript/spec/app/entities/country/country-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { CountryUpdateComponent } from 'app/entities/country/country-update.component'; +import { CountryService } from 'app/entities/country/country.service'; +import { Country } from 'app/shared/model/country.model'; + +describe('Component Tests', () => { + describe('Country Management Update Component', () => { + let comp: CountryUpdateComponent; + let fixture: ComponentFixture; + let service: CountryService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [CountryUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(CountryUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(CountryUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(CountryService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Country(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 Country(); + 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/country/country.component.spec.ts b/src/test/javascript/spec/app/entities/country/country.component.spec.ts new file mode 100644 index 0000000..75b50ca --- /dev/null +++ b/src/test/javascript/spec/app/entities/country/country.component.spec.ts @@ -0,0 +1,51 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; + +import { VisioTestModule } from '../../../test.module'; +import { CountryComponent } from 'app/entities/country/country.component'; +import { CountryService } from 'app/entities/country/country.service'; +import { Country } from 'app/shared/model/country.model'; + +describe('Component Tests', () => { + describe('Country Management Component', () => { + let comp: CountryComponent; + let fixture: ComponentFixture; + let service: CountryService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [CountryComponent], + providers: [] + }) + .overrideTemplate(CountryComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(CountryComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(CountryService); + }); + + 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 Country(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.countries[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/country/country.service.spec.ts b/src/test/javascript/spec/app/entities/country/country.service.spec.ts new file mode 100644 index 0000000..6ac03b8 --- /dev/null +++ b/src/test/javascript/spec/app/entities/country/country.service.spec.ts @@ -0,0 +1,111 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { CountryService } from 'app/entities/country/country.service'; +import { ICountry, Country } from 'app/shared/model/country.model'; + +describe('Service Tests', () => { + describe('Country Service', () => { + let injector: TestBed; + let service: CountryService; + let httpMock: HttpTestingController; + let elemDefault: ICountry; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(CountryService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Country(0, 'AAAAAAA'); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + 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 Country', async () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Country(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 Country', async () => { + const returnedFromService = Object.assign( + { + countryName: '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 Country', async () => { + const returnedFromService = Object.assign( + { + countryName: '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 Country', async () => { + const rxPromise = 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/department/department-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/department/department-delete-dialog.component.spec.ts new file mode 100644 index 0000000..870cbc0 --- /dev/null +++ b/src/test/javascript/spec/app/entities/department/department-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { DepartmentDeleteDialogComponent } from 'app/entities/department/department-delete-dialog.component'; +import { DepartmentService } from 'app/entities/department/department.service'; + +describe('Component Tests', () => { + describe('Department Management Delete Component', () => { + let comp: DepartmentDeleteDialogComponent; + let fixture: ComponentFixture; + let service: DepartmentService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [DepartmentDeleteDialogComponent] + }) + .overrideTemplate(DepartmentDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(DepartmentDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(DepartmentService); + 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/department/department-detail.component.spec.ts b/src/test/javascript/spec/app/entities/department/department-detail.component.spec.ts new file mode 100644 index 0000000..b6efd21 --- /dev/null +++ b/src/test/javascript/spec/app/entities/department/department-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { DepartmentDetailComponent } from 'app/entities/department/department-detail.component'; +import { Department } from 'app/shared/model/department.model'; + +describe('Component Tests', () => { + describe('Department Management Detail Component', () => { + let comp: DepartmentDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ department: new Department(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [DepartmentDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(DepartmentDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(DepartmentDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.department).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/department/department-update.component.spec.ts b/src/test/javascript/spec/app/entities/department/department-update.component.spec.ts new file mode 100644 index 0000000..a01ef0a --- /dev/null +++ b/src/test/javascript/spec/app/entities/department/department-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { DepartmentUpdateComponent } from 'app/entities/department/department-update.component'; +import { DepartmentService } from 'app/entities/department/department.service'; +import { Department } from 'app/shared/model/department.model'; + +describe('Component Tests', () => { + describe('Department Management Update Component', () => { + let comp: DepartmentUpdateComponent; + let fixture: ComponentFixture; + let service: DepartmentService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [DepartmentUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(DepartmentUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(DepartmentUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(DepartmentService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Department(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 Department(); + 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/department/department.component.spec.ts b/src/test/javascript/spec/app/entities/department/department.component.spec.ts new file mode 100644 index 0000000..583a49c --- /dev/null +++ b/src/test/javascript/spec/app/entities/department/department.component.spec.ts @@ -0,0 +1,51 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; + +import { VisioTestModule } from '../../../test.module'; +import { DepartmentComponent } from 'app/entities/department/department.component'; +import { DepartmentService } from 'app/entities/department/department.service'; +import { Department } from 'app/shared/model/department.model'; + +describe('Component Tests', () => { + describe('Department Management Component', () => { + let comp: DepartmentComponent; + let fixture: ComponentFixture; + let service: DepartmentService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [DepartmentComponent], + providers: [] + }) + .overrideTemplate(DepartmentComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(DepartmentComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(DepartmentService); + }); + + 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 Department(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.departments[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/department/department.service.spec.ts b/src/test/javascript/spec/app/entities/department/department.service.spec.ts new file mode 100644 index 0000000..b0ae80c --- /dev/null +++ b/src/test/javascript/spec/app/entities/department/department.service.spec.ts @@ -0,0 +1,111 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { DepartmentService } from 'app/entities/department/department.service'; +import { IDepartment, Department } from 'app/shared/model/department.model'; + +describe('Service Tests', () => { + describe('Department Service', () => { + let injector: TestBed; + let service: DepartmentService; + let httpMock: HttpTestingController; + let elemDefault: IDepartment; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(DepartmentService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Department(0, 'AAAAAAA'); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + 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 Department', async () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Department(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 Department', async () => { + const returnedFromService = Object.assign( + { + departmentName: '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 Department', async () => { + const returnedFromService = Object.assign( + { + departmentName: '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 Department', async () => { + const rxPromise = 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/employee/employee-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/employee/employee-delete-dialog.component.spec.ts new file mode 100644 index 0000000..4a16d5d --- /dev/null +++ b/src/test/javascript/spec/app/entities/employee/employee-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { EmployeeDeleteDialogComponent } from 'app/entities/employee/employee-delete-dialog.component'; +import { EmployeeService } from 'app/entities/employee/employee.service'; + +describe('Component Tests', () => { + describe('Employee Management Delete Component', () => { + let comp: EmployeeDeleteDialogComponent; + let fixture: ComponentFixture; + let service: EmployeeService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [EmployeeDeleteDialogComponent] + }) + .overrideTemplate(EmployeeDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(EmployeeDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(EmployeeService); + 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/employee/employee-detail.component.spec.ts b/src/test/javascript/spec/app/entities/employee/employee-detail.component.spec.ts new file mode 100644 index 0000000..ac377a5 --- /dev/null +++ b/src/test/javascript/spec/app/entities/employee/employee-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { EmployeeDetailComponent } from 'app/entities/employee/employee-detail.component'; +import { Employee } from 'app/shared/model/employee.model'; + +describe('Component Tests', () => { + describe('Employee Management Detail Component', () => { + let comp: EmployeeDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ employee: new Employee(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [EmployeeDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(EmployeeDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(EmployeeDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.employee).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/employee/employee-update.component.spec.ts b/src/test/javascript/spec/app/entities/employee/employee-update.component.spec.ts new file mode 100644 index 0000000..e52e19c --- /dev/null +++ b/src/test/javascript/spec/app/entities/employee/employee-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { EmployeeUpdateComponent } from 'app/entities/employee/employee-update.component'; +import { EmployeeService } from 'app/entities/employee/employee.service'; +import { Employee } from 'app/shared/model/employee.model'; + +describe('Component Tests', () => { + describe('Employee Management Update Component', () => { + let comp: EmployeeUpdateComponent; + let fixture: ComponentFixture; + let service: EmployeeService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [EmployeeUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(EmployeeUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(EmployeeUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(EmployeeService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Employee(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 Employee(); + 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/employee/employee.component.spec.ts b/src/test/javascript/spec/app/entities/employee/employee.component.spec.ts new file mode 100644 index 0000000..c88d984 --- /dev/null +++ b/src/test/javascript/spec/app/entities/employee/employee.component.spec.ts @@ -0,0 +1,128 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Data } from '@angular/router'; + +import { VisioTestModule } from '../../../test.module'; +import { EmployeeComponent } from 'app/entities/employee/employee.component'; +import { EmployeeService } from 'app/entities/employee/employee.service'; +import { Employee } from 'app/shared/model/employee.model'; + +describe('Component Tests', () => { + describe('Employee Management Component', () => { + let comp: EmployeeComponent; + let fixture: ComponentFixture; + let service: EmployeeService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [EmployeeComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => + fn({ + pagingParams: { + predicate: 'id', + reverse: false, + page: 0 + } + }) + } + } + } + ] + }) + .overrideTemplate(EmployeeComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(EmployeeComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(EmployeeService); + }); + + 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 Employee(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.employees[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 Employee(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.employees[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should re-initialize the page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new Employee(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + comp.reset(); + + // THEN + expect(comp.page).toEqual(0); + expect(service.query).toHaveBeenCalledTimes(2); + expect(comp.employees[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + it('should calculate the sort attribute for an id', () => { + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['id,asc']); + }); + + it('should calculate the sort attribute for a non-id attribute', () => { + // GIVEN + comp.predicate = 'name'; + + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['name,asc', 'id']); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/employee/employee.service.spec.ts b/src/test/javascript/spec/app/entities/employee/employee.service.spec.ts new file mode 100644 index 0000000..a90a88c --- /dev/null +++ b/src/test/javascript/spec/app/entities/employee/employee.service.spec.ts @@ -0,0 +1,148 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import * as moment from 'moment'; +import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; +import { EmployeeService } from 'app/entities/employee/employee.service'; +import { IEmployee, Employee } from 'app/shared/model/employee.model'; + +describe('Service Tests', () => { + describe('Employee Service', () => { + let injector: TestBed; + let service: EmployeeService; + let httpMock: HttpTestingController; + let elemDefault: IEmployee; + let expectedResult; + let currentDate: moment.Moment; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(EmployeeService); + httpMock = injector.get(HttpTestingController); + currentDate = moment(); + + elemDefault = new Employee(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', currentDate, 0, 0); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + const returnedFromService = Object.assign( + { + hireDate: currentDate.format(DATE_TIME_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 Employee', async () => { + const returnedFromService = Object.assign( + { + id: 0, + hireDate: currentDate.format(DATE_TIME_FORMAT) + }, + elemDefault + ); + const expected = Object.assign( + { + hireDate: currentDate + }, + returnedFromService + ); + service + .create(new Employee(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 Employee', async () => { + const returnedFromService = Object.assign( + { + firstName: 'BBBBBB', + lastName: 'BBBBBB', + email: 'BBBBBB', + phoneNumber: 'BBBBBB', + hireDate: currentDate.format(DATE_TIME_FORMAT), + salary: 1, + commissionPct: 1 + }, + elemDefault + ); + + const expected = Object.assign( + { + hireDate: 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 Employee', async () => { + const returnedFromService = Object.assign( + { + firstName: 'BBBBBB', + lastName: 'BBBBBB', + email: 'BBBBBB', + phoneNumber: 'BBBBBB', + hireDate: currentDate.format(DATE_TIME_FORMAT), + salary: 1, + commissionPct: 1 + }, + elemDefault + ); + const expected = Object.assign( + { + hireDate: 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 Employee', async () => { + const rxPromise = 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/job-history/job-history-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/job-history/job-history-delete-dialog.component.spec.ts new file mode 100644 index 0000000..3caa1d2 --- /dev/null +++ b/src/test/javascript/spec/app/entities/job-history/job-history-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { JobHistoryDeleteDialogComponent } from 'app/entities/job-history/job-history-delete-dialog.component'; +import { JobHistoryService } from 'app/entities/job-history/job-history.service'; + +describe('Component Tests', () => { + describe('JobHistory Management Delete Component', () => { + let comp: JobHistoryDeleteDialogComponent; + let fixture: ComponentFixture; + let service: JobHistoryService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobHistoryDeleteDialogComponent] + }) + .overrideTemplate(JobHistoryDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(JobHistoryDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JobHistoryService); + 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/job-history/job-history-detail.component.spec.ts b/src/test/javascript/spec/app/entities/job-history/job-history-detail.component.spec.ts new file mode 100644 index 0000000..c75170b --- /dev/null +++ b/src/test/javascript/spec/app/entities/job-history/job-history-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { JobHistoryDetailComponent } from 'app/entities/job-history/job-history-detail.component'; +import { JobHistory } from 'app/shared/model/job-history.model'; + +describe('Component Tests', () => { + describe('JobHistory Management Detail Component', () => { + let comp: JobHistoryDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ jobHistory: new JobHistory(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobHistoryDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(JobHistoryDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(JobHistoryDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.jobHistory).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/job-history/job-history-update.component.spec.ts b/src/test/javascript/spec/app/entities/job-history/job-history-update.component.spec.ts new file mode 100644 index 0000000..3f40a41 --- /dev/null +++ b/src/test/javascript/spec/app/entities/job-history/job-history-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { JobHistoryUpdateComponent } from 'app/entities/job-history/job-history-update.component'; +import { JobHistoryService } from 'app/entities/job-history/job-history.service'; +import { JobHistory } from 'app/shared/model/job-history.model'; + +describe('Component Tests', () => { + describe('JobHistory Management Update Component', () => { + let comp: JobHistoryUpdateComponent; + let fixture: ComponentFixture; + let service: JobHistoryService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobHistoryUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(JobHistoryUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(JobHistoryUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JobHistoryService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new JobHistory(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 JobHistory(); + 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/job-history/job-history.component.spec.ts b/src/test/javascript/spec/app/entities/job-history/job-history.component.spec.ts new file mode 100644 index 0000000..a0e54bd --- /dev/null +++ b/src/test/javascript/spec/app/entities/job-history/job-history.component.spec.ts @@ -0,0 +1,128 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Data } from '@angular/router'; + +import { VisioTestModule } from '../../../test.module'; +import { JobHistoryComponent } from 'app/entities/job-history/job-history.component'; +import { JobHistoryService } from 'app/entities/job-history/job-history.service'; +import { JobHistory } from 'app/shared/model/job-history.model'; + +describe('Component Tests', () => { + describe('JobHistory Management Component', () => { + let comp: JobHistoryComponent; + let fixture: ComponentFixture; + let service: JobHistoryService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobHistoryComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => + fn({ + pagingParams: { + predicate: 'id', + reverse: false, + page: 0 + } + }) + } + } + } + ] + }) + .overrideTemplate(JobHistoryComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(JobHistoryComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JobHistoryService); + }); + + 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 JobHistory(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.jobHistories[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 JobHistory(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.jobHistories[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + + it('should re-initialize the page', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [new JobHistory(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + comp.reset(); + + // THEN + expect(comp.page).toEqual(0); + expect(service.query).toHaveBeenCalledTimes(2); + expect(comp.jobHistories[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + it('should calculate the sort attribute for an id', () => { + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['id,asc']); + }); + + it('should calculate the sort attribute for a non-id attribute', () => { + // GIVEN + comp.predicate = 'name'; + + // WHEN + const result = comp.sort(); + + // THEN + expect(result).toEqual(['name,asc', 'id']); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/job-history/job-history.service.spec.ts b/src/test/javascript/spec/app/entities/job-history/job-history.service.spec.ts new file mode 100644 index 0000000..94bad50 --- /dev/null +++ b/src/test/javascript/spec/app/entities/job-history/job-history.service.spec.ts @@ -0,0 +1,145 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import * as moment from 'moment'; +import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; +import { JobHistoryService } from 'app/entities/job-history/job-history.service'; +import { IJobHistory, JobHistory, Language } from 'app/shared/model/job-history.model'; + +describe('Service Tests', () => { + describe('JobHistory Service', () => { + let injector: TestBed; + let service: JobHistoryService; + let httpMock: HttpTestingController; + let elemDefault: IJobHistory; + let expectedResult; + let currentDate: moment.Moment; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(JobHistoryService); + httpMock = injector.get(HttpTestingController); + currentDate = moment(); + + elemDefault = new JobHistory(0, currentDate, currentDate, Language.FRENCH); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + const returnedFromService = Object.assign( + { + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_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 JobHistory', async () => { + const returnedFromService = Object.assign( + { + id: 0, + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_FORMAT) + }, + elemDefault + ); + const expected = Object.assign( + { + startDate: currentDate, + endDate: currentDate + }, + returnedFromService + ); + service + .create(new JobHistory(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 JobHistory', async () => { + const returnedFromService = Object.assign( + { + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_FORMAT), + language: 'BBBBBB' + }, + elemDefault + ); + + const expected = Object.assign( + { + startDate: currentDate, + endDate: 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 JobHistory', async () => { + const returnedFromService = Object.assign( + { + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_FORMAT), + language: 'BBBBBB' + }, + elemDefault + ); + const expected = Object.assign( + { + startDate: currentDate, + endDate: 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 JobHistory', async () => { + const rxPromise = 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/job/job-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/job/job-delete-dialog.component.spec.ts new file mode 100644 index 0000000..253b6d0 --- /dev/null +++ b/src/test/javascript/spec/app/entities/job/job-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { JobDeleteDialogComponent } from 'app/entities/job/job-delete-dialog.component'; +import { JobService } from 'app/entities/job/job.service'; + +describe('Component Tests', () => { + describe('Job Management Delete Component', () => { + let comp: JobDeleteDialogComponent; + let fixture: ComponentFixture; + let service: JobService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobDeleteDialogComponent] + }) + .overrideTemplate(JobDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(JobDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JobService); + 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/job/job-detail.component.spec.ts b/src/test/javascript/spec/app/entities/job/job-detail.component.spec.ts new file mode 100644 index 0000000..a75e583 --- /dev/null +++ b/src/test/javascript/spec/app/entities/job/job-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { JobDetailComponent } from 'app/entities/job/job-detail.component'; +import { Job } from 'app/shared/model/job.model'; + +describe('Component Tests', () => { + describe('Job Management Detail Component', () => { + let comp: JobDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ job: new Job(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(JobDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(JobDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.job).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/job/job-update.component.spec.ts b/src/test/javascript/spec/app/entities/job/job-update.component.spec.ts new file mode 100644 index 0000000..93f0759 --- /dev/null +++ b/src/test/javascript/spec/app/entities/job/job-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { JobUpdateComponent } from 'app/entities/job/job-update.component'; +import { JobService } from 'app/entities/job/job.service'; +import { Job } from 'app/shared/model/job.model'; + +describe('Component Tests', () => { + describe('Job Management Update Component', () => { + let comp: JobUpdateComponent; + let fixture: ComponentFixture; + let service: JobService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(JobUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(JobUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JobService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Job(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 Job(); + 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/job/job.component.spec.ts b/src/test/javascript/spec/app/entities/job/job.component.spec.ts new file mode 100644 index 0000000..a174e9e --- /dev/null +++ b/src/test/javascript/spec/app/entities/job/job.component.spec.ts @@ -0,0 +1,138 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, Data } from '@angular/router'; + +import { VisioTestModule } from '../../../test.module'; +import { JobComponent } from 'app/entities/job/job.component'; +import { JobService } from 'app/entities/job/job.service'; +import { Job } from 'app/shared/model/job.model'; + +describe('Component Tests', () => { + describe('Job Management Component', () => { + let comp: JobComponent; + let fixture: ComponentFixture; + let service: JobService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [JobComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => + fn({ + pagingParams: { + predicate: 'id', + reverse: false, + page: 0 + } + }) + } + } + } + ] + }) + .overrideTemplate(JobComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(JobComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JobService); + }); + + 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 Job(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.jobs[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 Job(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.jobs[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 Job(123)], + headers + }) + ) + ); + + // WHEN + comp.loadPage(1); + comp.clear(); + + // THEN + expect(comp.page).toEqual(0); + expect(service.query).toHaveBeenCalledTimes(2); + expect(comp.jobs[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/job/job.service.spec.ts b/src/test/javascript/spec/app/entities/job/job.service.spec.ts new file mode 100644 index 0000000..a23439d --- /dev/null +++ b/src/test/javascript/spec/app/entities/job/job.service.spec.ts @@ -0,0 +1,115 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { JobService } from 'app/entities/job/job.service'; +import { IJob, Job } from 'app/shared/model/job.model'; + +describe('Service Tests', () => { + describe('Job Service', () => { + let injector: TestBed; + let service: JobService; + let httpMock: HttpTestingController; + let elemDefault: IJob; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(JobService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Job(0, 'AAAAAAA', 0, 0); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + 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 Job', async () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Job(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 Job', async () => { + const returnedFromService = Object.assign( + { + jobTitle: 'BBBBBB', + minSalary: 1, + maxSalary: 1 + }, + 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 Job', async () => { + const returnedFromService = Object.assign( + { + jobTitle: 'BBBBBB', + minSalary: 1, + maxSalary: 1 + }, + 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 Job', async () => { + const rxPromise = 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/location/location-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/location/location-delete-dialog.component.spec.ts new file mode 100644 index 0000000..b29969e --- /dev/null +++ b/src/test/javascript/spec/app/entities/location/location-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { LocationDeleteDialogComponent } from 'app/entities/location/location-delete-dialog.component'; +import { LocationService } from 'app/entities/location/location.service'; + +describe('Component Tests', () => { + describe('Location Management Delete Component', () => { + let comp: LocationDeleteDialogComponent; + let fixture: ComponentFixture; + let service: LocationService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [LocationDeleteDialogComponent] + }) + .overrideTemplate(LocationDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(LocationDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(LocationService); + 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/location/location-detail.component.spec.ts b/src/test/javascript/spec/app/entities/location/location-detail.component.spec.ts new file mode 100644 index 0000000..a347b0b --- /dev/null +++ b/src/test/javascript/spec/app/entities/location/location-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { LocationDetailComponent } from 'app/entities/location/location-detail.component'; +import { Location } from 'app/shared/model/location.model'; + +describe('Component Tests', () => { + describe('Location Management Detail Component', () => { + let comp: LocationDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ location: new Location(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [LocationDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(LocationDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(LocationDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.location).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/location/location-update.component.spec.ts b/src/test/javascript/spec/app/entities/location/location-update.component.spec.ts new file mode 100644 index 0000000..c50e0ce --- /dev/null +++ b/src/test/javascript/spec/app/entities/location/location-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { LocationUpdateComponent } from 'app/entities/location/location-update.component'; +import { LocationService } from 'app/entities/location/location.service'; +import { Location } from 'app/shared/model/location.model'; + +describe('Component Tests', () => { + describe('Location Management Update Component', () => { + let comp: LocationUpdateComponent; + let fixture: ComponentFixture; + let service: LocationService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [LocationUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(LocationUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(LocationUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(LocationService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Location(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 Location(); + 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/location/location.component.spec.ts b/src/test/javascript/spec/app/entities/location/location.component.spec.ts new file mode 100644 index 0000000..f5ea101 --- /dev/null +++ b/src/test/javascript/spec/app/entities/location/location.component.spec.ts @@ -0,0 +1,51 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; + +import { VisioTestModule } from '../../../test.module'; +import { LocationComponent } from 'app/entities/location/location.component'; +import { LocationService } from 'app/entities/location/location.service'; +import { Location } from 'app/shared/model/location.model'; + +describe('Component Tests', () => { + describe('Location Management Component', () => { + let comp: LocationComponent; + let fixture: ComponentFixture; + let service: LocationService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [LocationComponent], + providers: [] + }) + .overrideTemplate(LocationComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(LocationComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(LocationService); + }); + + 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 Location(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.locations[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/location/location.service.spec.ts b/src/test/javascript/spec/app/entities/location/location.service.spec.ts new file mode 100644 index 0000000..2306b8b --- /dev/null +++ b/src/test/javascript/spec/app/entities/location/location.service.spec.ts @@ -0,0 +1,117 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { LocationService } from 'app/entities/location/location.service'; +import { ILocation, Location } from 'app/shared/model/location.model'; + +describe('Service Tests', () => { + describe('Location Service', () => { + let injector: TestBed; + let service: LocationService; + let httpMock: HttpTestingController; + let elemDefault: ILocation; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(LocationService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Location(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', 'AAAAAAA'); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + 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 Location', async () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Location(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 Location', async () => { + const returnedFromService = Object.assign( + { + streetAddress: 'BBBBBB', + postalCode: 'BBBBBB', + city: 'BBBBBB', + stateProvince: '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 Location', async () => { + const returnedFromService = Object.assign( + { + streetAddress: 'BBBBBB', + postalCode: 'BBBBBB', + city: 'BBBBBB', + stateProvince: '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 Location', async () => { + const rxPromise = 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/region/region-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/region/region-delete-dialog.component.spec.ts new file mode 100644 index 0000000..02d5eef --- /dev/null +++ b/src/test/javascript/spec/app/entities/region/region-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { RegionDeleteDialogComponent } from 'app/entities/region/region-delete-dialog.component'; +import { RegionService } from 'app/entities/region/region.service'; + +describe('Component Tests', () => { + describe('Region Management Delete Component', () => { + let comp: RegionDeleteDialogComponent; + let fixture: ComponentFixture; + let service: RegionService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [RegionDeleteDialogComponent] + }) + .overrideTemplate(RegionDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(RegionDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(RegionService); + 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/region/region-detail.component.spec.ts b/src/test/javascript/spec/app/entities/region/region-detail.component.spec.ts new file mode 100644 index 0000000..81ba79f --- /dev/null +++ b/src/test/javascript/spec/app/entities/region/region-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { RegionDetailComponent } from 'app/entities/region/region-detail.component'; +import { Region } from 'app/shared/model/region.model'; + +describe('Component Tests', () => { + describe('Region Management Detail Component', () => { + let comp: RegionDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ region: new Region(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [RegionDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(RegionDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(RegionDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.region).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/region/region-update.component.spec.ts b/src/test/javascript/spec/app/entities/region/region-update.component.spec.ts new file mode 100644 index 0000000..30a8abb --- /dev/null +++ b/src/test/javascript/spec/app/entities/region/region-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { RegionUpdateComponent } from 'app/entities/region/region-update.component'; +import { RegionService } from 'app/entities/region/region.service'; +import { Region } from 'app/shared/model/region.model'; + +describe('Component Tests', () => { + describe('Region Management Update Component', () => { + let comp: RegionUpdateComponent; + let fixture: ComponentFixture; + let service: RegionService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [RegionUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(RegionUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(RegionUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(RegionService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Region(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 Region(); + 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/region/region.component.spec.ts b/src/test/javascript/spec/app/entities/region/region.component.spec.ts new file mode 100644 index 0000000..320a5bb --- /dev/null +++ b/src/test/javascript/spec/app/entities/region/region.component.spec.ts @@ -0,0 +1,51 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; + +import { VisioTestModule } from '../../../test.module'; +import { RegionComponent } from 'app/entities/region/region.component'; +import { RegionService } from 'app/entities/region/region.service'; +import { Region } from 'app/shared/model/region.model'; + +describe('Component Tests', () => { + describe('Region Management Component', () => { + let comp: RegionComponent; + let fixture: ComponentFixture; + let service: RegionService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [RegionComponent], + providers: [] + }) + .overrideTemplate(RegionComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(RegionComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(RegionService); + }); + + 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 Region(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.regions[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/region/region.service.spec.ts b/src/test/javascript/spec/app/entities/region/region.service.spec.ts new file mode 100644 index 0000000..6f875d1 --- /dev/null +++ b/src/test/javascript/spec/app/entities/region/region.service.spec.ts @@ -0,0 +1,111 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { RegionService } from 'app/entities/region/region.service'; +import { IRegion, Region } from 'app/shared/model/region.model'; + +describe('Service Tests', () => { + describe('Region Service', () => { + let injector: TestBed; + let service: RegionService; + let httpMock: HttpTestingController; + let elemDefault: IRegion; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(RegionService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Region(0, 'AAAAAAA'); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + 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 Region', async () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Region(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 Region', async () => { + const returnedFromService = Object.assign( + { + regionName: '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 Region', async () => { + const returnedFromService = Object.assign( + { + regionName: '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 Region', async () => { + const rxPromise = 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/task/task-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/task/task-delete-dialog.component.spec.ts new file mode 100644 index 0000000..db16ba2 --- /dev/null +++ b/src/test/javascript/spec/app/entities/task/task-delete-dialog.component.spec.ts @@ -0,0 +1,52 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { Observable, of } from 'rxjs'; +import { JhiEventManager } from 'ng-jhipster'; + +import { VisioTestModule } from '../../../test.module'; +import { TaskDeleteDialogComponent } from 'app/entities/task/task-delete-dialog.component'; +import { TaskService } from 'app/entities/task/task.service'; + +describe('Component Tests', () => { + describe('Task Management Delete Component', () => { + let comp: TaskDeleteDialogComponent; + let fixture: ComponentFixture; + let service: TaskService; + let mockEventManager: any; + let mockActiveModal: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [TaskDeleteDialogComponent] + }) + .overrideTemplate(TaskDeleteDialogComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(TaskDeleteDialogComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(TaskService); + 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/task/task-detail.component.spec.ts b/src/test/javascript/spec/app/entities/task/task-detail.component.spec.ts new file mode 100644 index 0000000..5c42d98 --- /dev/null +++ b/src/test/javascript/spec/app/entities/task/task-detail.component.spec.ts @@ -0,0 +1,40 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { TaskDetailComponent } from 'app/entities/task/task-detail.component'; +import { Task } from 'app/shared/model/task.model'; + +describe('Component Tests', () => { + describe('Task Management Detail Component', () => { + let comp: TaskDetailComponent; + let fixture: ComponentFixture; + const route = ({ data: of({ task: new Task(123) }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [TaskDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }] + }) + .overrideTemplate(TaskDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(TaskDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.task).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/task/task-update.component.spec.ts b/src/test/javascript/spec/app/entities/task/task-update.component.spec.ts new file mode 100644 index 0000000..5b2c37b --- /dev/null +++ b/src/test/javascript/spec/app/entities/task/task-update.component.spec.ts @@ -0,0 +1,62 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { FormBuilder } from '@angular/forms'; +import { Observable, of } from 'rxjs'; + +import { VisioTestModule } from '../../../test.module'; +import { TaskUpdateComponent } from 'app/entities/task/task-update.component'; +import { TaskService } from 'app/entities/task/task.service'; +import { Task } from 'app/shared/model/task.model'; + +describe('Component Tests', () => { + describe('Task Management Update Component', () => { + let comp: TaskUpdateComponent; + let fixture: ComponentFixture; + let service: TaskService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [TaskUpdateComponent], + providers: [FormBuilder] + }) + .overrideTemplate(TaskUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(TaskUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(TaskService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Task(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 Task(); + 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/task/task.component.spec.ts b/src/test/javascript/spec/app/entities/task/task.component.spec.ts new file mode 100644 index 0000000..976d8b0 --- /dev/null +++ b/src/test/javascript/spec/app/entities/task/task.component.spec.ts @@ -0,0 +1,51 @@ +/* tslint:disable max-line-length */ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Observable, of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; + +import { VisioTestModule } from '../../../test.module'; +import { TaskComponent } from 'app/entities/task/task.component'; +import { TaskService } from 'app/entities/task/task.service'; +import { Task } from 'app/shared/model/task.model'; + +describe('Component Tests', () => { + describe('Task Management Component', () => { + let comp: TaskComponent; + let fixture: ComponentFixture; + let service: TaskService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [VisioTestModule], + declarations: [TaskComponent], + providers: [] + }) + .overrideTemplate(TaskComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(TaskComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(TaskService); + }); + + 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 Task(123)], + headers + }) + ) + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.tasks[0]).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); +}); diff --git a/src/test/javascript/spec/app/entities/task/task.service.spec.ts b/src/test/javascript/spec/app/entities/task/task.service.spec.ts new file mode 100644 index 0000000..c543093 --- /dev/null +++ b/src/test/javascript/spec/app/entities/task/task.service.spec.ts @@ -0,0 +1,113 @@ +/* tslint:disable max-line-length */ +import { TestBed, getTestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpClient, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { take, map } from 'rxjs/operators'; +import { TaskService } from 'app/entities/task/task.service'; +import { ITask, Task } from 'app/shared/model/task.model'; + +describe('Service Tests', () => { + describe('Task Service', () => { + let injector: TestBed; + let service: TaskService; + let httpMock: HttpTestingController; + let elemDefault: ITask; + let expectedResult; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule] + }); + expectedResult = {}; + injector = getTestBed(); + service = injector.get(TaskService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new Task(0, 'AAAAAAA', 'AAAAAAA'); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + 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 Task', async () => { + const returnedFromService = Object.assign( + { + id: 0 + }, + elemDefault + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new Task(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 Task', async () => { + const returnedFromService = Object.assign( + { + title: 'BBBBBB', + description: '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 Task', async () => { + const returnedFromService = Object.assign( + { + title: 'BBBBBB', + description: '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 Task', async () => { + const rxPromise = service.delete(123).subscribe(resp => (expectedResult = resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + expect(expectedResult); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); + }); +});