Commit 21ccb03a authored by Ishankha K.C's avatar Ishankha K.C

Merge branch 'feature/chamode_dev' into 'master'

add device contact info

See merge request !8
parents cf4fb4d5 ce6986dd
......@@ -6,5 +6,6 @@ public class TableNames {
public final static String BABY_TABLE = "babies";
public final static String DOCUMENT_TABLE = "documents";
public final static String ACTIVITY_LOG_TABLE = "activity_logs";
public final static String CONTACT_INFO_TABLE = "contact_info";
}
......@@ -3,4 +3,7 @@ package com.kaluwa.enterprises.babycarebackendservice.constants;
public class UserRoles {
public static final String ADMIN = "ADMIN";
public static final String USER = "USER";
public static final String CRADLE = "CRADLE";
public static final String NANNY = "NANNY";
}
package com.kaluwa.enterprises.babycarebackendservice.dao;
import com.kaluwa.enterprises.babycarebackendservice.model.ContactInfo;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface ContactInfoDao extends JpaRepository<ContactInfo, Long> {
boolean existsByUserUserIdAndType(Long userId, String type);
Optional<ContactInfo> findByUserUserIdAndType(Long userId, String type);
boolean existsByUserUserIdAndTypeAndContactInfoIdNot(Long userId, String type, Long contactInfoId);
void deleteByUserUserIdAndType(Long userId, String type);
}
\ No newline at end of file
package com.kaluwa.enterprises.babycarebackendservice.dto;
import com.kaluwa.enterprises.babycarebackendservice.model.ContactInfo;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;
import java.io.Serializable;
/**
* DTO for {@link ContactInfo}
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class ContactInfoDto implements Serializable {
private Long contactInfoId;
@NotEmpty(message = "Contact name is required")
private String contactName;
@NotEmpty(message = "Contact number is required")
@Size(min = 10, max = 10, message = "Contact number should be 10 digits")
private String contactNo;
@NotEmpty(message = "Contact type is required")
private String type;
private UserDto user;
@NotNull(message = "User id is required")
private Long userId;
}
\ No newline at end of file
package com.kaluwa.enterprises.babycarebackendservice.error;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaluwa.enterprises.babycarebackendservice.global.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
......@@ -15,19 +16,22 @@ import java.util.Map;
public class ErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(BadRequestAlertException.class)
public ResponseEntity<Object> handleBadRequestAlertException(BadRequestAlertException ex, WebRequest request) {
public ResponseEntity<ErrorResponse> handleBadRequestAlertException(BadRequestAlertException ex, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now().toString());
body.put("message", ex.getMessage());
body.put("error", ex.getErrorKey());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setTimestamp(LocalDateTime.now().toString());
errorResponse.setMessage(ex.getMessage());
errorResponse.setError(ex.getErrorKey());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(AuthorizationAlertException.class)
public ResponseEntity<Object> handleAuthorizationAlertException(AuthorizationAlertException ae, WebRequest request) {
public ResponseEntity<ErrorResponse> handleAuthorizationAlertException(AuthorizationAlertException ae, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now().toString());
body.put("error", ae.getMessage());
return new ResponseEntity<>(body, HttpStatus.UNAUTHORIZED);
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setTimestamp(LocalDateTime.now().toString());
errorResponse.setMessage(ae.getMessage());
errorResponse.setError(ae.getErrorKey());
return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
}
}
......@@ -9,6 +9,12 @@ import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RestControllerAdvice
@Slf4j
public class CustomExceptionHandler {
......@@ -16,15 +22,22 @@ public class CustomExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationExceptions(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
FieldError error = result.getFieldError();
String message = error.getField()+ " : " +error.getDefaultMessage();
log.debug("Validation error: {}", message);
List<FieldError> fieldErrors = result.getFieldErrors();
// Collect all field errors into a single message
String message = fieldErrors.stream()
.map(fieldError -> fieldError.getField() + " : " + fieldError.getDefaultMessage())
.collect(Collectors.joining(", "));
log.debug("Validation errors: {}", message);
// Prepare the error response
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setHttpCode(400);
errorResponse.setErrorCode("VALIDATION FAILED!");
errorResponse.setDescription(message);
errorResponse.setTimestamp(LocalDateTime.now().toString());
errorResponse.setMessage("VALIDATION FAILED!");
errorResponse.setError(message);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
}
......@@ -4,11 +4,13 @@ import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ErrorResponse {
private int httpCode;
private String errorCode;
private String description;
private String timestamp;
private String message;
private String error;
}
package com.kaluwa.enterprises.babycarebackendservice.mappers;
import com.kaluwa.enterprises.babycarebackendservice.dto.ContactInfoDto;
import com.kaluwa.enterprises.babycarebackendservice.model.ContactInfo;
import org.mapstruct.*;
import java.util.List;
@Mapper(componentModel = "spring")
public interface ContactInfoMapper {
@Mappings({
@Mapping(target = "user.userId", source = "userId")
})
ContactInfo toEntity(ContactInfoDto contactInfoDto);
@Mappings({
@Mapping(source = "user.userId", target = "userId")
})
ContactInfoDto toDto(ContactInfo contactInfo);
@Mappings({
@Mapping(source = "user.userId", target = "userId")
})
List<ContactInfoDto> listToDto(List<ContactInfo> contactInfos);
}
\ No newline at end of file
package com.kaluwa.enterprises.babycarebackendservice.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import static com.kaluwa.enterprises.babycarebackendservice.constants.TableNames.CONTACT_INFO_TABLE;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = CONTACT_INFO_TABLE)
public class ContactInfo {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long contactInfoId;
private String contactName;
private String contactNo;
private String type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", referencedColumnName = "userId", nullable = false)
private User user;
}
package com.kaluwa.enterprises.babycarebackendservice.rest;
import com.kaluwa.enterprises.babycarebackendservice.dto.ContactInfoDto;
import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto;
import com.kaluwa.enterprises.babycarebackendservice.service.ContactInfoService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/contact-info")
@Slf4j
public class ContactInfoController {
private final ContactInfoService contactInfoService;
public ContactInfoController(ContactInfoService contactInfoService) {
this.contactInfoService = contactInfoService;
}
@PostMapping
public ResponseEntity<ContactInfoDto> createContactInfo(@RequestBody ContactInfoDto contactInfo) {
log.info("Inside ContactInfoController.createContactInfo");
return contactInfoService.createContactInfo(contactInfo);
}
@GetMapping("/user-id/{userId}/{type}")
public ResponseEntity<ContactInfoDto> getContactInfoByUserId(
@PathVariable Long userId,
@PathVariable String type
) {
log.info("Inside ContactInfoController.getContactInfoByUserId");
return contactInfoService.getContactInfoByUserId(userId, type);
}
@PutMapping("/{contactInfoId}")
public ResponseEntity<ContactInfoDto> updateContactInfo(@PathVariable Long contactInfoId, @RequestBody ContactInfoDto contactInfo) {
log.info("Inside ContactInfoController.updateContactInfo");
return contactInfoService.updateContactInfo(contactInfoId, contactInfo);
}
@DeleteMapping("/user-id/{userId}/{type}")
public ResponseEntity<ResponseDto> deleteContactInfoByUserId(
@PathVariable Long userId,
@PathVariable String type
) {
log.info("Inside ContactInfoController.deleteContactInfoByUserId");
return contactInfoService.deleteContactInfoByUserId(userId, type);
}
}
package com.kaluwa.enterprises.babycarebackendservice.service;
import com.kaluwa.enterprises.babycarebackendservice.dto.ContactInfoDto;
import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
public interface ContactInfoService {
ResponseEntity<ContactInfoDto> createContactInfo(@Valid ContactInfoDto contactInfo);
ResponseEntity<ContactInfoDto> getContactInfoByUserId(Long userId, String type);
ResponseEntity<ContactInfoDto> updateContactInfo(Long contactInfoId, @Valid ContactInfoDto contactInfo);
ResponseEntity<ResponseDto> deleteContactInfoByUserId(Long userId, String type);
}
package com.kaluwa.enterprises.babycarebackendservice.service.impl;
import com.kaluwa.enterprises.babycarebackendservice.dao.ContactInfoDao;
import com.kaluwa.enterprises.babycarebackendservice.dto.ContactInfoDto;
import com.kaluwa.enterprises.babycarebackendservice.dto.ResponseDto;
import com.kaluwa.enterprises.babycarebackendservice.error.BadRequestAlertException;
import com.kaluwa.enterprises.babycarebackendservice.mappers.ContactInfoMapper;
import com.kaluwa.enterprises.babycarebackendservice.model.ContactInfo;
import com.kaluwa.enterprises.babycarebackendservice.service.ContactInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.util.Optional;
import static com.kaluwa.enterprises.babycarebackendservice.constants.UserRoles.CRADLE;
import static com.kaluwa.enterprises.babycarebackendservice.constants.UserRoles.NANNY;
@Service
@Slf4j
public class ContactInfoServiceImpl implements ContactInfoService {
private final ContactInfoDao contactInfoDao;
private final ContactInfoMapper contactInfoMapper;
public ContactInfoServiceImpl(ContactInfoDao contactInfoDao, ContactInfoMapper contactInfoMapper) {
this.contactInfoDao = contactInfoDao;
this.contactInfoMapper = contactInfoMapper;
}
@Override
public ResponseEntity<ContactInfoDto> createContactInfo(ContactInfoDto contactInfo) {
log.info("Inside ContactInfoServiceImpl.createContactInfo");
try {
// validate
if (contactInfo.getType().isEmpty()) {
throw new BadRequestAlertException("Contact type is required", "ContactInfo", "ContactTypeRequired");
}
if (contactInfo.getType().equalsIgnoreCase(CRADLE)) {
contactInfo.setType(CRADLE);
} else if (contactInfo.getType().equalsIgnoreCase(NANNY)) {
contactInfo.setType(NANNY);
} else {
throw new BadRequestAlertException("Invalid contact type", "ContactInfo", "InvalidContactType");
}
if (contactInfo.getContactName().isEmpty()) {
throw new BadRequestAlertException("Contact name is required", "ContactInfo", "ContactNameRequired");
}
if (contactInfo.getContactNo().isEmpty()) {
throw new BadRequestAlertException("Contact number is required", "ContactInfo", "ContactNoRequired");
}
if (contactInfo.getContactNo().length() != 10) {
throw new BadRequestAlertException("Contact number should be 10 digits", "ContactInfo", "InvalidContactNo");
}
if (contactInfo.getUserId() == null) {
throw new BadRequestAlertException("User id is required", "ContactInfo", "UserIdRequired");
}
if (contactInfoDao.existsByUserUserIdAndType(contactInfo.getUserId(), contactInfo.getType())) {
throw new BadRequestAlertException("Contact info already exists for you", "ContactInfo", "ContactInfoExists");
}
// create
return ResponseEntity.ok(contactInfoMapper.toDto(contactInfoDao.save(contactInfoMapper.toEntity(contactInfo))));
} catch (Exception e) {
log.error("Error occurred while creating contact info", e);
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "Error", "Error");
}
}
@Override
public ResponseEntity<ContactInfoDto> getContactInfoByUserId(Long userId, String type) {
log.info("Inside ContactInfoServiceImpl.getContactInfoByUserId");
try {
// validate
if (!contactInfoDao.existsByUserUserIdAndType(userId, type)) {
throw new BadRequestAlertException("Contact info does not exist for you, Please add first", "ContactInfo", "ContactInfoDoesNotExist");
}
return ResponseEntity.ok(contactInfoMapper.toDto(contactInfoDao.findByUserUserIdAndType(userId, type).get()));
} catch (Exception e) {
log.error("Error occurred while getting contact info", e);
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "Error", "Error");
}
}
@Override
public ResponseEntity<ContactInfoDto> updateContactInfo(Long contactInfoId, ContactInfoDto contactInfo) {
log.info("Inside ContactInfoServiceImpl.updateContactInfo");
try {
// validate
if (contactInfo.getContactInfoId() == null) {
throw new BadRequestAlertException("Contact info id is required", "ContactInfo", "ContactInfoIdRequired");
}
if (contactInfo.getType().isEmpty()) {
throw new BadRequestAlertException("Contact type is required", "ContactInfo", "ContactTypeRequired");
}
if (!contactInfoId.equals(contactInfo.getContactInfoId())) {
throw new BadRequestAlertException("Invalid contact info id", "ContactInfo", "InvalidContactInfoId");
}
if (contactInfo.getContactName().isEmpty()) {
throw new BadRequestAlertException("Contact name is required", "ContactInfo", "ContactNameRequired");
}
if (contactInfo.getContactNo().isEmpty()) {
throw new BadRequestAlertException("Contact number is required", "ContactInfo", "ContactNoRequired");
}
if (contactInfo.getContactNo().length() != 10) {
throw new BadRequestAlertException("Contact number should be 10 digits", "ContactInfo", "InvalidContactNo");
}
if (contactInfo.getUserId() == null) {
throw new BadRequestAlertException("User id is required", "ContactInfo", "UserIdRequired");
}
Optional<ContactInfo> contactInfoDto = contactInfoDao.findById(contactInfoId);
if (!contactInfoDto.isPresent()) {
throw new BadRequestAlertException("Contact info does not exist", "ContactInfo", "ContactInfoDoesNotExist");
}
if (contactInfo.getType().equalsIgnoreCase(CRADLE)) {
contactInfo.setType(CRADLE);
} else if (contactInfo.getType().equalsIgnoreCase(NANNY)) {
contactInfo.setType(NANNY);
} else {
throw new BadRequestAlertException("Invalid contact type", "ContactInfo", "InvalidContactType");
}
if (contactInfoDao.existsByUserUserIdAndTypeAndContactInfoIdNot(contactInfo.getUserId(), contactInfo.getType(), contactInfoId)) {
throw new BadRequestAlertException("Contact info already exists for you", "ContactInfo", "ContactInfoExists");
}
// update
return ResponseEntity.ok(contactInfoMapper.toDto(contactInfoDao.save(contactInfoMapper.toEntity(contactInfo))));
} catch (Exception e) {
log.error("Error occurred while updating contact info", e);
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "Error", "Error");
}
}
@Override
public ResponseEntity<ResponseDto> deleteContactInfoByUserId(Long userId, String type) {
log.info("Inside ContactInfoServiceImpl.deleteContactInfoByUserId");
try {
// validate
if (!contactInfoDao.existsByUserUserIdAndType(userId, type)) {
throw new BadRequestAlertException("Contact info does not exist for you", "ContactInfo", "ContactInfoDoesNotExist");
}
// delete
contactInfoDao.deleteByUserUserIdAndType(userId, type);
return ResponseEntity.ok(new ResponseDto(Long.parseLong("200"), "Contact info deleted successfully"));
} catch (Exception e) {
log.error("Error occurred while deleting contact info", e);
e.printStackTrace();
throw new BadRequestAlertException(e.getMessage(), "Error", "Error");
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment