Merge pull request #32 from Kitzanos/develop

Sync master with develop branch(01/10/2024)
This commit is contained in:
rbonazzo-KZ
2024-10-01 16:45:45 +02:00
committed by GitHub
61 changed files with 1558 additions and 223 deletions

View File

@@ -66,7 +66,7 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
logger.info("SAML login successful for user: " + principal.getName());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
UserEntity userEntity = userRepository.findByCodiceFiscale(cf).orElse(null);
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscale(cf).orElse(null);
if (userEntity == null) {
redirectUrl += "/registration?temp_token=" + token;
} else {

View File

@@ -136,7 +136,6 @@ public class GepafinConstant {
public static final String APPLICATION_IS_INCOMPLETE_MSG = "application.is.incomplete";
public static final String AUTHORIZATION = "Authorization";
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_CODICE_FISCALE = "validation.codice.fiscale";
public static final String VALIDATION_CAP = "validation.cap";
@@ -167,4 +166,17 @@ public class GepafinConstant {
public static final String ROLE_ID_MANDATORY = "role.id.mandatory";
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";
public static final String UNAUTHORIZED = "UNAUTHORIZED";
public static final String COMPANY_ID_MANDATORY = "company.id.mandatory";
public static final String USER_ALREADY_CONNECTED_TO_COMPANY = "user.already.connected.to.company";
}

View File

@@ -17,15 +17,18 @@ import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
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;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import jakarta.persistence.criteria.Predicate;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
@@ -66,13 +69,16 @@ public class ApplicationDao {
@Autowired
private FlowDataRepository flowDataRepository;
@Autowired
private Validator validator;
public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId,Long applicationId) {
public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId, Long applicationId) {
FormEntity formEntity = formService.validateForm(formId);
CallEntity call = callService.validatePublishedCall(formEntity.getCall().getId());
callService.validatePublishedCall(formEntity.getCall().getId());
validateFormFields(applicationRequestBean,formEntity);
ApplicationEntity applicationEntity = validateApplication(applicationId);
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))){
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_SUBMITTED));
}
formService.validateFormField(applicationRequestBean.getFormFields(),applicationEntity,formEntity);
@@ -94,9 +100,10 @@ public class ApplicationDao {
return applicationFormEntity;
}
public ApplicationEntity createApplicationEntity(UserEntity user, CallEntity call) {
public ApplicationEntity createApplicationEntity(UserEntity user, CallEntity call, CompanyEntity companyEntity) {
ApplicationEntity entity = new ApplicationEntity();
entity.setUser(user);
entity.setUserId(user.getId());
entity.setCompany(companyEntity);
entity.setCall(call);
entity.setIsDeleted(false);
entity.setStatus(ApplicationStatusTypeEnum.DRAFT.getValue());
@@ -109,7 +116,6 @@ public class ApplicationDao {
ApplicationEntity applicationEntity = validateApplication(id);
ApplicationFormEntity applicationFormEntity = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(),formId);
List<ApplicationFormFieldResponseBean> applicationFormFieldResponseBeans=new ArrayList<>();
ApplicationFormFieldResponseBean applicationFormFieldResponseBeans1=null;
List<ApplicationFormFieldEntity> applicationFormFieldEntities = applicationFormFieldRepository.findByApplicationFormId(applicationFormEntity.getId());
applicationFormFieldResponseBeans=createApplicationFormFieldResponse(applicationFormFieldEntities, applicationFormEntity, applicationFormFieldResponseBeans);
ApplicationResponseBean applicationResponseBean= convertApplicationEntityToApplicationResponseBean(applicationEntity);
@@ -170,42 +176,72 @@ public class ApplicationDao {
log.info("Application deleted with ID: {}", id);
}
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId) {
boolean isBeneficiary = isBeneficiary(userEntity);
// public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, CompanyEntity companyEntity) {
// boolean isBeneficiary = validator.checkIsBeneficiary();
//
// log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
// List<ApplicationResponse> applicationResponses = new ArrayList<>();
//
// if (callId != null) {
// // Fetch based on callId and user if role is BENEFICIARY, otherwise fetch all for the call
// log.info("Fetching applications for callId: {}", callId);
// CallEntity call = callService.validateCall(callId);
//
// // Use a single method to handle both conditions for consistency
// List<ApplicationEntity> applicationEntities = isBeneficiary
// ? applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(), call.getId())
// .map(List::of) // Convert Optional<ApplicationEntity> to a List of one element
// .orElse(List.of()) // If not present, return an empty list
// : applicationRepository.findByCallIdAndIsDeletedFalse(call.getId());
//
// applicationResponses = applicationEntities.stream()
// .map(this::getApplicationResponse)
// .collect(Collectors.toList());
//
// } else {
// // Fetch all applications for the user if BENEFICIARY, or fetch all applications in general
// List<ApplicationEntity> applicationEntities = isBeneficiary
// ? applicationRepository.findByUserIdAndIsDeletedFalse(companyEntity.getId())
// : applicationRepository.findByIsDeletedFalse();
//
// applicationResponses = applicationEntities.stream()
// .map(this::getApplicationResponse)
// .collect(Collectors.toList());
// }
//
// return applicationResponses;
// }
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId) {
log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
List<ApplicationResponse> applicationResponses = new ArrayList<>();
Specification<ApplicationEntity> spec = search(userEntity.getId(), callId, companyId);
List<ApplicationEntity> applicationEntities = applicationRepository.findAll(spec);
return applicationEntities.stream()
.map(this::getApplicationResponse)
.collect(Collectors.toList());
}
private Specification<ApplicationEntity> search(Long userId, Long callId, Long companyId) {
return (root, query, builder) -> {
Boolean isBeneficiary = validator.checkIsBeneficiary();
Predicate predicate = builder.isFalse(root.get("isDeleted"));
if (isBeneficiary) {
predicate = builder.and(predicate, builder.equal(root.get("userId"), userId));
}
if (callId != null) {
// Fetch based on callId and user if role is BENEFICIARY, otherwise fetch all for the call
log.info("Fetching applications for callId: {}", callId);
CallEntity call = callService.validateCall(callId);
// Use a single method to handle both conditions for consistency
List<ApplicationEntity> applicationEntities = isBeneficiary
? applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(), call.getId())
.map(List::of) // Convert Optional<ApplicationEntity> to a List of one element
.orElse(List.of()) // If not present, return an empty list
: applicationRepository.findByCallIdAndIsDeletedFalse(call.getId());
applicationResponses = applicationEntities.stream()
.map(this::getApplicationResponse)
.collect(Collectors.toList());
} else {
// Fetch all applications for the user if BENEFICIARY, or fetch all applications in general
List<ApplicationEntity> applicationEntities = isBeneficiary
? applicationRepository.findByUserIdAndIsDeletedFalse(userEntity.getId())
: applicationRepository.findByIsDeletedFalse();
applicationResponses = applicationEntities.stream()
.map(this::getApplicationResponse)
.collect(Collectors.toList());
predicate = builder.and(predicate, builder.equal(root.get("call").get("id"), callId));
}
return applicationResponses;
if (companyId != null) {
predicate = builder.and(predicate, builder.equal(root.get("company").get("id"), companyId));
}
return predicate;
};
}
private ApplicationResponse getApplicationResponse(ApplicationEntity applicationEntity) {
ApplicationResponse responseBean = new ApplicationResponse();
@@ -222,11 +258,15 @@ public class ApplicationDao {
responseBean.setSubmissionDate(applicationEntity.getSubmissionDate());
responseBean.setStatus(applicationEntity.getStatus());
responseBean.setComments(applicationEntity.getComments());
responseBean.setCompanyId(applicationEntity.getCompany().getId());
responseBean.setCompanyName(applicationEntity.getCompany().getCompanyName());
return responseBean;
}
public ApplicationEntity validateApplication(Long id) {
ApplicationEntity applicationEntity= applicationRepository.findById(id).orElseThrow(() ->new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
ApplicationEntity applicationEntity = applicationRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
return applicationEntity;
}
@@ -348,20 +388,19 @@ public class ApplicationDao {
return applicationEntity;
}
public ApplicationGetResponseBean getApplicationByFormId( Long applicationId,Long formId, UserEntity userEntity) {
public ApplicationGetResponseBean getApplicationByFormId( Long applicationId, Long formId, UserEntity userEntity) {
List<FormApplicationResponse> formApplicationResponses = new ArrayList<>();
List<FormEntity> formEntities = new ArrayList<>();
boolean isBeneficiary = isBeneficiary(userEntity);
ApplicationEntity applicationEntity = isBeneficiary
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId,userEntity.getId())
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId())
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)))
: applicationRepository.findById(applicationId)
.stream().findFirst()
.orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
if (formId != null) {
FormEntity formEntity = formService.validateForm(formId);
Optional<ApplicationEntity> application = applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(),
Optional<ApplicationEntity> application = applicationRepository.findByIdAndUserIdAndCallIdAndIsDeletedFalse(applicationId, userEntity.getId(),
formEntity.getCall().getId());
applicationEntity=application.get();
formEntities.add(formEntity);
@@ -421,6 +460,8 @@ public class ApplicationDao {
applicationGetResponseBean.setSubmissionDate(applicationEntity.getSubmissionDate());
applicationGetResponseBean.setCallId(applicationEntity.getCall().getId());
applicationGetResponseBean.setCallTitle(applicationEntity.getCall().getName());
applicationGetResponseBean.setCompanyId(applicationEntity.getCompany().getId());
applicationGetResponseBean.setCompanyName(applicationEntity.getCompany().getCompanyName());
return applicationGetResponseBean;
}
@@ -433,36 +474,29 @@ public class ApplicationDao {
return formApplicationResponse;
}
public ApplicationResponse createApplicationByCallId(ApplicationRequest applicationRequest,Long callId,UserEntity userEntity){
CallEntity call=callService.validateCall(callId);
public ApplicationResponse createApplicationByCallId(CompanyEntity companyEntity,
ApplicationRequest applicationRequest, Long callId, UserEntity userEntity) {
CallEntity call = callService.validateCall(callId);
call = callService.validatePublishedCall(call.getId());
checkIfApplicationExists(call,userEntity);
ApplicationEntity applicationEntity=createApplicationEntity(userEntity,call);
checkIfApplicationExists(call, companyEntity);
ApplicationEntity applicationEntity = createApplicationEntity(userEntity, call, companyEntity);
applicationEntity.setComments(applicationRequest.getComments());
applicationEntity=saveApplicationEntity(applicationEntity);
ApplicationResponse applicationResponse=getApplicationResponse(applicationEntity);
applicationEntity = saveApplicationEntity(applicationEntity);
ApplicationResponse applicationResponse = getApplicationResponse(applicationEntity);
return applicationResponse;
}
public void checkIfApplicationExists(CallEntity call,UserEntity userEntity){
Optional<ApplicationEntity> applicationEntity=applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(),call.getId());
public void checkIfApplicationExists(CallEntity call, CompanyEntity companyEntity){
Optional<ApplicationEntity> applicationEntity=applicationRepository.findByCompanyIdAndCallIdAndIsDeletedFalse(companyEntity.getId(),call.getId());
if(applicationEntity.isPresent()){
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
}
}
public ApplicationEntity getApplicationByCallAndUser(CallEntity call, UserEntity userEntity) {
return applicationRepository.findByUserIdAndCallIdAndIsDeletedFalse(userEntity.getId(), call.getId())
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG)));
}
public void updateApplicationStatus(Long applicationId, ApplicationStatusTypeEnum status) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
if (status.equals(ApplicationStatusTypeEnum.SUBMIT)) {
CallEntity callEntity = applicationEntity.getCall();
// CallEntity callEntity = applicationEntity.getCall();
// Long initialFormId = callEntity.getInitialForm();
// Long finalFormId = callEntity.getFinalForm();
//// if (initialFormId == null || finalFormId == null) {
@@ -500,7 +534,7 @@ public class ApplicationDao {
return (int) Math.round(progress);
}
public void validateFormFields(ApplicationRequestBean request, FormEntity formEntity) {
List<String> errors=new ArrayList<>();
List<ContentResponseBean> contentResponseBeans=Utils.convertJsonStringToList(formEntity.getContent(),ContentResponseBean.class);
List<ApplicationFormFieldRequestBean> requestFields = request.getFormFields();

View File

@@ -1,5 +1,6 @@
package net.gepafin.tendermanagement.dao;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
@@ -10,6 +11,7 @@ import java.util.stream.Collectors;
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.service.*;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -124,6 +126,17 @@ public class CallDao {
callEntity.setConfidi(createCallRequest.getConfidi());
}
callEntity.setDocumentationRequested(createCallRequest.getDocumentationRequested());
if (createCallRequest.getAmountMin() != null && createCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) {
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG));
}
callEntity.setAmountMin(createCallRequest.getAmountMin());
if(createCallRequest.getEmail()==null || Boolean.FALSE.equals(Utils.isValidEmail(createCallRequest.getEmail()))){
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.VALIDATION_EMAIL,createCallRequest.getEmail()));
}
callEntity.setEmail(createCallRequest.getEmail());
callEntity.setPhoneNumber(createCallRequest.getPhoneNumber());
callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime()));
callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime()));
callEntity = callRepository.save(callEntity);
return callEntity;
}
@@ -259,6 +272,11 @@ public class CallDao {
createCallResponseBean.setDocumentationRequested(callEntity.getDocumentationRequested());
createCallResponseBean.setPriorityArea(callEntity.getPriorityArea());
createCallResponseBean.setConfidi(callEntity.getConfidi());
createCallResponseBean.setAmountMin(callEntity.getAmountMin());
createCallResponseBean.setPhoneNumber(callEntity.getPhoneNumber());
createCallResponseBean.setEndTime(callEntity.getEndTime());
createCallResponseBean.setStartTime(callEntity.getStartTime());
createCallResponseBean.setEmail(callEntity.getEmail());
createCallResponseBean.setCreatedDate(callEntity.getCreatedDate());
createCallResponseBean.setUpdatedDate(callEntity.getUpdatedDate());
return createCallResponseBean;
@@ -456,6 +474,18 @@ public class CallDao {
setIfUpdated(callEntity::getAmountMax, callEntity::setAmountMax, updateCallRequest.getAmountMax());
setIfUpdated(callEntity::getDocumentationRequested, callEntity::setDocumentationRequested,
updateCallRequest.getDocumentationRequested());
if (updateCallRequest.getAmountMin() != null && updateCallRequest.getAmountMin().compareTo(BigDecimal.ZERO) < 0) {
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.AMOUNT_GREATER_THAN_ZERO_MSG));
}
if(updateCallRequest.getEmail()==null || Boolean.FALSE.equals(Utils.isValidEmail(updateCallRequest.getEmail()))){
throw new CustomValidationException(Status.VALIDATION_ERROR,Translator.toLocale(GepafinConstant.VALIDATION_EMAIL,updateCallRequest.getEmail()));
}
setIfUpdated(callEntity::getAmountMin, callEntity::setAmountMin, updateCallRequest.getAmountMin());
setIfUpdated(callEntity::getEmail, callEntity::setEmail, updateCallRequest.getEmail());
setIfUpdated(callEntity::getPhoneNumber, callEntity::setPhoneNumber, updateCallRequest.getPhoneNumber());
setIfUpdated(callEntity::getStartTime, callEntity::setStartTime, DateTimeUtil.parseTime(updateCallRequest.getStartTime()));
setIfUpdated(callEntity::getEndTime, callEntity::setEndTime, DateTimeUtil.parseTime(updateCallRequest.getEndTime()));
setIfUpdated(callEntity::getConfidi, callEntity::setConfidi, updateCallRequest.getConfidi());
updateLookUpData(callEntity, updateCallRequest.getAimedTo(), LookUpDataTypeEnum.AIMED_TO);
updateFaq(updateCallRequest.getFaq(), callEntity, userEntity, LookUpDataTypeEnum.FAQ);
@@ -531,6 +561,11 @@ public class CallDao {
callDetailsResponseBean.setThreshold(callEntity.getThreshold());
callDetailsResponseBean.setDocumentationRequested(callEntity.getDocumentationRequested());
callDetailsResponseBean.setPriorityArea(callEntity.getPriorityArea());
callDetailsResponseBean.setAmountMin(callEntity.getAmountMin());
callDetailsResponseBean.setEmail(callEntity.getEmail());
callDetailsResponseBean.setEndTime(callEntity.getEndTime());
callDetailsResponseBean.setStartTime(callEntity.getStartTime());
callDetailsResponseBean.setPhoneNumber(callEntity.getPhoneNumber());
callDetailsResponseBean.setCreatedDate(callEntity.getCreatedDate());
callDetailsResponseBean.setUpdatedDate(callEntity.getUpdatedDate());
return callDetailsResponseBean;

View File

@@ -0,0 +1,175 @@
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) {
CompanyEntity existingCompany = companyRepository.findByVatNumber(companyRequest.getVatNumber());
if (existingCompany != null) {
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyId(userEntity.getId(), existingCompany.getId())
.orElse(null);
if (existingRelation == null) {
createUserWithCompanyRelation(userEntity, existingCompany);
} else {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.USER_ALREADY_CONNECTED_TO_COMPANY));
}
return convertCompanyEntityToCompanyResponse(existingCompany);
} else {
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();
}
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
return userWithCompanyRepository.findByUserIdAndCompanyId(userId, companyId).orElseThrow(() -> new CustomValidationException(Status.UNAUTHORIZED,
Translator.toLocale(GepafinConstant.UNAUTHORIZED)));
}
}

