Created crud opration for company api's

This commit is contained in:
rajesh
2024-09-28 21:40:14 +05:30
parent ee80959329
commit d45fce59ec
26 changed files with 884 additions and 29 deletions

View File

@@ -136,7 +136,6 @@ public class GepafinConstant {
public static final String APPLICATION_IS_INCOMPLETE_MSG = "application.is.incomplete"; public static final String APPLICATION_IS_INCOMPLETE_MSG = "application.is.incomplete";
public static final String AUTHORIZATION = "Authorization"; public static final String AUTHORIZATION = "Authorization";
public static final String CHECK_VATNUMBER_V2_NEW_URL = "https://imprese.openapi.it/advance"; public static final String CHECK_VATNUMBER_V2_NEW_URL = "https://imprese.openapi.it/advance";
public static final String VATNUMBER_V2 = "https://imprese.openapi.it/advance";
public static final String VALIDATION_FIELD_CUSTOM="validation.field.custom"; public static final String VALIDATION_FIELD_CUSTOM="validation.field.custom";
public static final String VALIDATION_CODICE_FISCALE = "validation.codice.fiscale"; public static final String VALIDATION_CODICE_FISCALE = "validation.codice.fiscale";
public static final String VALIDATION_CAP = "validation.cap"; public static final String VALIDATION_CAP = "validation.cap";
@@ -167,4 +166,15 @@ public class GepafinConstant {
public static final String ROLE_ID_MANDATORY = "role.id.mandatory"; public static final String ROLE_ID_MANDATORY = "role.id.mandatory";
public static final String VALIDATE_PASSWORD = "validate.password"; public static final String VALIDATE_PASSWORD = "validate.password";
public static final String COMPANY_CREATED_SUCCESS_MSG = "company.created.success";
public static final String COMPANY_UPDATED_SUCCESS_MSG = "company.updated.success";
public static final String COMPANY_DELETE_SUCCESS_MSG = "company.delete.success";
public static final String COMPANY_GET_SUCCESS_MSG = "company.get.success";
public static final String COMPANY_NOT_FOUND_MSG = "company.not.found";
public static final String CHECK_VATNUMBER_SUCCESS_MSG = "check.vatnumber.success";
public static final String INVALID_VATNUMBER = "invalid.vatnumber";
public static final String VATNUMBER_MANDATORY = "vatnumber.mandatory";
public static final String VATNUMBER_ALREADY_EXISTS = "vatnumber.already.exists";
public static final String INVALID_EMAIL = "invalid.email";
} }

View File

