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.

TBCropResource.java 32KB

2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. package vn.azteam.tpf.web.rest;
  2. import com.codahale.metrics.annotation.Timed;
  3. import io.github.jhipster.service.filter.LongFilter;
  4. import io.github.jhipster.service.filter.StringFilter;
  5. import io.swagger.v3.oas.annotations.security.SecurityRequirement;
  6. import org.apache.commons.logging.Log;
  7. import org.apache.commons.logging.LogFactory;
  8. import org.casbin.jcasbin.main.Enforcer;
  9. import org.springframework.http.HttpStatus;
  10. import org.springframework.util.StringUtils;
  11. import vn.azteam.tpf.service.*;
  12. import vn.azteam.tpf.service.dto.*;
  13. import vn.azteam.tpf.service.util.PageableUtil;
  14. import vn.azteam.tpf.service.util.UserRoleUtil;
  15. import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;
  16. import vn.azteam.tpf.web.rest.errors.ForbiddenException;
  17. import vn.azteam.tpf.web.rest.util.HeaderUtil;
  18. import vn.azteam.tpf.web.rest.util.PaginationUtil;
  19. import io.github.jhipster.web.util.ResponseUtil;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import org.springframework.data.domain.Page;
  23. import org.springframework.data.domain.Pageable;
  24. import org.springframework.http.HttpHeaders;
  25. import org.springframework.http.ResponseEntity;
  26. import org.springframework.web.bind.annotation.*;
  27. import javax.servlet.http.HttpServletRequest;
  28. import java.net.URI;
  29. import java.net.URISyntaxException;
  30. import java.time.Instant;
  31. import java.util.*;
  32. import java.util.stream.Collectors;
  33. import static vn.azteam.tpf.Constants.Constants.*;
  34. import static vn.azteam.tpf.security.contants.Contants.*;
  35. /**
  36. * REST controller for managing TBCrop.
  37. */
  38. @RestController
  39. @RequestMapping("/api")
  40. @SecurityRequirement(name = "api")
  41. public class TBCropResource {
  42. private final Logger log = LoggerFactory.getLogger(TBCropResource.class);
  43. protected final Log logger = LogFactory.getLog(this.getClass());
  44. private static final String ENTITY_NAME = "tBCrop";
  45. private final TBCropService tBCropService;
  46. private final TBActivityQueryService tBActivityQueryService;
  47. private final TBCropQueryService tBCropQueryService;
  48. private final UserService userService;
  49. private final UserRoleUtil userRoleUtil;
  50. private final Enforcer enforcer;
  51. private final TBEntityService tbEntityService;
  52. private final TBObjectUpdateService tbObjectUpdateService;
  53. private final PageableUtil pageableUtil;
  54. private final TBCustomerService tbCustomerService;
  55. private final TBAddressService tbAddressService;
  56. public TBCropResource(
  57. TBCropService tBCropService,
  58. TBActivityQueryService tBActivityQueryService,
  59. TBCropQueryService tBCropQueryService,
  60. UserRoleUtil userRoleUtil,
  61. Enforcer enforcer,
  62. UserService userService,
  63. TBEntityService tbEntityService,
  64. TBObjectUpdateService tbObjectUpdateService, PageableUtil pageableUtil, TBCustomerService tbCustomerService, TBAddressService tbAddressService) {
  65. this.tBCropService = tBCropService;
  66. this.tBActivityQueryService = tBActivityQueryService;
  67. this.tBCropQueryService = tBCropQueryService;
  68. this.userService = userService;
  69. this.enforcer = enforcer;
  70. this.userRoleUtil = userRoleUtil;
  71. this.tbEntityService = tbEntityService;
  72. this.tbObjectUpdateService = tbObjectUpdateService;
  73. this.pageableUtil = pageableUtil;
  74. this.tbCustomerService = tbCustomerService;
  75. this.tbAddressService = tbAddressService;
  76. }
  77. /**
  78. * POST /tb-crops : Create a new tBCrop.
  79. *
  80. * @param tBCropDTO the tBCropDTO to create
  81. * @return the ResponseEntity with status 201 (Created) and with body the new tBCropDTO, or with status 400 (Bad Request) if the tBCrop has already an ID
  82. * @throws URISyntaxException if the Location URI syntax is incorrect
  83. */
  84. @PostMapping("/tb-crops")
  85. @Timed
  86. public ResponseEntity<TBCropDTO> createTBCrop(@RequestBody TBCropDTO tBCropDTO) throws URISyntaxException {
  87. log.debug("REST request to save TBCrop : {}", tBCropDTO);
  88. //Set created by to current user login
  89. UserDTO currentUser = userService.getCurrentUserDTO().get();
  90. if (tBCropDTO.getId() != null) {
  91. throw new BadRequestAlertException("1047", ENTITY_NAME, "1047");
  92. }
  93. if(currentUser.getCustomerId() == null){
  94. throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
  95. }
  96. if(tBCropDTO.getTbCropTypeId() == null){
  97. throw new BadRequestAlertException("1031", ENTITY_NAME, "1031");
  98. }
  99. if (!userRoleUtil.currentUserHasPermissionByEntityId(tBCropDTO.getNetHouseId())) {
  100. throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
  101. }
  102. TBEntityDTO tbEntityDTO = tbEntityService.findOne(tBCropDTO.getNetHouseId()).get();
  103. if (currentUser.getCustomerId() != null
  104. && !currentUser.getCustomerId().equals(tbEntityDTO.getTbCustomerId())){
  105. throw new BadRequestAlertException("1019", ENTITY_NAME, "1019");
  106. }
  107. //Set created date to current timestamp
  108. tBCropDTO.setCreatedDate(Instant.now());
  109. tBCropDTO.setStartDate(tBCropDTO.getCreatedDate());
  110. tBCropDTO.setCreatedById(currentUser.getUserId());
  111. tBCropDTO.setTbCustomerId(currentUser.getCustomerId());
  112. tBCropDTO.setStatus(ENUM_CROP_STATUS.STATUS_ARE_ACTIVE.name());
  113. TBCropDTO result = null;
  114. Boolean hasViolationException = false;
  115. do {
  116. try {
  117. String qrCode = tBCropQueryService.generateRandomStringFromUUID(8);
  118. tBCropDTO.setQrCode(qrCode);
  119. result = tBCropService.save(tBCropDTO);
  120. } catch (org.springframework.dao.DataIntegrityViolationException ex) {
  121. if (ex.getMessage().contains("ux_tb_crop_qr_code")) {
  122. hasViolationException = true;
  123. } else {
  124. throw ex;
  125. }
  126. }
  127. }
  128. while (hasViolationException);
  129. return ResponseEntity.created(new URI("/api/tb-crops/" + result.getId()))
  130. .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
  131. .body(result);
  132. }
  133. /**
  134. * PUT /tb-crops : Updates an existing tBCrop.
  135. *
  136. * @param tBCropDTO the tBCropDTO to update
  137. * @return the ResponseEntity with status 200 (OK) and with body the updated tBCropDTO,
  138. * or with status 400 (Bad Request) if the tBCropDTO is not valid,
  139. * or with status 500 (Internal Server Error) if the tBCropDTO couldn't be updated
  140. */
  141. @PutMapping("/tb-crops")
  142. @Timed
  143. public ResponseEntity<TBCropDTO> updateTBCrop(@RequestBody TBCropDTO tBCropDTO) {
  144. log.debug("REST request to update TBCrop : {}", tBCropDTO);
  145. if (tBCropDTO.getId() == null) {
  146. throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
  147. }
  148. //Set created date to current timestamp
  149. tBCropDTO.setModifiedDate(Instant.now());
  150. //Set created by to current user login
  151. UserDTO currentUser = userService.getCurrentUserDTO().get();
  152. tBCropDTO.setModifiedById(currentUser.getUserId());
  153. TBCropDTO result = tBCropService.save(tBCropDTO);
  154. return ResponseEntity.ok()
  155. .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBCropDTO.getId().toString()))
  156. .body(result);
  157. }
  158. /**
  159. * GET /tb-crops-dropdown-list : get all the tBCrops for dropdown options.
  160. *
  161. * @param criteria the criterias which the requested entities should match
  162. * @return the ResponseEntity with status 200 (OK) and the list of tBCrops in body
  163. */
  164. @GetMapping("/tb-crops-dropdown-list")
  165. @Timed
  166. public ResponseEntity<List<TBCropDTO>> getAllTBCropsForDropdown(TBCropCriteria criteria) {
  167. log.debug("REST request to get TBCrops by criteria: {}", criteria);
  168. Page<TBCropDTO> page = tBCropQueryService.findByCriteria(criteria, Pageable.unpaged());
  169. //Authorize get list crop by customer of current user
  170. List<TBCropDTO> result = page.getContent().stream()
  171. .filter(item -> userRoleUtil.currentUserHasPermissionByCustomerId(item.getId())
  172. && userRoleUtil.currentUserHasPermissionByCropId(item.getId()))
  173. .sorted(Comparator.comparing(
  174. TBCropDTO::getCreatedDate,
  175. Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
  176. .collect(Collectors.toList());
  177. return ResponseEntity.ok().headers(null).body(result);
  178. }
  179. /**
  180. * GET /tb-crops : get all the tBCrops.
  181. *
  182. * @param pageable the pagination information
  183. * @param criteria the criterias which the requested entities should match
  184. * @return the ResponseEntity with status 200 (OK) and the list of tBCrops in body
  185. */
  186. @GetMapping("/tb-crops")
  187. @Timed
  188. public ResponseEntity<List<TBCropDTO>> getAllTBCrops(TBCropCriteria criteria, Pageable pageable) {
  189. log.debug("REST request to get TBCrops by criteria: {}", criteria);
  190. Page<TBCropDTO> page = tBCropQueryService.findByCriteria(criteria, Pageable.unpaged());
  191. //Authorize get list crop by customer of current user
  192. List<TBCropDTO> result = page.getContent().stream()
  193. .filter(item -> userRoleUtil.currentUserHasPermissionByCustomerId(item.getId())
  194. && userRoleUtil.currentUserHasPermissionByCropId(item.getId()))
  195. .sorted(Comparator.comparing(
  196. TBCropDTO::getCreatedDate,
  197. Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
  198. .collect(Collectors.toList());
  199. //Authorize get list crop by current user
  200. // result = result.stream()
  201. // .filter(item -> userRoleUtil.currentUserHasPermissionByCropId(item.getId()))
  202. // .collect(Collectors.toList());
  203. Page<TBCropDTO> pageResult = pageableUtil.changeTBCropDTOToPageFromList(result, pageable);
  204. for(TBCropDTO itemResult : result) {
  205. logger.error("Start date: " + itemResult.getStartDate());
  206. }
  207. HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(pageResult, "/api/tb-crops");
  208. return ResponseEntity.ok().headers(headers).body(pageResult.getContent());
  209. }
  210. @GetMapping("/ots/tb-crops-by-customer")
  211. @Timed
  212. public ResponseEntity<List<TBCropDTO>> getTBCropsByCustomer(HttpServletRequest request, TBCropCriteria criteria, Pageable pageable) {
  213. log.debug("REST request to get TBCrops by criteria: {}", criteria);
  214. Page<TBCropDTO> page = tBCropQueryService.findByCriteria(criteria, Pageable.unpaged());
  215. Long customer_id = Long.parseLong(request.getHeader(CUSID_API_KEY));
  216. List<TBCropDTO> result = page.getContent().stream()
  217. .filter(item -> item.getTbCustomerId().equals(customer_id))
  218. .sorted(Comparator.comparing(
  219. TBCropDTO::getCreatedDate,
  220. Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
  221. .collect(Collectors.toList());
  222. Page<TBCropDTO> pageResult = pageableUtil.changeTBCropDTOToPageFromList(result, pageable);
  223. for(TBCropDTO itemResult : result) {
  224. logger.error("Start date: " + itemResult.getStartDate());
  225. }
  226. HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(pageResult, "/api/ots/tb-crops-by-customer");
  227. return ResponseEntity.ok().headers(headers).body(pageResult.getContent());
  228. }
  229. /**
  230. * GET /tb-crops/:cropId : get the "id" tBCrop.
  231. *
  232. * @param cropId the id of the tBCropDTO to retrieve
  233. * @return the ResponseEntity with status 200 (OK) and with body the tBCropDTO, or with status 404 (Not Found)
  234. */
  235. @GetMapping("/ots/tb-crops/{cropId}")
  236. @Timed
  237. public ResponseEntity<TBCropDTO> getTBCropOTS(@PathVariable Long cropId, HttpServletRequest request) {
  238. log.debug("REST request to get TBCrop : {}", cropId);
  239. Long customer_id = Long.parseLong(request.getHeader(CUSID_API_KEY));
  240. Optional<TBCropDTO> tBCropDTO = tBCropService.findOne(cropId);
  241. if (!tBCropDTO.get().getTbCustomerId().equals(customer_id)){
  242. throw new ForbiddenException();
  243. }
  244. return ResponseUtil.wrapOrNotFound(tBCropDTO);
  245. }
  246. /**
  247. * GET /tb-crops/count : count all the tBCrops.
  248. *
  249. * @param criteria the criterias which the requested entities should match
  250. * @return the ResponseEntity with status 200 (OK) and the count in body
  251. */
  252. @GetMapping("/tb-crops/count")
  253. @Timed
  254. public ResponseEntity<Long> countTBCrops(TBCropCriteria criteria) {
  255. log.debug("REST request to count TBCrops by criteria: {}", criteria);
  256. return ResponseEntity.ok().body(tBCropQueryService.countByCriteria(criteria));
  257. }
  258. /**
  259. * GET /tb-crops/:id : get the "id" tBCrop.
  260. *
  261. * @param id the id of the tBCropDTO to retrieve
  262. * @return the ResponseEntity with status 200 (OK) and with body the tBCropDTO, or with status 404 (Not Found)
  263. */
  264. @GetMapping("/tb-crops/{id}")
  265. @Timed
  266. public ResponseEntity<TBCropDTO> getTBCrop(@PathVariable Long id) {
  267. log.debug("REST request to get TBCrop : {}", id);
  268. Optional<TBCropDTO> tBCropDTO = tBCropService.findOne(id);
  269. //@CUONGLT - Filter scope customer's data
  270. if (!userRoleUtil.currentUserHasPermissionByCropId(id)) {
  271. throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
  272. }
  273. return ResponseUtil.wrapOrNotFound(tBCropDTO);
  274. }
  275. /**
  276. * GET /tb-crops-detail/:id : get the "id" tBCrop.
  277. *
  278. * @param id the id of the tBCropDTO to retrieve
  279. * @return the ResponseEntity with status 200 (OK) and with body the tBCropDTO, or with status 404 (Not Found)
  280. */
  281. @GetMapping("/tb-crops-detail/{id}")
  282. @Timed
  283. public ResponseEntity<TBCropDetailDTO> getDetailTBCropForWeb(@PathVariable Long id, Pageable pageable) {
  284. log.debug("REST request to get TBCrop detail for web : {}", id);
  285. return getCropDetailDTOResponseEntity(id, pageable, true);
  286. }
  287. /**
  288. * GET /tb-crops-detail-for-app/:id : get the "id" tBCrop.
  289. *
  290. * @param id the id of the tBCropDTO to retrieve
  291. * @return the ResponseEntity with status 200 (OK) and with body the tBCropDTO, or with status 404 (Not Found)
  292. */
  293. @GetMapping("/tb-crops-detail-for-app/{id}")
  294. @Timed
  295. public ResponseEntity<TBCropDetailDTO> getDetailTBCropForApp(@PathVariable Long id, Pageable pageable) {
  296. log.debug("REST request to get TBCrop detail for app : {}", id);
  297. return getCropDetailDTOResponseEntity(id, pageable, false);
  298. }
  299. /**
  300. * GET /ots/tb-crops-detail/:id : get the "id" tBCrop.
  301. *
  302. * @param id the id of the tBCropDTO to retrieve
  303. * @return the ResponseEntity with status 200 (OK) and with body the tBCropDTO, or with status 404 (Not Found)
  304. */
  305. @GetMapping("/ots/tb-crops-detail/{id}")
  306. @Timed
  307. public ResponseEntity<TBCropDetailDTO> getDetailTBCropForOts(@RequestParam(required=false) String type, @PathVariable Long id, HttpServletRequest request, Pageable pageable) {
  308. log.debug("REST request to get TBCrop detail for app : {}", id);
  309. return getCropDetailDTOResponseEntityOts(type, id, request, pageable);
  310. }
  311. /**
  312. * GET /tb-crops/:qrCode : get the "qrCode" tBCrop.
  313. *
  314. * @param qrCode the qrCode of the tBCropDTO to retrieve
  315. * @return the ResponseEntity with status 200 (OK) and with body the tBCropDTO, or with status 404 (Not Found)
  316. */
  317. @GetMapping("/tb-crops-scan-qrCode/{qrCode}")
  318. @Timed
  319. public ResponseEntity<TBCropDetailDTO> getTBCropScanQRCode(@PathVariable String qrCode, Pageable pageable) {
  320. Optional<UserDTO> currentUser = userService.getCurrentUserDTO();
  321. Long currentUserId = currentUser.get().getId();
  322. TBCropCriteria tbCropCriteria = new TBCropCriteria();
  323. StringFilter qrCodeFilter = new StringFilter();
  324. qrCodeFilter.setEquals(qrCode);
  325. tbCropCriteria.setQrCode(qrCodeFilter);
  326. List<TBCropDTO> tBCropDTOs = tBCropQueryService.findByCriteria(tbCropCriteria);
  327. List<TBCropDTO> listTBCropDTOs = new ArrayList<>();
  328. if (tBCropDTOs.size() > 0) {
  329. //@CUONGLT - Filter scope customer's data
  330. listTBCropDTOs = tBCropDTOs.stream()
  331. .filter(item -> userRoleUtil.currentUserHasPermissionByCropId(item.getId()))
  332. .collect(Collectors.toList());
  333. return listTBCropDTOs.size() > 0 ? this.getDetailTBCropForWeb(listTBCropDTOs.get(0).getId(), pageable) : null;
  334. }
  335. return ResponseEntity.ok().headers(null).body(null);
  336. }
  337. /**
  338. * Add or delete crop's person in charges
  339. *
  340. * @param cropPersonInChargeDTO
  341. * @return
  342. */
  343. @PutMapping("/update-person-in-charge")
  344. @Timed
  345. public ResponseEntity<TBCropDTO> updatePersonInCharge(@RequestBody CropPersonInChargeDTO cropPersonInChargeDTO) {
  346. log.debug("REST request to update PIC : {}", cropPersonInChargeDTO);
  347. if (cropPersonInChargeDTO.getCropId() == null) {
  348. throw new BadRequestAlertException("1039", ENTITY_NAME, "1039");
  349. }
  350. List<Long> listAssignmentPrev = userRoleUtil.getListUserIdByCropId(cropPersonInChargeDTO.getCropId());
  351. Optional<TBCropDTO> tBCropDTO = tBCropService.updateCropPersonInCharge(cropPersonInChargeDTO);
  352. if (null != tBCropDTO) {
  353. sendNotificationPersonInCharge(cropPersonInChargeDTO, listAssignmentPrev);
  354. }
  355. return ResponseUtil.wrapOrNotFound(tBCropDTO);
  356. }
  357. /**
  358. * DELETE /tb-crops/:id : delete the "id" tBCrop.
  359. *
  360. * @param id the id of the tBCropDTO to delete
  361. * @return the ResponseEntity with status 200 (OK)
  362. */
  363. @DeleteMapping("/tb-crops/{id}")
  364. @Timed
  365. public ResponseEntity<Void> deleteTBCrop(@PathVariable Long id) {
  366. log.debug("REST request to delete TBCrop : {}", id);
  367. TBCropDTO cropDTO = tBCropService.findOne(id).get();
  368. UserDTO currentUser = userService.getCurrentUserDTO().get();
  369. cropDTO.setDeletedDate(Instant.now());
  370. cropDTO.setDeletedById(currentUser.getId());
  371. tBCropService.save(cropDTO);
  372. return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
  373. }
  374. /**
  375. * SEARCH /_search/tb-crops?query=:query : search for the tBCrop corresponding
  376. * to the query.
  377. *
  378. * @param query the query of the tBCrop search
  379. * @param pageable the pagination information
  380. * @return the result of the search
  381. */
  382. @GetMapping("/_search/tb-crops")
  383. @Timed
  384. public ResponseEntity<List<TBCropDTO>> searchTBCrops(
  385. @RequestParam(required = false) String query,
  386. @RequestParam(required = false) Long areaId,
  387. @RequestParam(required = false) Long netHouseId,
  388. Pageable pageable) {
  389. log.debug("REST request to search for a page of TBCrops for query {}", query);
  390. Page<TBCropDTO> page = tBCropQueryService.searchCrop(query, areaId, netHouseId, Pageable.unpaged());
  391. List<TBCropDTO> result = page.getContent().stream()
  392. .filter(item -> userRoleUtil.currentUserHasPermissionByCustomerId(item.getId())
  393. && userRoleUtil.currentUserHasPermissionByCropId(item.getId()))
  394. .sorted(Comparator.comparing(
  395. TBCropDTO::getCreatedDate,
  396. Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
  397. .collect(Collectors.toList());
  398. Page<TBCropDTO> pageResult = pageableUtil.changeTBCropDTOToPageFromList(result, pageable);
  399. HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(pageResult, "/api/_search/tb-crops");
  400. return ResponseEntity.ok().headers(headers).body(pageResult.getContent());
  401. }
  402. /**
  403. * Get crop detail by id
  404. *
  405. * @param id
  406. * @param pageable
  407. * @param isRequestedFromWeb
  408. * @return
  409. */
  410. private ResponseEntity<TBCropDetailDTO> getCropDetailDTOResponseEntity(
  411. @PathVariable Long id,
  412. Pageable pageable,
  413. Boolean isRequestedFromWeb) {
  414. Optional<TBCropDTO> tBCropDTO = tBCropService.findOne(id);
  415. if (!userRoleUtil.currentUserHasPermissionByCropId(tBCropDTO.get().getId())) {
  416. throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
  417. }
  418. Optional<UserDTO> currentUser = userService.getCurrentUserDTO();
  419. TBCropDetailDTO tbCropDetailDTO = new TBCropDetailDTO();
  420. tbCropDetailDTO.setTbCropDTO(tBCropDTO.get());
  421. // Get list of activity
  422. TBActivityCriteria criteria = new TBActivityCriteria();
  423. LongFilter cropFilter = new LongFilter();
  424. cropFilter.setEquals(id);
  425. criteria.setCropId(cropFilter);
  426. List<TBActivityDTO> allActivities = tBActivityQueryService.findByCriteria(criteria).stream()
  427. .sorted(Comparator.comparing(
  428. TBActivityDTO::getExecuteDate,
  429. Comparator.nullsLast(Comparator.naturalOrder())).reversed())
  430. .collect(Collectors.toList());
  431. //remove env activities automatically
  432. allActivities
  433. .removeIf(activity -> ACTIVE_TYPE_UPDATE_ENV.equals(activity.getActivityTypeName())
  434. && activity.getCreatedById() == null);
  435. // Lo Uom
  436. if(tBCropDTO.get().getTbCropTypeId() == 1) {
  437. // Get sowing Date
  438. TBActivityDTO nurseryActivity = allActivities.stream()
  439. .sorted(Comparator.comparing(
  440. TBActivityDTO::getExecuteDate,
  441. Comparator.nullsLast(Comparator.naturalOrder())))
  442. .filter(activity -> ACTIVE_TYPE_NURSERY.equals(activity.getActivityTypeName()))
  443. .findAny()
  444. .orElse(null);
  445. if (nurseryActivity != null) {
  446. tbCropDetailDTO.setSowingDate(nurseryActivity.getExecuteDate());
  447. List<TBObjectUpdateDTO> tbObjectUpdateDTOs = tbObjectUpdateService.findByTBActivityId(nurseryActivity.getId(), Pageable.unpaged());
  448. if(tbObjectUpdateDTOs!= null && tbObjectUpdateDTOs.size() > 0) {
  449. tbObjectUpdateDTOs.forEach(item -> {
  450. if (item.getTbObjectParameterDTO().getName().equals(THOI_GIAN_NGAM_HAT)) {
  451. item.setIndex(item.getIndex() != null && !item.getIndex().isEmpty() ? item.getIndex() : "0");
  452. tbCropDetailDTO.setSeedIncubationTime(Double.valueOf(item.getIndex()));
  453. }
  454. });
  455. }
  456. }
  457. }
  458. //Lo Trong
  459. if(tBCropDTO.get().getTbCropTypeId() == 2) {
  460. // Get planting Date
  461. TBActivityDTO plantingActivity = allActivities.stream()
  462. .sorted(Comparator.comparing(
  463. TBActivityDTO::getExecuteDate,
  464. Comparator.nullsLast(Comparator.naturalOrder())))
  465. .filter(activity -> ACTIVE_TYPE_PLANTING.equals(activity.getActivityTypeName()))
  466. .findAny()
  467. .orElse(null);
  468. tbCropDetailDTO.setPlantingDate(plantingActivity != null ? plantingActivity.getExecuteDate() : null);
  469. List<Long> listActivities = allActivities.stream().map(TBActivityDTO::getId).collect(Collectors.toList());
  470. List<TBObjectUpdateDTO> tbObjectUpdateDTOs = tbObjectUpdateService.findByInListTBActivityId(listActivities, Pageable.unpaged());
  471. if(tbObjectUpdateDTOs!= null && tbObjectUpdateDTOs.size() > 0) {
  472. tbObjectUpdateDTOs.forEach(item -> {
  473. if (item.getTbObjectParameterDTO().getName().equals(SO_LUONG_CAY_TRONG)) {
  474. item.setIndex(item.getIndex() != null && !item.getIndex().isEmpty() ? item.getIndex() : "0");
  475. tbCropDetailDTO.setNumberPlants(Integer.parseInt(item.getIndex().replaceAll("[^0-9]","")));
  476. tbCropDetailDTO.setNumberCurrentPlants(Integer.parseInt(item.getIndex().replaceAll("[^0-9]","")));
  477. }
  478. if (item.getTbObjectParameterDTO().getName().equals(SO_LUONG_LOAI_BO)) {
  479. item.setIndex(item.getIndex() != null && !item.getIndex().isEmpty() ? item.getIndex() : "0");
  480. Integer currentNumberPlants = tbCropDetailDTO.getNumberPlants() - Integer.parseInt(item.getIndex().replaceAll("[^0-9]",""));
  481. tbCropDetailDTO.setNumberCurrentPlants(currentNumberPlants > 0 ? currentNumberPlants : 0);
  482. }
  483. });
  484. }
  485. }
  486. //Filter assignment croptype by customer
  487. if (currentUser.get().getCustomerId() != null) {
  488. List<Long> ListActivityTypeId = tBCropService.getListActivityTypeIdByByCustomerAndCropType(currentUser.get().getCustomerId(),tBCropDTO.get().getTbCropTypeId());
  489. allActivities = allActivities.stream().filter(item -> ListActivityTypeId.contains(item.getActivityTypeId())).collect(Collectors.toList());
  490. }
  491. if (isRequestedFromWeb) {
  492. ActivityTimelineDTO activityTimeline =
  493. tBCropQueryService.getActivityTimeline(id, allActivities, pageable);
  494. tbCropDetailDTO.setActivityTimeline(activityTimeline);
  495. } else {
  496. allActivities = pageableUtil.changeTBActivityDTOToPageFromList(allActivities,pageable).getContent();
  497. tbCropDetailDTO.setActivities(allActivities);
  498. }
  499. TBActivityDTO endActivity = allActivities.stream()
  500. .sorted(Comparator.comparing(
  501. TBActivityDTO::getExecuteDate,
  502. Comparator.nullsLast(Comparator.naturalOrder())).reversed())
  503. .filter(activity -> ACTIVE_TYPE_END.equals(activity.getActivityTypeName()))
  504. .findAny()
  505. .orElse(null);
  506. if (endActivity != null) {
  507. tbCropDetailDTO.setEndOfFarmingDate(endActivity.getExecuteDate());
  508. }
  509. return ResponseEntity.ok().headers(null).body(tbCropDetailDTO);
  510. }
  511. /**
  512. * Get crop detail by id
  513. *
  514. * @param id
  515. * @param pageable
  516. * @param request
  517. * @return
  518. */
  519. private ResponseEntity<TBCropDetailDTO> getCropDetailDTOResponseEntityOts(
  520. @RequestParam String type,
  521. @PathVariable Long id,
  522. HttpServletRequest request,
  523. Pageable pageable) {
  524. Long customerId = Long.parseLong(request.getHeader(CUSID_API_KEY));
  525. Optional<TBCropDTO> tBCropDTO = tBCropService.findOne(id);
  526. if (!tBCropDTO.isPresent()){
  527. throw new BadRequestAlertException("Customer not found", ENTITY_NAME, "idinvalid");
  528. }
  529. if (!tBCropDTO.get().getTbCustomerId().equals(customerId)){
  530. throw new ForbiddenException();
  531. }
  532. Optional<UserDTO> currentUser = userService.getCurrentUserDTO();
  533. TBCropDetailDTO tbCropDetailDTO = new TBCropDetailDTO();
  534. Optional<TBCustomerDTO> currentCustomerDTO = tbCustomerService.findOne(customerId);
  535. Optional<TBAddressDTO> locationOptional = tbAddressService.findOne(currentCustomerDTO.get().getTbAddressId());
  536. locationOptional.ifPresent(tbCropDetailDTO::setTbAddressDTO);
  537. tbCropDetailDTO.setTbCropDTO(tBCropDTO.get());
  538. // Get list of activity
  539. TBActivityCriteria criteria = new TBActivityCriteria();
  540. LongFilter cropFilter = new LongFilter();
  541. cropFilter.setEquals(id);
  542. criteria.setCropId(cropFilter);
  543. List<TBActivityDTO> allActivities = tBActivityQueryService.findByCriteria(criteria).stream()
  544. .filter(item -> !StringUtils.hasText(type) || item.getActivityTypeName().equals(type))
  545. .sorted(Comparator.comparing(
  546. TBActivityDTO::getExecuteDate,
  547. Comparator.nullsLast(Comparator.naturalOrder())).reversed())
  548. .collect(Collectors.toList());
  549. //remove env activities automatically
  550. allActivities
  551. .removeIf(activity -> ACTIVE_TYPE_UPDATE_ENV.equals(activity.getActivityTypeName())
  552. && activity.getCreatedById() == null);
  553. //Filter assignment croptype by customer
  554. if (currentUser.get().getCustomerId() != null) {
  555. List<Long> ListActivityTypeId = tBCropService.getListActivityTypeIdByByCustomerAndCropType(currentUser.get().getCustomerId(),tBCropDTO.get().getTbCropTypeId());
  556. allActivities = allActivities.stream().filter(item -> ListActivityTypeId.contains(item.getActivityTypeId())).collect(Collectors.toList());
  557. }
  558. allActivities = pageableUtil.changeTBActivityDTOToPageFromList(allActivities,pageable).getContent();
  559. tbCropDetailDTO.setActivities(allActivities);
  560. TBActivityDTO endActivity = allActivities.stream()
  561. .sorted(Comparator.comparing(
  562. TBActivityDTO::getExecuteDate,
  563. Comparator.nullsLast(Comparator.naturalOrder())).reversed())
  564. .filter(activity -> ACTIVE_TYPE_END.equals(activity.getActivityTypeName()))
  565. .findAny()
  566. .orElse(null);
  567. if (endActivity != null) {
  568. tbCropDetailDTO.setEndOfFarmingDate(endActivity.getExecuteDate());
  569. }
  570. // Lo Uom
  571. if(tBCropDTO.get().getTbCropTypeId() == 1) {
  572. // Get sowing Date
  573. TBActivityDTO nurseryActivity = allActivities.stream()
  574. .sorted(Comparator.comparing(
  575. TBActivityDTO::getExecuteDate,
  576. Comparator.nullsLast(Comparator.naturalOrder())))
  577. .filter(activity -> ACTIVE_TYPE_NURSERY.equals(activity.getActivityTypeName()))
  578. .findAny()
  579. .orElse(null);
  580. if (nurseryActivity != null) {
  581. tbCropDetailDTO.setSowingDate(nurseryActivity.getExecuteDate());
  582. List<TBObjectUpdateDTO> tbObjectUpdateDTOs = tbObjectUpdateService.findByTBActivityId(nurseryActivity.getId(), Pageable.unpaged());
  583. if(tbObjectUpdateDTOs!= null && tbObjectUpdateDTOs.size() > 0) {
  584. tbObjectUpdateDTOs.forEach(item -> {
  585. if (item.getTbObjectParameterDTO().getName().equals(THOI_GIAN_NGAM_HAT)) {
  586. item.setIndex(item.getIndex() != null && !item.getIndex().isEmpty() ? item.getIndex() : "0");
  587. tbCropDetailDTO.setSeedIncubationTime(Double.valueOf(item.getIndex()));
  588. }
  589. });
  590. }
  591. }
  592. }
  593. //Lo Trong
  594. if(tBCropDTO.get().getTbCropTypeId() == 2) {
  595. // Get planting Date
  596. TBActivityDTO plantingActivity = allActivities.stream()
  597. .sorted(Comparator.comparing(
  598. TBActivityDTO::getExecuteDate,
  599. Comparator.nullsLast(Comparator.naturalOrder())))
  600. .filter(activity -> ACTIVE_TYPE_PLANTING.equals(activity.getActivityTypeName()))
  601. .findAny()
  602. .orElse(null);
  603. tbCropDetailDTO.setPlantingDate(plantingActivity != null ? plantingActivity.getExecuteDate() : null);
  604. List<Long> listActivities = allActivities.stream().map(TBActivityDTO::getId).collect(Collectors.toList());
  605. List<TBObjectUpdateDTO> tbObjectUpdateDTOs = tbObjectUpdateService.findByInListTBActivityId(listActivities, Pageable.unpaged());
  606. if(tbObjectUpdateDTOs!= null && tbObjectUpdateDTOs.size() > 0) {
  607. tbObjectUpdateDTOs.forEach(item -> {
  608. if (item.getTbObjectParameterDTO().getName().equals(SO_LUONG_CAY_TRONG)) {
  609. item.setIndex(item.getIndex() != null && !item.getIndex().isEmpty() ? item.getIndex() : "0");
  610. tbCropDetailDTO.setNumberPlants(Integer.parseInt(item.getIndex().replaceAll("[^0-9]","")));
  611. tbCropDetailDTO.setNumberCurrentPlants(Integer.parseInt(item.getIndex().replaceAll("[^0-9]","")));
  612. }
  613. if (item.getTbObjectParameterDTO().getName().equals(SO_LUONG_LOAI_BO)) {
  614. item.setIndex(item.getIndex() != null && !item.getIndex().isEmpty() ? item.getIndex() : "0");
  615. Integer currentNumberPlants = tbCropDetailDTO.getNumberPlants() - Integer.parseInt(item.getIndex().replaceAll("[^0-9]",""));
  616. tbCropDetailDTO.setNumberCurrentPlants(currentNumberPlants > 0 ? currentNumberPlants : 0);
  617. }
  618. });
  619. }
  620. }
  621. return ResponseEntity.ok().headers(null).body(tbCropDetailDTO);
  622. }
  623. @PostMapping("/notification/update-person-in-charge")
  624. public ResponseEntity sendNotificationPersonInCharge(@RequestBody CropPersonInChargeDTO cropPersonInChargeDTO, List<Long> listAssignmentPrev) {
  625. tBCropQueryService.sendNotificationPersonInCharge(cropPersonInChargeDTO, listAssignmentPrev);
  626. return new ResponseEntity<>(new PushNotificationResponse(HttpStatus.OK.value(), "Notification has been sent."), HttpStatus.OK);
  627. }
  628. }