You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

232 lines
10.0KB

  1. package vn.azteam.tpf.web.rest;
  2. import com.codahale.metrics.annotation.Timed;
  3. import io.github.jhipster.web.util.ResponseUtil;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.data.domain.Page;
  8. import org.springframework.data.domain.Pageable;
  9. import org.springframework.http.HttpHeaders;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.web.bind.annotation.*;
  12. import vn.azteam.tpf.domain.TBCodeStatusEnum;
  13. import vn.azteam.tpf.service.*;
  14. import vn.azteam.tpf.service.dto.*;
  15. import vn.azteam.tpf.service.util.PageableUtil;
  16. import vn.azteam.tpf.service.util.UserRoleUtil;
  17. import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;
  18. import vn.azteam.tpf.web.rest.util.HeaderUtil;
  19. import vn.azteam.tpf.web.rest.util.PaginationUtil;
  20. import vn.azteam.tpf.web.rest.util.RandomStringUtil;
  21. import java.net.URI;
  22. import java.net.URISyntaxException;
  23. import java.time.Instant;
  24. import java.util.ArrayList;
  25. import java.util.Comparator;
  26. import java.util.List;
  27. import java.util.Optional;
  28. import java.util.stream.Collectors;
  29. @RestController
  30. @RequestMapping("/api")
  31. public class TBCodeResource {
  32. private static final String ENTITY_NAME = "tBCode";
  33. private final Logger log = LoggerFactory.getLogger(TBCodeResource.class);
  34. private final TBCodeService tBCodeService;
  35. private final TBCodeDetailsService tbCodeDetailsService;
  36. private final TBCropService tBCropService;
  37. private final UserService userService;
  38. private final TBCodeQueryService tBCodeQueryService;
  39. private final UserRoleUtil userRoleUtil;
  40. private final PageableUtil pageableUtil;
  41. public TBCodeResource(TBCodeService tBCodeService, TBCodeDetailsService tbCodeDetailsService, TBCropService tBCropService, UserService userService, TBCodeQueryService tBCodeQueryService, UserRoleUtil userRoleUtil, PageableUtil pageableUtil) {
  42. this.tBCodeService = tBCodeService;
  43. this.tbCodeDetailsService = tbCodeDetailsService;
  44. this.tBCropService = tBCropService;
  45. this.userService = userService;
  46. this.tBCodeQueryService = tBCodeQueryService;
  47. this.userRoleUtil = userRoleUtil;
  48. this.pageableUtil = pageableUtil;
  49. }
  50. /**
  51. * GET /tb-codes-dropdown-list : get all the tBCode for dropdown options.
  52. *
  53. * @param criteria the criterias which the requested entities should match
  54. * @return the ResponseEntity with status 200 (OK) and the list of tBCode in body
  55. */
  56. @GetMapping("/tb-codes/dropdown-list")
  57. @Timed
  58. public ResponseEntity<List<TBCodeDTO>> getAllTBCodesForDropdown(TBCodeCriteria criteria) {
  59. log.debug("REST request to get TBCodes by criteria: {}", criteria);
  60. Page<TBCodeDTO> page = tBCodeQueryService.findByCriteria(criteria, Pageable.unpaged());
  61. //Authorize get list crop by customer of current user
  62. List<TBCodeDTO> result = page.getContent().stream()
  63. .filter(item -> userRoleUtil.currentUserHasPermissionByCustomerId(item.getId())
  64. && userRoleUtil.currentUserHasPermissionByCropId(item.getId()))
  65. .sorted(Comparator.comparing(
  66. TBCodeDTO::getCreatedDate,
  67. Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
  68. .collect(Collectors.toList());
  69. return ResponseEntity.ok().headers(null).body(result);
  70. }
  71. /**
  72. * GET /tb-codes : get all the tBCodes.
  73. *
  74. * @param pageable the pagination information
  75. * @param criteria the criterias which the requested entities should match
  76. * @return the ResponseEntity with status 200 (OK) and the list of tBCrops in body
  77. */
  78. @GetMapping("/tb-codes")
  79. @Timed
  80. public ResponseEntity<List<TBCodeDTO>> getAllTBCodes(TBCodeCriteria criteria, Pageable pageable) {
  81. log.debug("REST request to get TBCrops by criteria: {}", criteria);
  82. Page<TBCodeDTO> page = tBCodeQueryService.findByCriteria(criteria, Pageable.unpaged());
  83. //Authorize get list crop by customer of current user
  84. List<TBCodeDTO> result = page.getContent().stream()
  85. .filter(item -> userRoleUtil.currentUserHasPermissionByCustomerId(item.getId())
  86. && userRoleUtil.currentUserHasPermissionByCropId(item.getId()))
  87. .sorted(Comparator.comparing(
  88. TBCodeDTO::getCreatedDate,
  89. Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
  90. .collect(Collectors.toList());
  91. Page<TBCodeDTO> pageResult = pageableUtil.changeTBCodeDTOToPageFromList(result, pageable);
  92. for (TBCodeDTO itemResult : result) {
  93. //logger.error("Start date: " + itemResult.getStartDate());
  94. }
  95. HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(pageResult, "/api/tb-codes");
  96. return ResponseEntity.ok().headers(headers).body(pageResult.getContent());
  97. }
  98. @PostMapping("/tb-codes")
  99. @Timed
  100. public ResponseEntity<TBCodeDTO> createTBCrop(@RequestBody TBCodeCreationDTO tBCodeCreationDTO) throws URISyntaxException {
  101. log.debug("REST request to save TBCode : {}", tBCodeCreationDTO);
  102. //Set created by to current user login
  103. UserDTO currentUser = userService.getCurrentUserDTO().get();
  104. if (tBCodeCreationDTO.gettBCropId() != null) {
  105. throw new BadRequestAlertException("1047", ENTITY_NAME, "1047");
  106. }
  107. if (tBCodeCreationDTO.getQuantity() != null && tBCodeCreationDTO.getQuantity() <= 0) {
  108. throw new BadRequestAlertException("1047", ENTITY_NAME, "1047");
  109. }
  110. Optional<TBCropDTO> tbCropDTO = tBCropService.findOne(tBCodeCreationDTO.gettBCropId());
  111. if (!tbCropDTO.isPresent()) {
  112. throw new BadRequestAlertException("1019", ENTITY_NAME, "1019");
  113. }
  114. try {
  115. TBCodeDTO tBCodeDTO = new TBCodeDTO();
  116. tBCodeDTO.setTbCrop(tbCropDTO.get());
  117. tBCodeDTO.setDescription(StringUtils.isNotBlank(tBCodeCreationDTO.getDescription()) ?
  118. tBCodeCreationDTO.getDescription() : "");
  119. tBCodeDTO.setQuantity(tBCodeCreationDTO.getQuantity());
  120. tBCodeDTO.setPathImage(StringUtils.isNotBlank(tBCodeCreationDTO.getPathImage()) ?
  121. tBCodeCreationDTO.getPathImage() : "");
  122. tBCodeDTO.setCreatedDate(Instant.now());
  123. tBCodeDTO.setCreatedById(currentUser.getUserId());
  124. tBCodeDTO.setStatus(TBCodeStatusEnum.NEW);
  125. tBCodeDTO.setExpiredDate(tBCodeCreationDTO.getExpiredDate());
  126. TBCodeDTO result = null;
  127. Boolean hasViolationException = false;
  128. do {
  129. try {
  130. tBCodeDTO.setCode(RandomStringUtil.generateRandomStringFromUUID(8));
  131. result = tBCodeService.save(tBCodeDTO);
  132. } catch (org.springframework.dao.DataIntegrityViolationException ex) {
  133. if (ex.getMessage().contains("ux_tb_code_code")) {
  134. hasViolationException = true;
  135. } else {
  136. throw ex;
  137. }
  138. }
  139. }
  140. while (hasViolationException);
  141. if (result.getId() != null) {
  142. List<TBCodeDetailsDTO> tbCodeDetailsDTOS = new ArrayList<>();
  143. for (int i = 1; i <= tBCodeCreationDTO.getQuantity(); i++) {
  144. TBCodeDetailsDTO codeDetailsDTO = new TBCodeDetailsDTO();
  145. codeDetailsDTO.setCode(String.valueOf(RandomStringUtil.getDigitCodeDetail()));
  146. codeDetailsDTO.setTbCode(tBCodeDTO);
  147. codeDetailsDTO.setNumberScan(0);
  148. codeDetailsDTO.setStatus(TBCodeStatusEnum.NEW);
  149. codeDetailsDTO.setCreatedDate(Instant.now());
  150. tBCodeDTO.setCreatedById(currentUser.getUserId());
  151. tbCodeDetailsDTOS.add(codeDetailsDTO);
  152. }
  153. tbCodeDetailsService.saveAll(tbCodeDetailsDTOS);
  154. }
  155. return ResponseEntity.created(new URI("/api/tb-codes/" + result.getId()))
  156. .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
  157. .body(result);
  158. } catch (Exception exception) {
  159. throw new RuntimeException();
  160. }
  161. }
  162. @GetMapping("/tb-codes/{id}")
  163. @Timed
  164. public ResponseEntity<TBCodeDTO> getTBCodes(@PathVariable Long id) {
  165. log.debug("REST request to get TBCode : {}", id);
  166. Optional<TBCodeDTO> tBCropDTO = tBCodeService.findOne(id);
  167. //@CUONGLT - Filter scope customer's data
  168. // if (!userRoleUtil.currentUserHasPermissionByCropId(id)) {
  169. // throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
  170. // }
  171. return ResponseUtil.wrapOrNotFound(tBCropDTO);
  172. }
  173. /**
  174. * Add or delete crop's person in charges
  175. *
  176. * @param cropPersonInChargeDTO
  177. * @return
  178. */
  179. @PutMapping("/tb-codes/update/{id}/status/{status}")
  180. @Timed
  181. public ResponseEntity<TBCodeDTO> updateTBCode(@PathVariable Long id, @PathVariable String status) {
  182. log.debug("REST request to update tb codes : {}, status {} ", id, status);
  183. if (id == null || StringUtils.isBlank(status)) {
  184. throw new BadRequestAlertException("1039", ENTITY_NAME, "1039");
  185. }
  186. try {
  187. TBCodeStatusEnum.valueOf(status);
  188. } catch (Exception exception) {
  189. throw new BadRequestAlertException("1039", ENTITY_NAME, "1039");
  190. }
  191. UserDTO currentUser = userService.getCurrentUserDTO().get();
  192. TBCodeDTO tbCodeDTO = new TBCodeDTO();
  193. tbCodeDTO.setId(id);
  194. tbCodeDTO.setModifiedDate(Instant.now());
  195. tbCodeDTO.setModifiedById(currentUser.getId());
  196. tbCodeDTO.setStatus(TBCodeStatusEnum.valueOf(status));
  197. Optional<TBCodeDTO> tBCodeUpdated = tBCodeService.updateStatusTBCode(tbCodeDTO);
  198. // if (null != tBCropDTO) {
  199. // sendNotificationPersonInCharge(cropPersonInChargeDTO, listAssignmentPrev);
  200. // }
  201. return ResponseUtil.wrapOrNotFound(tBCodeUpdated);
  202. }
  203. }