@@ -0,0 +1,156 @@
package net.gepafin.tendermanagement.dao;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.repositories.CompanyRepository;
import net.gepafin.tendermanagement.repositories.UserWithCompanyRepository;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@Component
public class CompanyDao {
@Autowired
private CompanyRepository companyRepository;
@Autowired
private UserService userService;
@Autowired
private UserWithCompanyRepository userWithCompanyRepository;
public CompanyResponse createCompany(UserEntity userEntity, CompanyRequest companyRequest) {
validateCompany(companyRequest);
CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(companyRequest);
companyRepository.save(companyEntity);
createUserWithCompanyRelation(userEntity, companyEntity);
return convertCompanyEntityToCompanyResponse(companyEntity);
}
private void validateCompany(CompanyRequest companyRequest) {
if (Boolean.FALSE.equals(StringUtils.isEmpty(companyRequest.getEmail()))
&& Boolean.FALSE.equals(Utils.isValidEmail(companyRequest.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_EMAIL));
}
if(StringUtils.isEmpty(companyRequest.getVatNumber())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_MANDATORY));
}
if(companyRepository.existsByVatNumber(companyRequest.getVatNumber())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_ALREADY_EXISTS));
}
}
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity) {
UserWithCompanyEntity userWithCompanyEntity = new UserWithCompanyEntity();
if (userEntity.getBeneficiary() != null) {
userWithCompanyEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
userWithCompanyEntity.setCompanyId(companyEntity.getId());
userWithCompanyEntity.setUserId(userEntity.getId());
return userWithCompanyRepository.save(userWithCompanyEntity);
}
private CompanyEntity convertCompanyRequestToCompanyEntity(CompanyRequest request) {
CompanyEntity entity = new CompanyEntity();
entity.setCompanyName(request.getCompanyName());
entity.setVatNumber(request.getVatNumber());
entity.setCodiceFiscale(request.getCodiceFiscale());
entity.setAddress(request.getAddress());
entity.setPhoneNumber(request.getPhoneNumber());
entity.setCity(request.getCity());
entity.setProvince(request.getProvince());
entity.setCap(request.getCap());
entity.setCountry(request.getCountry());
entity.setPec(request.getPec());
entity.setEmail(request.getEmail());
entity.setNumberOfEmployees(request.getNumberOfEmployees());
entity.setAnnualRevenue(request.getAnnualRevenue());
return entity;
}
private CompanyResponse convertCompanyEntityToCompanyResponse(CompanyEntity entity) {
CompanyResponse response = new CompanyResponse();
response.setId(entity.getId());
response.setCompanyName(entity.getCompanyName());
response.setVatNumber(entity.getVatNumber());
response.setCodiceFiscale(entity.getCodiceFiscale());
response.setAddress(entity.getAddress());
response.setPhoneNumber(entity.getPhoneNumber());
response.setCity(entity.getCity());
response.setProvince(entity.getProvince());
response.setCap(entity.getCap());
response.setCountry(entity.getCountry());
response.setPec(entity.getPec());
response.setEmail(entity.getEmail());
response.setNumberOfEmployees(entity.getNumberOfEmployees());
response.setAnnualRevenue(entity.getAnnualRevenue());
response.setCreatedDate(entity.getCreatedDate());
response.setUpdatedDate(entity.getUpdatedDate());
return response;
}
public CompanyResponse updateCompany(UserEntity userEntity, Long companyId, CompanyRequest companyRequest) {
CompanyEntity companyEntity = validateCompany(companyId);
Utils.setIfUpdated(companyEntity::getCompanyName, companyEntity::setCompanyName,
companyRequest.getCompanyName());
Utils.setIfUpdated(companyEntity::getVatNumber, companyEntity::setVatNumber, companyRequest.getVatNumber());
Utils.setIfUpdated(companyEntity::getCodiceFiscale, companyEntity::setCodiceFiscale,
companyRequest.getCodiceFiscale());
Utils.setIfUpdated(companyEntity::getAddress, companyEntity::setAddress, companyRequest.getAddress());
Utils.setIfUpdated(companyEntity::getPhoneNumber, companyEntity::setPhoneNumber,
companyRequest.getPhoneNumber());
Utils.setIfUpdated(companyEntity::getCity, companyEntity::setCity, companyRequest.getCity());
Utils.setIfUpdated(companyEntity::getProvince, companyEntity::setProvince, companyRequest.getProvince());
Utils.setIfUpdated(companyEntity::getCap, companyEntity::setCap, companyRequest.getCap());
Utils.setIfUpdated(companyEntity::getCountry, companyEntity::setCountry, companyRequest.getCountry());
Utils.setIfUpdated(companyEntity::getPec, companyEntity::setPec, companyRequest.getPec());
Utils.setIfUpdated(companyEntity::getEmail, companyEntity::setEmail, companyRequest.getEmail());
Utils.setIfUpdated(companyEntity::getNumberOfEmployees, companyEntity::setNumberOfEmployees,
companyRequest.getNumberOfEmployees());
Utils.setIfUpdated(companyEntity::getAnnualRevenue, companyEntity::setAnnualRevenue,
companyRequest.getAnnualRevenue());
companyRepository.save(companyEntity);
return convertCompanyEntityToCompanyResponse(companyEntity);
}
public CompanyEntity validateCompany(Long companyId) {
return companyRepository.findById(companyId).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.COMPANY_NOT_FOUND_MSG)));
}
public CompanyResponse getCompany(UserEntity userEntity, Long companyId) {
return convertCompanyEntityToCompanyResponse(validateCompany(companyId));
}
public void deleteCompany(UserEntity userEntity, Long companyId) {
CompanyEntity companyEntity = validateCompany(companyId);
companyRepository.delete(companyEntity);
userWithCompanyRepository.deleteByCompanyId(companyId);
}
public List<CompanyResponse> getCompanyByUserId(Long userId) {
UserEntity userEntity = userService.validateUser(userId);
List<Long> companyIds = userWithCompanyRepository.findCompanyIdByUserId(userEntity.getId());
List<CompanyEntity> list = companyRepository.findByIdIn(companyIds);
return list.stream().map(this::convertCompanyEntityToCompanyResponse).toList();
}
}