View File

@@ -12,8 +12,11 @@ import net.gepafin.tendermanagement.model.request.FaqReq;
import net.gepafin.tendermanagement.model.response.FaqResponseBean;
import net.gepafin.tendermanagement.repositories.FaqRepository;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.LookUpDataService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.Validator;
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;
import org.springframework.beans.factory.annotation.Autowired;
@@ -36,11 +39,24 @@ public class FaqDao {
@Autowired
private LookUpDataService lookUpDataService;
public FaqResponseBean createFaq(FaqReq faqRequest, UserEntity userEntity, Long callId) {
FaqEntity entity = new FaqEntity();
@Autowired
private Validator validator;
@Autowired
private CompanyService companyService;
public FaqResponseBean createFaq(FaqReq faqRequest, UserEntity userEntity, Long callId, Long companyId) {
CallEntity callEntity = callService.validateCall(callId);
entity = createOrUpdateFaqEntity(faqRequest, callEntity, userEntity,
FaqEntity entity = createOrUpdateFaqEntity(faqRequest, callEntity, userEntity,
LookUpDataEntity.LookUpDataTypeEnum.FAQ);
if (validator.checkIsBeneficiary() && companyId == null) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.COMPANY_ID_MANDATORY));
}
if(companyId!=null) {
companyService.validateCompany(companyId);
entity.setCompanyId(companyId);
}
faqRepository.save(entity);
return convertToFaqResponseBean(entity);
}

