Untitled

mail@pastecode.io avatarunknown
java
a month ago
19 kB
1
Indexable
Never
package com.vn.meddental.web.rest;

import com.vn.meddental.repository.SuppliesRepository;
import com.vn.meddental.service.SuppliesService;
import com.vn.meddental.service.dto.SuppliesDTO;
import com.vn.meddental.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.validation.Valid;
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.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link com.vn.meddental.domain.Supplies}.
 */
@RestController
@RequestMapping("/api/supplies")
public class SuppliesResource {

    private final Logger log = LoggerFactory.getLogger(SuppliesResource.class);

    private static final String ENTITY_NAME = "supplies";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final SuppliesService suppliesService;

    private final SuppliesRepository suppliesRepository;

    public SuppliesResource(SuppliesService suppliesService, SuppliesRepository suppliesRepository) {
        this.suppliesService = suppliesService;
        this.suppliesRepository = suppliesRepository;
    }

    /**
     * {@code POST  /supplies} : Create a new supplies.
     *
     * @param suppliesDTO the suppliesDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new suppliesDTO, or with status {@code 400 (Bad Request)} if the supplies has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping
    public ResponseEntity<SuppliesDTO> create(@Valid @RequestBody SuppliesDTO suppliesDTO) throws URISyntaxException {
        log.debug("REST request to save Supplies : {}", suppliesDTO);

        //        if (suppliesDTO.getId() != null) {
        //            throw new BadRequestAlertException("A new supplies cannot already have an ID", ENTITY_NAME, "idexists");
        //        }
        SuppliesDTO result = suppliesService.save(suppliesDTO);
        return ResponseEntity
            .created(new URI("/api/supplies/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /supplies/:id} : Updates an existing supplies.
     *
     * @param id the id of the suppliesDTO to save.
     * @param suppliesDTO the suppliesDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated suppliesDTO,
     * or with status {@code 400 (Bad Request)} if the suppliesDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the suppliesDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/supplies/{id}")
    public ResponseEntity<SuppliesDTO> updateSupplies(
        @PathVariable(value = "id", required = false) final Long id,
        @Valid @RequestBody SuppliesDTO suppliesDTO
    ) throws URISyntaxException {
        log.debug("REST request to update Supplies : {}, {}", id, suppliesDTO);
        //        if (suppliesDTO.getId() == null) {
        //            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        //        }
        //        if (!Objects.equals(id, suppliesDTO.getId())) {
        //            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        //        }
        //
        //        if (!suppliesRepository.existsById(id)) {
        //            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        //        }

        SuppliesDTO result = suppliesService.update(suppliesDTO, id);
        return ResponseEntity.ok(result);
    }

    /**
     * {@code PATCH  /supplies/:id} : Partial updates given fields of an existing supplies, field will ignore if it is null
     *
     * @param id the id of the suppliesDTO to save.
     * @param suppliesDTO the suppliesDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated suppliesDTO,
     * or with status {@code 400 (Bad Request)} if the suppliesDTO is not valid,
     * or with status {@code 404 (Not Found)} if the suppliesDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the suppliesDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
//    @PatchMapping(value = "/supplies/{id}", consumes = { "application/json", "application/merge-patch+json" })
//    public ResponseEntity<SuppliesDTO> partialUpdateSupplies(
//        @PathVariable(value = "id", required = false) final Long id,
//        @Valid @RequestBody SuppliesDTO suppliesDTO
//    ) throws URISyntaxException {
//        log.debug("REST request to partial update Supplies partially : {}, {}", id, suppliesDTO);
//        if (suppliesDTO.getId() == null) {
//            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
//        }
//        if (!Objects.equals(id, suppliesDTO.getId())) {
//            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
//        }
//
//        if (!suppliesRepository.existsById(id)) {
//            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
//        }
//
//        Optional<SuppliesDTO> result = suppliesService.partialUpdate(suppliesDTO);
//
//        return ResponseUtil.wrapOrNotFound(
//            result,
//            HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, suppliesDTO.getId().toString())
//        );
//    }

    /**
     * {@code GET  /supplies} : get all the supplies.
     *
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of supplies in body.
     */
    @GetMapping("/supplies")
    public ResponseEntity<List<SuppliesDTO>> getAllSupplies(@org.springdoc.api.annotations.ParameterObject Pageable pageable) {
        log.debug("REST request to get a page of Supplies");
        Page<SuppliesDTO> page = suppliesService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /supplies/:id} : get the "id" supplies.
     *
     * @param id the id of the suppliesDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the suppliesDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/supplies/{id}")
    public ResponseEntity<SuppliesDTO> getSupplies(@PathVariable Long id) {
        log.debug("REST request to get Supplies : {}", id);
        Optional<SuppliesDTO> suppliesDTO = suppliesService.findOne(id);
        return ResponseUtil.wrapOrNotFound(suppliesDTO);
    }