View File

@@ -31,8 +31,6 @@ import org.springframework.stereotype.Repository;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated; import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
import java.util.regex.Pattern;
@Repository @Repository
public class UserDao { public class UserDao {
@@ -84,7 +82,7 @@ public class UserDao {
} }
private void validateUserRequest(String tempToken, UserReq userReq) { private void validateUserRequest(String tempToken, UserReq userReq) {
if (Boolean.FALSE.equals(isValidEmail(userReq.getEmail()))) { if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR, throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL)); Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
} }
@@ -303,16 +301,6 @@ public class UserDao {
log.info("User successfully logged out."); log.info("User successfully logged out.");
} }
public static Boolean isValidEmail(String email) {
String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
if (email == null || email.isEmpty()) {
return false;
}
Pattern pattern = Pattern.compile(EMAIL_REGEX);
return pattern.matcher(email).matches();
}
public UserResponseBean updateUserStatus(Long userId, UserStatusEnum statusReq) { public UserResponseBean updateUserStatus(Long userId, UserStatusEnum statusReq) {
log.info("Updating status for user with ID: {}", userId); log.info("Updating status for user with ID: {}", userId);
UserEntity userEntity=validateUser(userId); UserEntity userEntity=validateUser(userId);

View File

@@ -1,8 +1,13 @@
package net.gepafin.tendermanagement.dao; package net.gepafin.tendermanagement.dao;
import feign.FeignException; import feign.FeignException;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant; import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.service.feignClient.VatCheckService; import net.gepafin.tendermanagement.service.feignClient.VatCheckService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -67,8 +72,17 @@ public class VatCheckDao {
} }
} catch (FeignException ex) { } catch (FeignException ex) {
log.error("Exception occurred while checking vat number: {0}", ex); log.error("Exception occurred while checking vat number: {0}", ex);
throw ex; Utils.callException(ex.status(), ex);
} }
return responseBody; return responseBody;
} }
public Map<String, Object> checkVatNumber(String vatNumber) {
try {
return checkVatNumberApi(vatNumber);
} catch (Exception e) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
}
}
} }

View File