View File

@@ -4,20 +4,16 @@ import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.FlowDataEntity;
import net.gepafin.tendermanagement.entities.FlowDataEntity;
import net.gepafin.tendermanagement.entities.FlowEdgesEntity;
import net.gepafin.tendermanagement.enums.CallStatusEnum;
import net.gepafin.tendermanagement.model.request.FlowDataRequestBean;
import net.gepafin.tendermanagement.model.request.FlowEdgesRequestBean;
import net.gepafin.tendermanagement.model.request.FlowRequestBean;
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
import net.gepafin.tendermanagement.model.response.FlowDataResponseBean;
import net.gepafin.tendermanagement.model.response.FlowEdgesResponseBean;
import net.gepafin.tendermanagement.model.response.FlowResponseBean;
import net.gepafin.tendermanagement.repositories.CallRepository;
import net.gepafin.tendermanagement.repositories.FlowDataRepository;
import net.gepafin.tendermanagement.repositories.FlowDataRepository;
import net.gepafin.tendermanagement.repositories.FlowEdgesRepository;
import net.gepafin.tendermanagement.repositories.FlowEdgesRepository;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.FormService;
@@ -29,7 +25,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

View File

@@ -1,7 +1,6 @@
package net.gepafin.tendermanagement.dao;
import java.util.*;
import java.util.stream.Collectors;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.repositories.*;
@@ -20,7 +19,6 @@ import net.gepafin.tendermanagement.enums.FormActionEnum;
import net.gepafin.tendermanagement.model.response.NextOrPreviousFormResponse;
import net.gepafin.tendermanagement.service.FormService;
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
@@ -296,6 +294,8 @@ public class FlowFormDao {
applicationDao.processForm(formEntity, applicationEntity));
nextOrPreviousFormResponse.setCallId(applicationEntity.getCall().getId());
nextOrPreviousFormResponse.setCallTitle(applicationEntity.getCall().getName());
nextOrPreviousFormResponse.setCompanyId(applicationEntity.getCompany().getId());
nextOrPreviousFormResponse.setCompanyName(applicationEntity.getCompany().getCompanyName());
List<FlowEdgesEntity> flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
Long totalFormSteps = calculateTotalSteps(flowEdgesList);

View File