    /**
     * {@code DELETE  /supplies/:id} : delete the "id" supplies.
     *
     * @param id the id of the suppliesDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/supplies/{id}")
    public ResponseEntity<Void> deleteSupplies(@PathVariable Long id) {
        log.debug("REST request to delete Supplies : {}", id);
        suppliesService.delete(id);
        return ResponseEntity.noContent().build();
    }

    // deleteList -> PUT
}










package com.vn.meddental.service.impl;

import com.vn.meddental.constant.Constants;
import com.vn.meddental.domain.Supplies;
import com.vn.meddental.domain.User;
import com.vn.meddental.repository.SuppliesRepository;
import com.vn.meddental.service.BaseService;
import com.vn.meddental.service.SuppliesService;
import com.vn.meddental.service.dto.SuppliesDTO;
import com.vn.meddental.service.mapper.SuppliesMapper;
import com.vn.meddental.web.rest.errors.BadRequestAlertException;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service Implementation for managing {@link Supplies}.
 */
@Service
@Transactional
public class SuppliesServiceImpl implements SuppliesService {

    private final Logger log = LoggerFactory.getLogger(SuppliesServiceImpl.class);
    private static final String ENTITY_NAME = "supplies";
    private final SuppliesRepository suppliesRepository;

    private final SuppliesMapper suppliesMapper;

    public SuppliesServiceImpl(SuppliesRepository suppliesRepository, SuppliesMapper suppliesMapper) {
        this.suppliesRepository = suppliesRepository;
        this.suppliesMapper = suppliesMapper;
    }

    @Override
    public SuppliesDTO save(SuppliesDTO suppliesDTO) {
        log.debug("Request to save Supplies : {}", suppliesDTO);
        //        String loggedUser = SecurityContextHolder.getContext().getAuthentication().getName();

//        if (suppliesDTO.getId() != null) {
//            throw new BadRequestAlertException("A new supplies cannot already have an ID", ENTITY_NAME, "idexists");
//        }

        // check group: exists or not

        if (suppliesRepository.existsByCode(suppliesDTO.getCode())) throw new BadRequestAlertException(
            "Supply Code already exists",
            ENTITY_NAME,
            "codeexists"
        );

        // modify strim() method
        User currentUser = BaseService.getCurrentUser();
        Supplies supplies = suppliesMapper.toEntity(suppliesDTO);

        supplies.setName(suppliesDTO.getName().trim());
        supplies.setCode(suppliesDTO.getCode().trim().toUpperCase());
        supplies.setStorageUnit(suppliesDTO.getStorageUnit());
        // check xem có cùng danh mục category k
        supplies.setNormUnit(suppliesDTO.getNormUnit());
        supplies.setSizeSupply(suppliesDTO.getSizeSupply());
        supplies.setIdSuppliesGroup(suppliesDTO.getIdSuppliesGroup());

        //
        supplies.setStatus(1);
        supplies.setCreatedBy(currentUser.getName());
        supplies.setCreatedDate(Instant.now());
        supplies.setLastModifiedBy(currentUser.getName());
        supplies.setLastModifiedDate(Instant.now());

        suppliesRepository.save(supplies);
        return suppliesMapper.toDto(supplies);
    }