@@ -9,7 +9,7 @@ import jakarta.validation.constraints.Email;
import lombok.Data; import lombok.Data;
@Entity @Entity
@Table(name = "beneficiary") @Table(name = "BENEFICIARY")
@Data @Data
public class BeneficiaryEntity extends BaseEntity { public class BeneficiaryEntity extends BaseEntity {

View File

@@ -0,0 +1,53 @@
package net.gepafin.tendermanagement.entities;
import java.math.BigDecimal;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.Data;
@Entity
@Table(name = "COMPANY")
@Data
public class CompanyEntity extends BaseEntity{
@Column(name = "COMPANY_NAME")
private String companyName;
@Column(name = "VAT_NUMBER")
private String vatNumber;
@Column(name = "CODICE_FISCALE")
private String codiceFiscale;
@Column(name = "ADDRESS")
private String address;
@Column(name = "PHONE_NUMBER")
private String phoneNumber;
@Column(name = "CITY")
private String city;
@Column(name = "PROVINCE")
private String province;
@Column(name = "CAP")
private String cap;
@Column(name = "COUNTRY")
private String country;
@Column(name = "PEC")
private String pec;
@Column(name = "EMAIL")
private String email;
@Column(name = "NUMBER_OF_EMPLOYEES")
private String numberOfEmployees;
@Column(name = "ANNUAL_REVENUE")
private BigDecimal annualRevenue;
}

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.Data;
@Entity
@Table(name = "USER_WITH_COMPANY")
@Data
public class UserWithCompanyEntity extends BaseEntity{
@Column(name = "USER_ID")
Long userId;
@Column(name = "BENEFICIARY_ID")
Long beneficiaryId;
@Column(name = "COMPANY_ID")
Long companyId;
}

View File

@@ -0,0 +1,24 @@
package net.gepafin.tendermanagement.model.request;
import java.math.BigDecimal;
import lombok.Data;
@Data
public class CompanyRequest {
private String companyName;
private String vatNumber;
private String codiceFiscale;
private String address;
private String phoneNumber;
private String city;
private String province;
private String cap;
private String country;
private String pec;
private String email;
private String numberOfEmployees;
private BigDecimal annualRevenue;
}

View File

@@ -0,0 +1,25 @@
package net.gepafin.tendermanagement.model.response;
import java.math.BigDecimal;
import lombok.Data;
import net.gepafin.tendermanagement.model.BaseBean;
@Data
public class CompanyResponse extends BaseBean{
private String companyName;
private String vatNumber;
private String codiceFiscale;
private String address;
private String phoneNumber;
private String city;
private String province;
private String cap;
private String country;
private String pec;
private String email;
private String numberOfEmployees;
private BigDecimal annualRevenue;
}

View File

@@ -0,0 +1,17 @@
package net.gepafin.tendermanagement.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.gepafin.tendermanagement.entities.CompanyEntity;
@Repository
public interface CompanyRepository extends JpaRepository<CompanyEntity, Long> {
List<CompanyEntity> findByIdIn(List<Long> companyIds);
Boolean existsByVatNumber(String vatNumber);
}

View File

@@ -0,0 +1,19 @@
package net.gepafin.tendermanagement.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
public interface UserWithCompanyRepository extends JpaRepository<UserWithCompanyEntity, Long> {
void deleteByCompanyId(Long companyId);
@Query("SELECT uwc.companyId FROM UserWithCompanyEntity uwc WHERE uwc.userId = :userId")
List<Long> findCompanyIdByUserId(@Param("userId") Long userId);
}

View File

@@ -0,0 +1,24 @@
package net.gepafin.tendermanagement.service;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
public interface CompanyService {
CompanyResponse createCompany(HttpServletRequest request, CompanyRequest companyRequest);
CompanyResponse updateCompany(HttpServletRequest request, Long companyId, CompanyRequest companyRequest);
CompanyResponse getCompany(HttpServletRequest request, Long companyId);
void deleteCompany(HttpServletRequest request, Long companyId);
List<CompanyResponse> getCompanyByUserId(HttpServletRequest request, Long userId);
Map<String, Object> checkVatNumber(HttpServletRequest request, String vatNumber);
}

View File

@@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.RequestHeader;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
@FeignClient(value = "vat-check-service", url = GepafinConstant.VATNUMBER_V2) @FeignClient(value = "vat-check-service", url = GepafinConstant.CHECK_VATNUMBER_V2_NEW_URL)
public interface VatCheckService { public interface VatCheckService {

View File

@@ -0,0 +1,72 @@
package net.gepafin.tendermanagement.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.CompanyDao;
import net.gepafin.tendermanagement.dao.VatCheckDao;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.util.Validator;
@Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private Validator validator;
@Autowired
private CompanyDao companyDao;
@Autowired
private VatCheckDao vatCheckDao;
@Override
@Transactional(rollbackFor = Exception.class)
public CompanyResponse createCompany(HttpServletRequest request, CompanyRequest companyRequest) {
UserEntity userEntity =validator.validateUser(request);
return companyDao.createCompany(userEntity, companyRequest);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CompanyResponse updateCompany(HttpServletRequest request, Long companyId, CompanyRequest companyRequest) {
UserEntity userEntity =validator.validateUser(request);
return companyDao.updateCompany(userEntity, companyId, companyRequest);
}
@Override
@Transactional(readOnly = true)
public CompanyResponse getCompany(HttpServletRequest request, Long companyId) {
UserEntity userEntity =validator.validateUser(request);
return companyDao.getCompany(userEntity, companyId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCompany(HttpServletRequest request, Long companyId) {
UserEntity userEntity =validator.validateUser(request);
companyDao.deleteCompany(userEntity, companyId);
}
@Override
@Transactional(readOnly = true)
public List<CompanyResponse> getCompanyByUserId(HttpServletRequest request, Long userId) {
UserEntity userEntity = validator.validateUser(request);
return companyDao.getCompanyByUserId(userId);
}
@Override
@Transactional(readOnly = true)
public Map<String, Object> checkVatNumber(HttpServletRequest request, String vatNumber) {
return vatCheckDao.checkVatNumber(vatNumber);
}
}

View File

@@ -35,6 +35,7 @@ public class UserServiceImpl implements UserService {
@Autowired @Autowired
private SamlSuccessHandler samlSuccessHandler; private SamlSuccessHandler samlSuccessHandler;
@Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) { public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
if (tempToken == null) { if (tempToken == null) {

View File

@@ -1,17 +1,5 @@
package net.gepafin.tendermanagement.util; package net.gepafin.tendermanagement.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.micrometer.common.util.StringUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -21,8 +9,29 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import feign.FeignException;
import io.micrometer.common.util.StringUtils;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientForbiddenException;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientUnauthorizedException;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientValidationException;
public class Utils { public class Utils {
@@ -190,4 +199,32 @@ public class Utils {
return null; return null;
} }
} }
public static void callException(Integer staus, FeignException ex) {
switch (staus) {
case 400:
throw new FeignClientValidationException(HttpStatus.valueOf(staus), ex.getMessage());
case 401:
throw new FeignClientUnauthorizedException(HttpStatus.valueOf(staus), ex.getMessage());
case 403:
throw new FeignClientForbiddenException(HttpStatus.valueOf(staus), ex.getMessage());
case 404:
throw new FeignClientNotFoundException(HttpStatus.valueOf(staus), ex.getMessage());
default:
log.error("Exception occured :- {0}", ex);
throw ex;
}
}
public static Boolean isValidEmail(String email) {
String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
if (email == null || email.isEmpty()) {
return false;
}
Pattern pattern = Pattern.compile(EMAIL_REGEX);
return pattern.matcher(email).matches();
}
} }

View File

@@ -0,0 +1,97 @@
package net.gepafin.tendermanagement.web.rest.api;
import java.util.List;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
public interface CompanyApi {
@Operation(summary = "Api to create company", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@PostMapping(value = "", produces = { "application/json" })
ResponseEntity<Response<CompanyResponse>> createCompany(HttpServletRequest request,
@Parameter(description = "Company request object", required = true) @RequestBody CompanyRequest companyRequest);
@Operation(summary = "Api to update company", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@PutMapping(value = "/{companyId}", produces = { "application/json" })
ResponseEntity<Response<CompanyResponse>> updateCompany(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId,
@Parameter(description = "Company request object", required = true) @RequestBody CompanyRequest companyRequest);
@Operation(summary = "Api to delete company", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@DeleteMapping(value = "/{companyId}", produces = { "application/json" })
ResponseEntity<Response<Void>> deleteCompany(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId);
@Operation(summary = "Api to get company", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/{companyId}", produces = { "application/json" })
ResponseEntity<Response<CompanyResponse>> getCompany(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId);
@Operation(summary = "Api to get company by user Id", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/user/{userId}", produces = { "application/json" })
ResponseEntity<Response<List<CompanyResponse>>> getCompanyByUserId(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("userId") Long userId);
@Operation(summary = "Api to check vatNumber", responses = { @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/vatNumber", produces = { "application/json" })
ResponseEntity<Response<Map<String,Object>>> checkVatNumber(HttpServletRequest request,
@Parameter(description = "The vatNumber of company", required = true) @RequestParam("vatNumber") String vatNumber);
}

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.web.rest.api.errors;
import org.springframework.http.HttpStatus;
import feign.FeignException;
public class FeignClientForbiddenException extends FeignException{
private static final long serialVersionUID = 1L;
private final HttpStatus status;
public FeignClientForbiddenException(HttpStatus status,String message) {
super(403,message);
this.status = status;
}
public HttpStatus getStatus() {
return status;
}
}

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.web.rest.api.errors;
import org.springframework.http.HttpStatus;
import feign.FeignException;
public class FeignClientNotFoundException extends FeignException{
private static final long serialVersionUID = 1L;
private final HttpStatus status;
public FeignClientNotFoundException(HttpStatus status,String message) {
super(404,message);
this.status = status;
}
public HttpStatus getStatus() {
return status;
}
}

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.web.rest.api.errors;
import org.springframework.http.HttpStatus;
import feign.FeignException;
public class FeignClientUnauthorizedException extends FeignException{
private static final long serialVersionUID = 1L;
private final HttpStatus status;
public FeignClientUnauthorizedException(HttpStatus status,String message) {
super(401,message);
this.status = status;
}
public HttpStatus getStatus() {
return status;
}
}

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.web.rest.api.errors;
import org.springframework.http.HttpStatus;
import feign.FeignException;
public class FeignClientValidationException extends FeignException{
private static final long serialVersionUID = 1L;
private final HttpStatus status;
public FeignClientValidationException(HttpStatus status,String message) {
super(400,message);
this.status = status;
}
public HttpStatus getStatus() {
return status;
}
}

View File

@@ -2,9 +2,11 @@ package net.gepafin.tendermanagement.web.rest.api.errors;
import net.gepafin.tendermanagement.config.Translator; import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.model.util.Response; import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.util.Utils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -14,6 +16,9 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
import feign.FeignException;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authorization.AuthorizationDeniedException; import org.springframework.security.authorization.AuthorizationDeniedException;
@@ -122,4 +127,54 @@ public class GlobalExceptionHandler {
} }
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(FeignClientValidationException.class)
@ResponseBody
public Map<String, Object> handleFeignClientBadRequestException(final Throwable ex) {
log.error(ex.getMessage());
log.error(ex.getLocalizedMessage(), ex);
String exceptionString = ex.getMessage().substring(ex.getMessage().indexOf("]: [") + 4, ex.getMessage().length() - 1);
return Utils.convertIntoJson(exceptionString);
}
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ExceptionHandler(FeignClientForbiddenException.class)
@ResponseBody
public Map<String, Object> handleFeignClientForbiddenException(final Throwable ex) {
log.error(ex.getMessage());
log.error(ex.getLocalizedMessage(), ex);
String exceptionString = ex.getMessage().substring(ex.getMessage().indexOf("]: [") + 4, ex.getMessage().length() - 1);
return Utils.convertIntoJson(exceptionString);
}
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(FeignClientUnauthorizedException.class)
@ResponseBody
public Map<String, Object> handleFeignClientUnauthorizedException(final Throwable ex) {
log.error(ex.getMessage());
log.error(ex.getLocalizedMessage(), ex);
String exceptionString = ex.getMessage().substring(ex.getMessage().indexOf("]: [") + 4, ex.getMessage().length() - 1);
return Utils.convertIntoJson(exceptionString);
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ExceptionHandler(FeignClientNotFoundException.class)
@ResponseBody
public Map<String, Object> handleFeignClientNotFoundException(final Throwable ex) {
log.error(ex.getMessage());
log.error(ex.getLocalizedMessage(), ex);
String exceptionString = ex.getMessage().substring(ex.getMessage().indexOf("]: [") + 4, ex.getMessage().length() - 1);
return Utils.convertIntoJson(exceptionString);
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(FeignException.class)
@ResponseBody
public Map<String, Object> handleFeignException(final Throwable ex) {
log.error(ex.getMessage());
log.error(ex.getLocalizedMessage(), ex);
String exceptionString = ex.getMessage().substring(ex.getMessage().indexOf("]: [") + 4, ex.getMessage().length() - 1);
return Utils.convertIntoJson(exceptionString);
}
} }

View File

@@ -0,0 +1,89 @@
package net.gepafin.tendermanagement.web.rest.api.impl;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.web.rest.api.CompanyApi;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@RestController
@RequestMapping("${openapi.gepafin.base-path:/v1/company}")
public class CompanyApiController implements CompanyApi{
private final Logger log = LoggerFactory.getLogger(CompanyApiController.class);
@Autowired
private CompanyService companyService;
@Override
public ResponseEntity<Response<CompanyResponse>> createCompany(HttpServletRequest request,
CompanyRequest companyRequest) {
log.info("Create company with - Request Body: {}", companyRequest);
CompanyResponse data = companyService.createCompany(request, companyRequest);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.COMPANY_CREATED_SUCCESS_MSG)));
}
@Override
public ResponseEntity<Response<CompanyResponse>> updateCompany(HttpServletRequest request, Long companyId,
CompanyRequest companyRequest) {
log.info("Update company with - Request Body: {}", companyRequest);
CompanyResponse data = companyService.updateCompany(request, companyId, companyRequest);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.COMPANY_UPDATED_SUCCESS_MSG)));
}
@Override
public ResponseEntity<Response<CompanyResponse>> getCompany(HttpServletRequest request, Long companyId) {
log.info("Get company with id: {}", companyId);
CompanyResponse data = companyService.getCompany(request, companyId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.COMPANY_GET_SUCCESS_MSG)));
}
@Override
public ResponseEntity<Response<Void>> deleteCompany(HttpServletRequest request, Long companyId) {
log.info("Delete company with id: {}", companyId);
companyService.deleteCompany(request, companyId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.COMPANY_DELETE_SUCCESS_MSG)));
}
@Override
public ResponseEntity<Response<List<CompanyResponse>>> getCompanyByUserId(HttpServletRequest request, Long userId) {
log.info("Get company with userId: {}", userId);
List<CompanyResponse> data = companyService.getCompanyByUserId(request, userId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.COMPANY_GET_SUCCESS_MSG)));
}
@Override
public ResponseEntity<Response<Map<String,Object>>> checkVatNumber(HttpServletRequest request, String vatNumber) {
log.info("check VatNumber with: {}", vatNumber);
Map<String,Object> data = companyService.checkVatNumber(request, vatNumber);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.CHECK_VATNUMBER_SUCCESS_MSG)));
}
}