@@ -4,16 +4,20 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
import net.gepafin.tendermanagement.entities.RoleEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.impl.AuthenticationService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
@@ -25,20 +29,22 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.List;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
import java.util.regex.Pattern;
@Repository
@Component
public class UserDao {
private final Logger log = LoggerFactory.getLogger(UserDao.class);
@Autowired
private UserRepository userRepository;
@Autowired
private CompanyDao companyDao;
@Autowired
private AuthenticationService authService;
@@ -48,9 +54,42 @@ public class UserDao {
@Autowired
private RoleDao roleDao;
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
@Autowired
private BeneficiaryRepository beneficiaryRepository;
if (Boolean.FALSE.equals(isValidEmail(userReq.getEmail()))) {
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
validateUserRequest(tempToken, userReq);
validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken);
RoleEntity roleEntity = getRoleEntity(userReq.getRoleId());
BeneficiaryEntity beneficiary = createBeneficiary(roleEntity, userReq);
UserEntity userEntity = convertUserRequestToUserEntity(beneficiary, roleEntity, userReq);
log.info("User created with ID: {}", userEntity.getId());
return authService.getJWTTokenBean(userEntity, Boolean.TRUE);
}
private BeneficiaryEntity createBeneficiary(RoleEntity roleEntity, UserReq userReq) {
BeneficiaryEntity beneficiaryEntity = null;
if (RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType())) {
beneficiaryEntity = new BeneficiaryEntity();
beneficiaryEntity.setAddress(userReq.getAddress());
beneficiaryEntity.setCity(userReq.getCity());
beneficiaryEntity.setCodiceFiscale(userReq.getCodiceFiscale());
beneficiaryEntity.setCountry(userReq.getCountry());
beneficiaryEntity.setDateOfBirth(userReq.getDateOfBirth());
beneficiaryEntity.setEmail(userReq.getEmail());
beneficiaryEntity.setFirstName(userReq.getFirstName());
beneficiaryEntity.setLastName(userReq.getLastName());
beneficiaryEntity.setOrganization(userReq.getOrganization());
beneficiaryEntity.setPhoneNumber(userReq.getPhoneNumber());
beneficiaryEntity =beneficiaryRepository.save(beneficiaryEntity);
}
return beneficiaryEntity;
}
private void validateUserRequest(String tempToken, UserReq userReq) {
if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
}
@@ -61,7 +100,7 @@ public class UserDao {
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
}
if (Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getCodiceFiscale()))
&& userRepository.existsByCodiceFiscale(userReq.getCodiceFiscale())) {
&& userRepository.existsByBeneficiaryCodiceFiscale(userReq.getCodiceFiscale())) {
log.error("User creation failed: CodiceFiscale {} already exists", userReq.getCodiceFiscale());
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CODICE_FISCALE_EXISTS));
@@ -70,15 +109,9 @@ public class UserDao {
throw new ResourceNotFoundException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.ROLE_ID_MANDATORY));
}
if(tempToken != null) {
if (tempToken != null) {
userReq.setRoleId(null);
}
validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken);
UserEntity userEntity = convertUserRequestToUserEntity(userReq);
userEntity = userRepository.save(userEntity);
log.info("User created with ID: {}", userEntity.getId());
return authService.getJWTTokenBean(userEntity, Boolean.TRUE);
}
private void validatePassword(String password, String confirmPassword, String tempToken) {
@@ -124,22 +157,24 @@ public class UserDao {
return convertUserEntityToUserResponse(userEntity);
}
private UserEntity convertUserRequestToUserEntity(UserReq userReq) {
private UserEntity convertUserRequestToUserEntity(BeneficiaryEntity beneficiary, RoleEntity roleEntity, UserReq userReq) {
UserEntity userEntity = new UserEntity();
if(Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getPassword()))) {
userEntity.setPassword(passwordEncoder.encode(userReq.getPassword()));
}
userEntity.setRoleEntity(roleEntity);
userEntity.setEmail(userReq.getEmail());
userEntity.setFirstName(userReq.getFirstName());
userEntity.setStatus(UserStatusEnum.ACTIVE.getValue());
userEntity.setBeneficiary(beneficiary);
if (Boolean.FALSE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType()))) {
userEntity.setFirstName(userReq.getFirstName());
userEntity.setLastName(userReq.getLastName());
userEntity.setOrganization(userReq.getOrganization());
userEntity.setAddress(userReq.getAddress());
userEntity.setPhoneNumber(userReq.getPhoneNumber());
userEntity.setRoleEntity(getRoleEntity(userReq.getRoleId()));
userEntity.setCodiceFiscale(userReq.getCodiceFiscale());
userEntity.setDateOfBirth(userReq.getDateOfBirth());
return userEntity;
}
return userRepository.save(userEntity);
}
private RoleEntity getRoleEntity(Long roleId) {
@@ -156,6 +191,13 @@ public class UserDao {
userResponseBean.setCreatedDate(userEntity.getCreatedDate());
userResponseBean.setUpdatedDate(userEntity.getUpdatedDate());
userResponseBean.setEmail(userEntity.getEmail());
userResponseBean.setStatus(UserStatusEnum.valueOf(userEntity.getStatus()));
RoleResponseBean roleResponseBean = roleDao.convertRoleEntityToRoleResponse(userEntity.getRoleEntity());
userResponseBean.setRole(roleResponseBean);
userResponseBean.setLastLogin(userEntity.getLastLogin());
List<CompanyResponse> companyResponseBeans = companyDao.getCompanyByUserId(userEntity.getId());
userResponseBean.setCompanies(companyResponseBeans);
if (userEntity.getBeneficiary() == null) {
userResponseBean.setFirstName(userEntity.getFirstName());
userResponseBean.setLastName(userEntity.getLastName());
userResponseBean.setPhoneNumber(userEntity.getPhoneNumber());
@@ -163,18 +205,24 @@ public class UserDao {
userResponseBean.setAddress(userEntity.getAddress());
userResponseBean.setCity(userEntity.getCity());
userResponseBean.setCountry(userEntity.getCountry());
userResponseBean.setStatus(UserStatusEnum.valueOf(userEntity.getStatus()));
RoleResponseBean roleResponseBean = roleDao.convertRoleEntityToRoleResponse(userEntity.getRoleEntity());
userResponseBean.setRole(roleResponseBean);
userResponseBean.setLastLogin(userEntity.getLastLogin());
userResponseBean.setCodiceFiscale(userEntity.getCodiceFiscale());
userResponseBean.setDateOfBirth(userEntity.getDateOfBirth());
} else {
userResponseBean.setFirstName(userEntity.getBeneficiary().getFirstName());
userResponseBean.setLastName(userEntity.getBeneficiary().getLastName());
userResponseBean.setPhoneNumber(userEntity.getBeneficiary().getPhoneNumber());
userResponseBean.setOrganization(userEntity.getBeneficiary().getOrganization());
userResponseBean.setAddress(userEntity.getBeneficiary().getAddress());
userResponseBean.setCity(userEntity.getBeneficiary().getCity());
userResponseBean.setCountry(userEntity.getBeneficiary().getCountry());
userResponseBean.setCodiceFiscale(userEntity.getBeneficiary().getCodiceFiscale());
userResponseBean.setDateOfBirth(userEntity.getBeneficiary().getDateOfBirth());
}
return userResponseBean;
}
public UserResponseBean getUserById(Long id) {
log.info("Fetching user with ID: {}", id);
UserEntity userEntity=validateUser(id);
UserEntity userEntity = validateUser(id);
// if (!UserStatusEnum.ACTIVE.getValue().equals(userEntity.getStatus())) {
// log.info("User with ID: {} is not active", id);
// throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
@@ -262,16 +310,6 @@ public class UserDao {
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) {
log.info("Updating status for user with ID: {}", userId);
UserEntity userEntity=validateUser(userId);

View File

@@ -1,8 +1,13 @@
package net.gepafin.tendermanagement.dao;
import feign.FeignException;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
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.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -67,8 +72,17 @@ public class VatCheckDao {
}
} catch (FeignException ex) {
log.error("Exception occurred while checking vat number: {0}", ex);
throw ex;
Utils.callException(ex.status(), ex);
}
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

@@ -13,9 +13,12 @@ import java.time.LocalDateTime;
@Builder
public class ApplicationEntity extends BaseEntity {
@Column(name = "USER_ID")
private Long userId;
@ManyToOne
@JoinColumn(name = "USER_ID", nullable = false)
private UserEntity user;
@JoinColumn(name = "COMPANY_ID", nullable = false)
private CompanyEntity company;
@Column(name = "SUBMISSION_DATE")
private LocalDateTime submissionDate;

View File

@@ -0,0 +1,47 @@
package net.gepafin.tendermanagement.entities;
import java.time.LocalDateTime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.validation.constraints.Email;
import lombok.Data;
@Entity
@Table(name = "BENEFICIARY")
@Data
public class BeneficiaryEntity extends BaseEntity {
@Email
@Column(name = "EMAIL")
private String email;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "PHONE_NUMBER")
private String phoneNumber;
@Column(name = "ORGANIZATION")
private String organization;
@Column(name = "ADDRESS")
private String address;
@Column(name = "CITY")
private String city;
@Column(name = "COUNTRY")
private String country;
@Column(name = "CODICE_FISCALE")
private String codiceFiscale;
@Column(name = "DATE_OF_BIRTH")
private LocalDateTime dateOfBirth;
}

View File

@@ -8,6 +8,7 @@ import lombok.Builder;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Entity
@Table(name = "CALL")
@@ -68,5 +69,20 @@ public class CallEntity extends BaseEntity {
@Column(name="FINAL_FORM")
private Long finalForm;
@Column(name = "AMOUNT_MIN")
private BigDecimal amountMin;
@Column(name="EMAIL")
private String email;
@Column(name = "PHONE_NUMBER")
private String phoneNumber;
@Column(name = "START_TIME")
private LocalTime startTime;
@Column(name = "END_TIME")
private LocalTime endTime;
}

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

@@ -42,5 +42,8 @@ public class FaqEntity extends BaseEntity {
@Column(name ="IS_DELETED", nullable = false)
private Boolean isDeleted = false;
@Column(name ="COMPANY_ID")
private Long companyId;
}

View File

@@ -59,9 +59,10 @@ public class UserEntity extends BaseEntity {
@Column(name = "RESET_PASSWORD_TOKEN", length = 255, nullable = true)
private String resetPasswordToken;
@Column(name = "CODICE_FISCALE")
private String codiceFiscale;
@Column(name = "DATE_OF_BIRTH")
private LocalDateTime dateOfBirth;
@OneToOne
@JoinColumn(name = "BENEFICIARY_ID")
private BeneficiaryEntity beneficiary;
}

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

@@ -2,7 +2,9 @@ package net.gepafin.tendermanagement.model.request;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import lombok.Data;
@Data
@@ -26,6 +28,16 @@ public class CreateCallRequestStep1 {
private String documentationRequested;
private BigDecimal amountMin;
private String email;
private String phoneNumber;
private String startTime;
private String endTime;
private Boolean confidi;
private List<FaqReq> faq;

View File

@@ -2,6 +2,7 @@ package net.gepafin.tendermanagement.model.request;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import lombok.Data;
@@ -25,6 +26,16 @@ public class UpdateCallRequestStep1 {
private String documentationRequested;
private BigDecimal amountMin;
private String email;
private String phoneNumber;
private String startTime;
private String endTime;
private Boolean confidi;
private List<FaqReq> faq;

View File

@@ -20,6 +20,10 @@ public class ApplicationGetResponseBean {
private String callTitle;
private Long companyId;
private String companyName;
private List<FormApplicationResponse> form;
}

View File

@@ -27,4 +27,8 @@ public class ApplicationResponse{
private String comments;
private Long companyId;
private String companyName;
}

View File

@@ -5,6 +5,7 @@ import net.gepafin.tendermanagement.enums.CallStatusEnum;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@Data
public class CallDetailsResponseBean {
@@ -37,6 +38,16 @@ public class CallDetailsResponseBean {
private String documentationRequested;
private BigDecimal amountMin;
private String email;
private String phoneNumber;
private LocalTime startTime;
private LocalTime endTime;
private LocalDateTime createdDate;
private LocalDateTime updatedDate;

View File

@@ -2,6 +2,7 @@ package net.gepafin.tendermanagement.model.response;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import lombok.Data;
@@ -40,6 +41,16 @@ public class CallResponse {
private Boolean confidi;
private BigDecimal amountMin;
private String email;
private String phoneNumber;
private LocalTime startTime;
private LocalTime endTime;
private LocalDateTime createdDate;
private LocalDateTime updatedDate;

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

@@ -6,6 +6,7 @@ import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
import java.util.List;
@Getter
@Setter
@@ -43,4 +44,6 @@ public class LoginResponse {
private LocalDateTime createdDate;
private LocalDateTime updatedDate;
private List<CompanyResponse> companies;
}

View File

@@ -18,6 +18,10 @@ public class NextOrPreviousFormResponse {
private Long currentStep;
private Long companyId;
private String companyName;
private ApplicationStatusTypeEnum applicationStatus;
private FormApplicationResponse applicationFormResponse;

View File

@@ -6,6 +6,7 @@ import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.BaseBean;
import java.time.LocalDateTime;
import java.util.List;
@Getter
@Setter
@@ -37,4 +38,5 @@ public class UserResponseBean extends BaseBean {
private LocalDateTime dateOfBirth;
private List<CompanyResponse> companies;
}

View File

@@ -3,6 +3,7 @@ package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.FaqEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@@ -11,9 +12,7 @@ import java.util.List;
import java.util.Optional;
@Repository
public interface ApplicationRepository extends JpaRepository<ApplicationEntity,Long> {
public Optional<ApplicationEntity> findByUserIdAndCallIdAndIsDeletedFalse(Long userId,Long callId);
public interface ApplicationRepository extends JpaRepository<ApplicationEntity, Long>, JpaSpecificationExecutor<ApplicationEntity> {
public List<ApplicationEntity> findByUserIdAndIsDeletedFalse(Long userId);
@@ -26,4 +25,9 @@ public interface ApplicationRepository extends JpaRepository<ApplicationEntity,L
public Optional<ApplicationEntity> findByIdAndUserIdAndIsDeletedFalse(Long id,Long userId);
Optional<ApplicationEntity> findByCompanyIdAndCallIdAndIsDeletedFalse(Long companyId, Long callId);
public Optional<ApplicationEntity> findByIdAndUserIdAndCallIdAndIsDeletedFalse(Long applicationId, Long userId,
Long callId);
}

View File

@@ -0,0 +1,11 @@
package net.gepafin.tendermanagement.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
@Repository
public interface BeneficiaryRepository extends JpaRepository<BeneficiaryEntity, Long> {
}

View File

@@ -0,0 +1,18 @@
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);
CompanyEntity findByVatNumber(String vatNumber);
}

View File

@@ -2,9 +2,11 @@ package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByEmailIgnoreCase(String email);
@@ -13,7 +15,7 @@ public interface UserRepository extends JpaRepository<UserEntity, Long> {
UserEntity findByEmail(String email);
Optional<UserEntity> findByCodiceFiscale(String cf);
Optional<UserEntity> findByBeneficiaryCodiceFiscale(String codiceFiscale);
boolean existsByCodiceFiscale(String codiceFiscale);
boolean existsByBeneficiaryCodiceFiscale(String codiceFiscale);
}

View File

@@ -0,0 +1,22 @@
package net.gepafin.tendermanagement.repositories;
import java.util.List;
import java.util.Optional;
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);
Optional<UserWithCompanyEntity> findByUserIdAndCompanyId(Long userId, Long companyId);
}

View File

@@ -19,15 +19,16 @@ public interface ApplicationService {
ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId);
List<ApplicationResponse> getAllApplications(HttpServletRequest request,Long callId);
List<ApplicationResponse> getAllApplications(HttpServletRequest request,Long callId, Long companyId);
void deleteApplication(HttpServletRequest request, Long applicationId);
public ApplicationEntity validateApplication(Long userId);
public ApplicationResponse createApplication(HttpServletRequest request, ApplicationRequest applicationRequest, Long callId);
public ApplicationResponse createApplication(HttpServletRequest request, Long companyId, ApplicationRequest applicationRequest, Long callId);
public NextOrPreviousFormResponse getNextOrPreviousForm(HttpServletRequest request, Long applicationId, Long formId, FormActionEnum action);
public void updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status);
}

View File

@@ -0,0 +1,30 @@
package net.gepafin.tendermanagement.service;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
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);
CompanyEntity validateCompany(Long companyId);
UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId);
}

View File

@@ -11,7 +11,7 @@ import net.gepafin.tendermanagement.model.response.FaqResponseBean;
public interface FaqService {
FaqResponseBean createFaq(HttpServletRequest request,Long callId, FaqReq faqRequest);
FaqResponseBean createFaq(HttpServletRequest request,Long callId, Long companyId, FaqReq faqRequest);
FaqResponseBean getFaqById(HttpServletRequest request, Long id);

View File

@@ -11,7 +11,7 @@ import org.springframework.web.bind.annotation.RequestHeader;
import java.net.URI;
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 {

View File

@@ -4,6 +4,7 @@ import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.ApplicationDao;
import net.gepafin.tendermanagement.dao.FlowFormDao;
import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.ApplicationRequest;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
@@ -35,9 +36,10 @@ public class ApplicationServiceImpl implements ApplicationService {
@Override
@Transactional(rollbackFor = Exception.class)
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean,Long applicationId, Long formId) {
public ApplicationResponseBean createApplication(HttpServletRequest request,
ApplicationRequestBean applicationRequestBean, Long applicationId, Long formId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.createApplication(applicationRequestBean,userEntity,formId,applicationId);
return applicationDao.createApplication(applicationRequestBean, userEntity, formId, applicationId);
}
@Override
@@ -60,9 +62,10 @@ public class ApplicationServiceImpl implements ApplicationService {
@Override
@Transactional(rollbackFor = Exception.class)
public ApplicationResponse createApplication(HttpServletRequest request, ApplicationRequest applicationRequest, Long callId) {
public ApplicationResponse createApplication(HttpServletRequest request, Long companyId, ApplicationRequest applicationRequest, Long callId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.createApplicationByCallId(applicationRequest,callId,userEntity);
CompanyEntity companyEntity = validator.validateUSerWithCompany(request, companyId);
return applicationDao.createApplicationByCallId(companyEntity, applicationRequest, callId, userEntity);
}
@Override
@@ -80,8 +83,11 @@ public class ApplicationServiceImpl implements ApplicationService {
@Override
@Transactional(readOnly = true)
public List<ApplicationResponse> getAllApplications(HttpServletRequest request,Long callId) {
public List<ApplicationResponse> getAllApplications(HttpServletRequest request, Long callId, Long companyId) {
UserEntity userEntity = validator.validateUser(request);
return applicationDao.getAllApplications(userEntity,callId);
if (companyId != null) {
validator.validateUSerWithCompany(request, companyId);
}
return applicationDao.getAllApplications(userEntity, callId, companyId);
}
}

View File

@@ -5,11 +5,13 @@ import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.CompanyDao;
import net.gepafin.tendermanagement.dao.RoleDao;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.LoginReq;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.response.LoginResponse;
import net.gepafin.tendermanagement.model.response.RoleResponseBean;
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
@@ -42,6 +44,8 @@ public class AuthenticationService {
private final TokenProvider tokenProvider;
private final AuthenticationManager authenticationManager;
@Autowired
private CompanyDao companyDao;
@Autowired
private UserRepository userRepository;
@@ -90,24 +94,38 @@ public class AuthenticationService {
return jwtToken;
}
private static LoginResponse getLoginResponse(UserEntity user, RoleResponseBean roleResponseBean) {
private LoginResponse getLoginResponse(UserEntity user, RoleResponseBean roleResponseBean) {
LoginResponse loginResponse = new LoginResponse();
loginResponse.setId(user.getId());
loginResponse.setEmail(user.getEmail());
loginResponse.setId(user.getId());
List<CompanyResponse> companyResponseBeans = companyDao.getCompanyByUserId(user.getId());
loginResponse.setCompanies(companyResponseBeans);
loginResponse.setRole(roleResponseBean);
loginResponse.setStatus(user.getStatus());
loginResponse.setLastLogin(user.getLastLogin());
loginResponse.setCreatedDate(user.getCreatedDate());
loginResponse.setUpdatedDate(user.getUpdatedDate());
if (user.getBeneficiary() == null) {
loginResponse.setFirstName(user.getFirstName());
loginResponse.setLastName(user.getLastName());
loginResponse.setRole(roleResponseBean);
loginResponse.setPhoneNumber(user.getPhoneNumber());
loginResponse.setAddress(user.getAddress());
loginResponse.setOrganization(user.getOrganization());
loginResponse.setCountry(user.getCountry());
loginResponse.setStatus(user.getStatus());
loginResponse.setCity(user.getCity());
loginResponse.setLastLogin(user.getLastLogin());
loginResponse.setCodiceFiscale(user.getCodiceFiscale());
loginResponse.setDateOfBirth(user.getDateOfBirth());
loginResponse.setCreatedDate(user.getCreatedDate());
loginResponse.setUpdatedDate(user.getUpdatedDate());
}else {
loginResponse.setFirstName(user.getBeneficiary().getFirstName());
loginResponse.setLastName(user.getBeneficiary().getLastName());
loginResponse.setPhoneNumber(user.getBeneficiary().getPhoneNumber());
loginResponse.setAddress(user.getBeneficiary().getAddress());
loginResponse.setOrganization(user.getBeneficiary().getOrganization());
loginResponse.setCountry(user.getBeneficiary().getCountry());
loginResponse.setCity(user.getBeneficiary().getCity());
loginResponse.setCodiceFiscale(user.getBeneficiary().getCodiceFiscale());
loginResponse.setDateOfBirth(user.getBeneficiary().getDateOfBirth());
}
return loginResponse;
}
public void logout(HttpServletRequest request, HttpServletResponse response) {
@@ -131,7 +149,7 @@ public class AuthenticationService {
Map<String, List<Object>> userAttributes = Utils
.convertStringIntoMap(samlResponseLogEntity.getAuthenticationObject());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
UserEntity userEntity = userRepository.findByCodiceFiscale(cf)
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscale(cf)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
samlResponseLogRepository.delete(samlResponseLogEntity);
@@ -150,7 +168,7 @@ public class AuthenticationService {
Map<String, List<Object>> userAttributes = Utils
.convertStringIntoMap(samlResponseLogEntity.getAuthenticationObject());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
if (userRepository.findByCodiceFiscale(cf).isPresent()) {
if (userRepository.existsByBeneficiaryCodiceFiscale(cf)) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_ALREADY_EXIST_MSG));
}

View File

@@ -10,6 +10,7 @@ import net.gepafin.tendermanagement.model.response.CallResponse;
import net.gepafin.tendermanagement.model.response.FlowResponseBean;
import net.gepafin.tendermanagement.model.response.FormResponseBean;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -28,6 +29,10 @@ public class CallValidatorServiceImpl {
.notNull(response.getAmount(), "amount")
.notNull(response.getAmountMax(), "amountMax")
.notNull(response.getThreshold(), "threshold")
.notNull(response.getEmail(),"email")
.notNull(response.getAmountMin(),"amountMin")
.notNull(response.getStartTime(),"startTime")
.notNull(response.getEndTime(),"endTime")
.notNull(response.getDocumentationRequested(), "documentationRequested")
.notEmpty(response.getAimedTo(), "aimedTo")
.notEmpty(response.getCriteria(), "criteria")

View File

@@ -0,0 +1,83 @@
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.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.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);
}
@Override
public CompanyEntity validateCompany(Long companyId) {
return companyDao.validateCompany(companyId);
}
@Override
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
return companyDao.validateUserWithCompny(userId, companyId);
}
}

View File

@@ -25,9 +25,9 @@ public class FaqServiceImpl implements FaqService {
private Validator validator;
@Override
public FaqResponseBean createFaq(HttpServletRequest request,Long callId, FaqReq faqRequest) {
public FaqResponseBean createFaq(HttpServletRequest request,Long callId, Long companyId, FaqReq faqRequest) {
UserEntity userEntity = validator.validateUser(request);
return faqDao.createFaq(faqRequest, userEntity,callId);
return faqDao.createFaq(faqRequest, userEntity, callId, companyId);
}
@Override

View File

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

View File

@@ -1,16 +1,29 @@
package net.gepafin.tendermanagement.util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;
@Component
public class DateTimeUtil {
private static final Pattern TIME_PATTERN = Pattern.compile(
"^((([01]?\\d|2[0-3]):([0-5]\\d)(:[0-5]\\d)?(\\s?[AP]M)?)|((0?[1-9]|1[0-2]):([0-5]\\d)(:[0-5]\\d)?\\s?[AP]M))$");
public static LocalDateTime DateServerToUTC(LocalDateTime systemDate) {
@@ -50,4 +63,27 @@ public class DateTimeUtil {
.from(localDateTime.atZone(ZoneId.systemDefault())
.toInstant());
}
public static LocalTime parseTime(String timeString) throws DateTimeParseException {
DateTimeFormatter formatter;
if(timeString==null) {
return null;
}
if (!TIME_PATTERN.matcher(timeString).matches()) {
throw new CustomValidationException(Status.BAD_REQUEST,"Invalid time format: " + timeString);
}
// Try to parse using default formats if no format is provided
String[] defaultFormats = {"HH:mm:ss", "HH:mm", "HH:mm:ss a", "hh:mm a"};
for (String defaultFormat : defaultFormats) {
formatter = DateTimeFormatter.ofPattern(defaultFormat);
try {
return LocalTime.parse(timeString, formatter);
} catch (DateTimeParseException e) {
// Continue to the next format
}
}
// If all parsing attempts fail, throw an exception
throw new CustomValidationException(Status.BAD_REQUEST,"Failed to parse time: " + timeString);
}
}

View File

@@ -1,17 +1,5 @@
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.Type;
import java.nio.charset.StandardCharsets;
@@ -21,8 +9,29 @@ import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
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 {
@@ -190,4 +199,32 @@ public class Utils {
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

@@ -4,8 +4,10 @@ import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import net.gepafin.tendermanagement.web.rest.api.errors.UnauthorizedAccessException;
@@ -27,6 +29,9 @@ public class Validator {
@Autowired
private UserService userService;
@Autowired
private CompanyService companyService;
public Map<String, Object> getUserInfoFromToken(HttpServletRequest request) {
return tokenProvider.getUserInfoAndUserIdFromToken(request);
}
@@ -36,7 +41,7 @@ public class Validator {
return userService.validateUser(Long.parseLong(userInfo.get("userId").toString()));
}
public Boolean checkIsSuperAdmin(HttpServletRequest request) {
public Boolean checkIsSuperAdmin() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
@@ -51,9 +56,35 @@ public class Validator {
}
public void validateRequest(HttpServletRequest request,RoleStatusEnum role) {
if (RoleStatusEnum.ROLE_SUPER_ADMIN.equals(role) && Boolean.FALSE.equals(checkIsSuperAdmin(request))) {
throw new UnauthorizedAccessException(Status.UNAUTHORIZED, Translator.toLocale(GepafinConstant.INVALID_USER));
if (RoleStatusEnum.ROLE_SUPER_ADMIN.equals(role) && Boolean.FALSE.equals(checkIsSuperAdmin())) {
throw new UnauthorizedAccessException(Status.UNAUTHORIZED, Translator.toLocale(GepafinConstant.INVALID_REQUEST));
}
}
public CompanyEntity validateUSerWithCompany(HttpServletRequest request, Long companyId) {
if (checkIsSuperAdmin()) {
return companyService.validateCompany(companyId);
}
Map<String, Object> userInfo = tokenProvider.getUserInfoAndUserIdFromToken(request);
companyService.validateUserWithCompny(getUserId(userInfo), companyId);
return companyService.validateCompany(companyId);
}
private Long getUserId(Map<String, Object> userInfo) {
return Long.parseLong(userInfo.get("userId").toString());
}
public Boolean checkIsBeneficiary() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
// Check if the user has the ROLE_SUPER_ADMIN authority
for (GrantedAuthority authority : authentication.getAuthorities()) {
if (RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(authority.getAuthority())) {
return true;
}
}
}
return false;
}
}

View File

@@ -67,7 +67,8 @@ public interface ApplicationApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "", produces = "application/json")
ResponseEntity<Response<List<ApplicationResponse>>> getAllApplications(HttpServletRequest request,
@Parameter(description = "The call id", required = false) @RequestParam(value = "callId", required = false) Long callId);
@Parameter(description = "The call id", required = false) @RequestParam(value = "callId", required = false) Long callId,
@Parameter(description = "The company id", required = false) @RequestParam(value = "companyId", required = false) Long companyId);
@Operation(summary = "Api to delete application",
responses = {
@@ -94,6 +95,7 @@ public interface ApplicationApi {
@PostMapping(value = "/call/{callId}",
produces = { "application/json" })
ResponseEntity<Response<ApplicationResponse>> createApplicationByCallId(HttpServletRequest request,
@Parameter(description = "The company ID", required = true) @RequestParam(value = "companyId", required = true) Long companyId,
@Parameter(description = " Flow request object", required = true) @Valid @RequestBody ApplicationRequest applicationRequest,
@Parameter(description = "The call ID", required = true) @PathVariable("callId") Long callId);

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

@@ -31,7 +31,11 @@ public interface DocumentApi {
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))})
@PostMapping(value = "/uploadFile/source/{sourceId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
default ResponseEntity<Response<List<DocumentResponseBean>>> uploadFile(HttpServletRequest httpServletRequest, @Parameter(description = "Source Id", required = true) @PathVariable("sourceId") Long sourceId, @RequestParam DocumentSourceTypeEnum sourceType, @RequestParam("file") List<MultipartFile> files, @RequestParam("documentType") DocumentTypeEnum documentTypeEnum) {
default ResponseEntity<Response<List<DocumentResponseBean>>> uploadFile(HttpServletRequest httpServletRequest,
@Parameter(description = "Source Id", required = true) @PathVariable("sourceId") Long sourceId,
@RequestParam("sourceType") DocumentSourceTypeEnum sourceType,
@RequestParam("file") List<MultipartFile> files,
@RequestParam("documentType") DocumentTypeEnum documentTypeEnum) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}

View File

@@ -24,7 +24,7 @@ public interface FaqApi {
})
@PostMapping(value = "/call/{callId}", consumes = "application/json", produces = "application/json")
ResponseEntity<Response<FaqResponseBean>> createFaq(HttpServletRequest request, @Parameter(description = "call id", required = true)
@PathVariable("callId") Long callId, @Valid @RequestBody FaqReq faqRequest);
@PathVariable("callId") Long callId, @RequestParam(value = "companyId", required = false) Long companyId, @Valid @RequestBody FaqReq faqRequest);
@Operation(summary = "API to get FAQ by id",
responses = {

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.model.util.Response;
import net.gepafin.tendermanagement.util.Utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import feign.FeignException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
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

@@ -60,14 +60,14 @@ public class ApplicationApiController implements ApplicationApi {
}
@Override
public ResponseEntity<Response<ApplicationResponse>> createApplicationByCallId(HttpServletRequest request, ApplicationRequest applicationRequest, Long callId) {
ApplicationResponse applicationResponseBean=applicationService.createApplication(request,applicationRequest,callId);
public ResponseEntity<Response<ApplicationResponse>> createApplicationByCallId(HttpServletRequest request, Long companyId, ApplicationRequest applicationRequest, Long callId) {
ApplicationResponse applicationResponseBean=applicationService.createApplication(request, companyId, applicationRequest, callId);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(applicationResponseBean, Status.SUCCESS, Translator.toLocale(GepafinConstant.APPLICATION_CREATED_SUCCESS_MSG)));
}
@Override
public ResponseEntity<Response<List<ApplicationResponse>>> getAllApplications(HttpServletRequest request,Long callId) {
List<ApplicationResponse> applications = applicationService.getAllApplications(request,callId);
public ResponseEntity<Response<List<ApplicationResponse>>> getAllApplications(HttpServletRequest request,Long callId,Long companyId) {
List<ApplicationResponse> applications = applicationService.getAllApplications(request,callId,companyId);
log.info("Get All Applications");
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(applications, Status.SUCCESS, Translator.toLocale(GepafinConstant.GET_APPLICATION_SUCCESS_MSG)));

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

@@ -22,8 +22,8 @@ public class FaqApiController implements FaqApi {
private FaqService faqService;
@Override
public ResponseEntity<Response<FaqResponseBean>> createFaq(HttpServletRequest request, Long callId,FaqReq faqRequest) {
FaqResponseBean response = faqService.createFaq(request,callId, faqRequest);
public ResponseEntity<Response<FaqResponseBean>> createFaq(HttpServletRequest request, Long callId, Long companyId, FaqReq faqRequest) {
FaqResponseBean response = faqService.createFaq(request,callId, companyId, faqRequest);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(response, Status.SUCCESS, Translator.toLocale(GepafinConstant.FAQ_CREATED_SUCCESSFULLY)));
}

View File

@@ -738,4 +738,100 @@
<dropNotNullConstraint tableName="gepafin_user" columnName="password"/>
</changeSet>
<changeSet id="27-09-2024_1" author="Rajesh Khore">
<createTable tableName="beneficiary">
<column name="id" type="INTEGER" autoIncrement="true">
<constraints nullable="false" primaryKey="true"
primaryKeyName="beneficiary_pkey" />
</column>
<column name="EMAIL" type="VARCHAR(255)" />
<column name="FIRST_NAME" type="VARCHAR(255)" />
<column name="LAST_NAME" type="VARCHAR(255)" />
<column name="PHONE_NUMBER" type="VARCHAR(255)" />
<column name="ORGANIZATION" type="TEXT" />
<column name="ADDRESS" type="TEXT" />
<column name="CITY" type="TEXT" />
<column name="COUNTRY" type="TEXT" />
<column name="CODICE_FISCALE" type="varchar(255)">
<constraints nullable="true" unique="true"/>
</column>
<column name="DATE_OF_BIRTH" type="TIMESTAMP" />
<column name="created_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
<column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE"/>
</createTable>
<dropColumn tableName="gepafin_user" columnName="codice_fiscale"/>
<dropNotNullConstraint tableName="gepafin_user" columnName="first_name"/>
<dropNotNullConstraint tableName="gepafin_user" columnName="last_name"/>
<addColumn tableName="gepafin_user">
<column name="beneficiary_id" type="INTEGER">
<constraints nullable="true" foreignKeyName="fk_beneficiary_gepafin_user" references="beneficiary(id)"/>
</column>
</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 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>
<changeSet id="27-09-2024_4" author="Rajesh Khore">
<addColumn tableName="APPLICATION">
<column name="COMPANY_ID" type="INTEGER">
<constraints nullable="true" foreignKeyName="fk_COMPANY_APPLICATION" references="company(id)"/>
</column>
</addColumn>
<addColumn tableName="FAQ">
<column name="COMPANY_ID" type="INTEGER"/>
</addColumn>
</changeSet>
<changeSet id="01-10-2024_1" author="Nisha Kashyap">
<addColumn tableName="call">
<column name="amount_min" type="numeric"></column>
<column name="phone_number" type="VARCHAR(255)"></column>
<column name="email" type="VARCHAR(255)"></column>
<column name="end_time" type="TIME"></column>
<column name="start_time" type="TIME"></column>
</addColumn>
</changeSet>
</databaseChangeLog>

View File

@@ -194,3 +194,15 @@ codice.fiscale.exists=This codice fiscale is already associated with another use
total.steps.not.zero=Total steps cannot be zero.
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.
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.
company.id.mandatory=Company id is mandatory.
user.already.connected.to.company=The user is already connected to this company.

View File

@@ -187,3 +187,15 @@ 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.
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.
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.
company.id.mandatory=L'ID dell'azienda è obbligatorio.
user.already.connected.to.company=L'utente è già collegato a questa azienda.