    // Not update supplies_group
    @Override
    public SuppliesDTO update(SuppliesDTO suppliesDTO, Long id) {
        log.debug("Request to update Supplies : {}", suppliesDTO);
        //        if (suppliesDTO.getId() == null) {
        //            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        //        }

        //        if (!Objects.equals(id, suppliesDTO.getId())) {
        //            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        //        }

        if (!suppliesRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        //
        User currentUser = BaseService.getCurrentUser();
        Supplies supplies = suppliesMapper.toEntity(suppliesDTO);
        supplies.setId(id);
        supplies.setName(suppliesDTO.getName().trim());
        // không update code
//        supplies.setCode(suppliesDTO.getCode().trim().toUpperCase());

        supplies.setStorageUnit(suppliesDTO.getStorageUnit());
        supplies.setNormUnit(suppliesDTO.getNormUnit());

        // check xem có cho đổi status không
        supplies.setSizeSupply(suppliesDTO.getSizeSupply());
        supplies.setStatus(suppliesDTO.getStatus());
        supplies.setLastModifiedBy(currentUser.getName());
        supplies.setLastModifiedDate(Instant.now());

        supplies = suppliesRepository.save(supplies);
        return suppliesMapper.toDto(supplies);
    }


    @Override
    @Transactional(readOnly = true)
    public Page<SuppliesDTO> findAll(Pageable pageable) {
        log.debug("Request to get all Supplies");
        return suppliesRepository.findAll(pageable).map(suppliesMapper::toDto);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<SuppliesDTO> findOne(Long id) {
        log.debug("Request to get Supplies : {}", id);
        return suppliesRepository.findById(id).map(suppliesMapper::toDto);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        log.debug("Request to delete Supplies : {}", id);
        //        suppliesRepository.deleteById(id);
        SuppliesDTO suppliesDTO = findOne(id)
            .orElseThrow(() -> new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound"));
        suppliesDTO.setStatus(Constants.STATUS.DELETE);
        update(suppliesDTO, suppliesDTO.getId());
    }

    // search (pageable, searchDTO) -> suppliesGroupId, search keyword
                    //                  id              name or code
    //
    // deleteList

}





package com.vn.meddental.service.dto;

import java.io.Serializable;
import java.time.Instant;
import java.util.Objects;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * A DTO for the {@link com.vn.meddental.domain.Supplies} entity.
 */
@SuppressWarnings("common-java:DuplicatedBlocks")
public class SuppliesDTO implements Serializable {

    private Long id;

    @NotBlank(message = "filed.not.null.empty")
    @Size(min = 1, max = 50, message = "filed.min.length.and.max5.50")
    private String name;

    @Size(min = 1, max = 50, message = "filed.min.length.and.max5.50")
    @NotBlank(message = "filed.not.null.empty")
    @Pattern(regexp = "^[a-zA-Z0-9]*$", message = "supply.code.format.invalid-Code")
    private String code;

    // validate *
    private Long storageUnit;

    private Long normUnit;

    private String sizeSupply;

    private Long idSuppliesGroup;

    private Integer status;

    private String createdBy;

    private Instant createdDate;

    private String lastModifiedBy;

    private Instant lastModifiedDate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Long getStorageUnit() {
        return storageUnit;
    }

    public void setStorageUnit(Long storageUnit) {
        this.storageUnit = storageUnit;
    }

    public Long getNormUnit() {
        return normUnit;
    }

    public void setNormUnit(Long normUnit) {
        this.normUnit = normUnit;
    }

    public String getSizeSupply() {
        return sizeSupply;
    }

    public void setSizeSupply(String sizeSupply) {
        this.sizeSupply = sizeSupply;
    }

    public Long getIdSuppliesGroup() {
        return idSuppliesGroup;
    }

    public void setIdSuppliesGroup(Long idSuppliesGroup) {
        this.idSuppliesGroup = idSuppliesGroup;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Instant getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Instant createdDate) {
        this.createdDate = createdDate;
    }

    public String getLastModifiedBy() {
        return lastModifiedBy;
    }

    public void setLastModifiedBy(String lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }

    public Instant getLastModifiedDate() {
        return lastModifiedDate;
    }

    public void setLastModifiedDate(Instant lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof SuppliesDTO)) {
            return false;
        }

        SuppliesDTO suppliesDTO = (SuppliesDTO) o;
        if (this.id == null) {
            return false;
        }
        return Objects.equals(this.id, suppliesDTO.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.id);
    }

    // prettier-ignore
    @Override
    public String toString() {
        return "SuppliesDTO{" +
            "id=" + getId() +
            ", name='" + getName() + "'" +
            ", code='" + getCode() + "'" +
            ", storageUnit=" + getStorageUnit() +
            ", normUnit=" + getNormUnit() +
            ", sizeSupply='" + getSizeSupply() + "'" +
            ", idSuppliesGroup=" + getIdSuppliesGroup() +
            ", status=" + getStatus() +
            ", createdBy='" + getCreatedBy() + "'" +
            ", createdDate='" + getCreatedDate() + "'" +
            ", lastModifiedBy='" + getLastModifiedBy() + "'" +
            ", lastModifiedDate='" + getLastModifiedDate() + "'" +
            "}";
    }
}