View File

@@ -767,7 +767,51 @@
<constraints nullable="true" foreignKeyName="fk_beneficiary_gepafin_user" references="beneficiary(id)"/> <constraints nullable="true" foreignKeyName="fk_beneficiary_gepafin_user" references="beneficiary(id)"/>
</column> </column>
</addColumn> </addColumn>
</changeSet>
<changeSet id="27-09-2024_2" author="Rajesh Khore">
<createTable tableName="COMPANY">
<column name="id" type="INTEGER" autoIncrement="true">
<constraints nullable="false" primaryKey="true"
primaryKeyName="company_pkey" />
</column>
<column name="COMPANY_NAME" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="VAT_NUMBER" type="VARCHAR(255)">
<constraints nullable="true" unique="true"/>
</column>
<column name="CODICE_FISCALE" type="VARCHAR(255)"/>
<column name="ADDRESS" type="VARCHAR(255)"/>
<column name="PHONE_NUMBER" type="VARCHAR(255)"/>
<column name="CITY" type="VARCHAR(255)"/>
<column name="PROVINCE" type="VARCHAR(255)"/>
<column name="CAP" type="VARCHAR(255)"/>
<column name="COUNTRY" type="VARCHAR(255)"/>
<column name="PEC" type="VARCHAR(255)"/>
<column name="EMAIL" type="VARCHAR(255)"/>
<column name="NUMBER_OF_EMPLOYEES" type="VARCHAR(255)"/>
<column name="ANNUAL_REVENUE" type="NUMERIC"/>
<column name="created_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
<column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
</createTable>
</changeSet> </changeSet>
<changeSet id="27-09-2024_3" author="Rajesh Khore">
<createTable tableName="USER_WITH_COMPANY">
<column name="id" type="INTEGER" autoIncrement="true">
<constraints nullable="false" primaryKey="true"
primaryKeyName="user_with_company_pkey" />
</column>
<column name="USER_ID" type="INTEGER"/>
<column name="BENEFICIARY_ID" type="INTEGER"/>
<column name="COMPANY_ID" type="INTEGER"/>
<column name="created_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
<column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
</createTable>
</changeSet>
</databaseChangeLog> </databaseChangeLog>

View File

@@ -194,3 +194,13 @@ codice.fiscale.exists=This codice fiscale is already associated with another use
total.steps.not.zero=Total steps cannot be zero. total.steps.not.zero=Total steps cannot be zero.
completed.steps.not.valid=Completed steps should be between 0 and total steps. completed.steps.not.valid=Completed steps should be between 0 and total steps.
field.id.not.found=Field ID {0} does not exist in the form structure. field.id.not.found=Field ID {0} does not exist in the form structure.
company.created.success=Company created successfully.
company.updated.success=Company updated successfully.
company.delete.success=Company deleted successfully.
company.get.success=Company retrieved successfully.
company.not.found=Company not found.
check.vatnumber.success=VAT number checked successfully.
invalid.vatnumber=Invalid VAT number.
vatnumber.mandatory=VatNumber is mandatory.
vatnumber.already.exists=VatNumber already exists.
invalid.email=Invalid email.

View File

@@ -187,3 +187,13 @@ codice.fiscale.exists=Questo codice fiscale <20> gi<67> associato ad un altro uten
total.steps.not.zero=Il totale dei passaggi non pu� essere zero. total.steps.not.zero=Il totale dei passaggi non pu� essere zero.
completed.steps.not.valid=I passaggi completati devono essere compresi tra 0 e il totale dei passaggi. completed.steps.not.valid=I passaggi completati devono essere compresi tra 0 e il totale dei passaggi.
field.id.not.found=L'ID campo {0} non esiste nella struttura del modulo. field.id.not.found=L'ID campo {0} non esiste nella struttura del modulo.
company.created.success=Azienda creata con successo.
company.updated.success=Azienda aggiornata con successo.
company.delete.success=Azienda eliminata con successo.
company.get.success=Azienda recuperata con successo.
company.not.found=Azienda non trovata.
check.vatnumber.success=Numero di partita IVA verificato con successo.
invalid.vatnumber=Numero di partita IVA non valido.
vatnumber.mandatory=Il numero di partita IVA è obbligatorio.
vatnumber.already.exists=Il numero di partita IVA esiste già.
invalid.email=Email non valida.