resolved conflict

This commit is contained in:
nisha
2024-10-09 13:27:14 +05:30
37 changed files with 832 additions and 73 deletions

View File

@@ -15,7 +15,7 @@ import jakarta.servlet.http.HttpServletResponse;
@Component
public class SamlFailureHandler implements AuthenticationFailureHandler {
private final Logger logger = LoggerFactory.getLogger(SamlSuccessHandler.class);
private final Logger logger = LoggerFactory.getLogger(SamlFailureHandler.class);
@Value("${fe.base.url}")
private String feBaseUrl;

View File

@@ -96,32 +96,53 @@ public class SecurityConfig {
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(auth -> auth
// Allow public access to the login endpoints
// Apply stateless session management globally
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
// Public endpoints
.requestMatchers("/v1/user/login").permitAll() // JWT-based login
.requestMatchers("/v1/user").permitAll() // User registration
.requestMatchers("/v1/user/sso/validate/existing-user/{token}").permitAll()
.requestMatchers("/v1/user/sso/validate/new-user/{token}").permitAll()
.requestMatchers("/v1/saml/**").permitAll() // JWT-based login
.requestMatchers("/saml2/**").permitAll() // SAML login initiation
.requestMatchers("/swagger-ui/**").permitAll() // Swagger docs
.requestMatchers("/v1/api-docs/**").permitAll() // API docs
.anyRequest().authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
// Add SAML2 login configuration (for BENEFICIARI)
/*
* .saml2Login(saml -> saml.loginPage("/saml/login") // Entry point for SAML
* login .defaultSuccessUrl("/") // Redirect after successful SAML login );
*/
.saml2Login(saml -> saml.defaultSuccessUrl("/").successHandler(samlSuccessHandler)
.failureHandler(samlFailureHandler));
// SAML-related endpoints
.requestMatchers("/v1/saml/**", "/saml2/**").permitAll()
// Other authenticated requests
.anyRequest().authenticated())
// Globally use stateless session management for most requests
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// SAML2 login configuration
.saml2Login(saml -> saml
.defaultSuccessUrl("/")
.successHandler(samlSuccessHandler)
.failureHandler(samlFailureHandler));
return http.build();
}
// Add another SecurityFilterChain for SAML requests with stateful session management
@Bean
public SecurityFilterChain samlSecurityFilterChain(HttpSecurity http) throws Exception {
// Apply stateful session management for SAML-related endpoints
http
.securityMatcher("/v1/saml/**", "/saml2/**") // Match SAML requests
.authorizeHttpRequests(auth -> auth
.requestMatchers("/v1/saml/**", "/saml2/**").permitAll()
.anyRequest().authenticated())
// Use stateful session management for SAML requests
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
return http.build();
}
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()

View File

@@ -179,10 +179,26 @@ public class GepafinConstant {
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";
public static final String YYYY_MM_DD_DASH = "yyyy-MM-dd";
public static final String YYYY_MM_DD_SLASH = "yyyy/MM/dd";
public static final String DELEGATION_TEMPLATE = "DELEGATION_TEMPLATE";
public static final String VALIDATION_ERROR_MISSING_FIRSTNAME = "validation.error.missing.firstName";
public static final String VALIDATION_ERROR_MISSING_LASTNAME = "validation.error.missing.lastName";
public static final String VALIDATION_ERROR_MISSING_CODICEFISCALE = "validation.error.missing.codiceFiscale";
public static final String DELEGATION_FILE_UPLOAD_SUCCESS = "delegation.file.upload.success";
public static final String DELEGATION_FETCH_SUCCESS = "delegation.fetch.success";
public static final String DELEGATION_TEMPLATE_GENERATION_ERROR = "delegation.template.generation.error";
public static final String VALIDATION_ERROR_FILE_EMPTY = "validation.error.file.empty";
public static final String VALIDATION_ERROR_FILE_INVALIDTYPE = "validation.error.file.invalidType";
public static final String UPLOAD_ERROR_S3 = "upload.error.s3";
public static final String CALL_NOT_STARTED_YET = "call.not.started.yet";
public static final String CALL_ALREADY_ENDED = "call.already.ended";
public static final String APPLICATION_STATUS_UPDATED_SUCCESSFULLY = "application.status.updated.successfully";
public static final String APPLICATION_ALREADY_IN_PREVIOUS_STATUS = "application.already.in.provided.status";
public static final String DELEGATION_NOT_FOUND = "delegation.not.found";
public static final String USER_COMPANY_RELATION_NOT_FOUND = "user.company.relation.not.found";
public static final String DELEGATION_DELETE_SUCCESS = "delegation.delete.success";
}

View File

@@ -21,6 +21,8 @@ import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationExceptio
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
public class CompanyDao {
@@ -33,24 +35,26 @@ public class CompanyDao {
@Autowired
private UserWithCompanyRepository userWithCompanyRepository;
public CompanyResponse createCompany(UserEntity userEntity, CompanyRequest companyRequest) {
CompanyEntity existingCompany = companyRepository.findByVatNumber(companyRequest.getVatNumber());
UserWithCompanyEntity userWithCompanyEntity = null;
if (existingCompany != null) {
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyId(userEntity.getId(), existingCompany.getId())
.orElse(null);
if (existingRelation == null) {
createUserWithCompanyRelation(userEntity, existingCompany);
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, existingCompany, companyRequest.getIsLegalRepresentant());
} else {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.USER_ALREADY_CONNECTED_TO_COMPANY));
}
return convertCompanyEntityToCompanyResponse(existingCompany);
return convertCompanyEntityToCompanyResponse(existingCompany, userWithCompanyEntity);
} else {
validateCompany(companyRequest);
CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(companyRequest);
companyRepository.save(companyEntity);
createUserWithCompanyRelation(userEntity, companyEntity);
return convertCompanyEntityToCompanyResponse(companyEntity);
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, companyEntity, companyRequest.getIsLegalRepresentant());
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
}
}
@@ -72,13 +76,14 @@ public class CompanyDao {
}
}
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity) {
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity, Boolean isLegalRepresentant) {
UserWithCompanyEntity userWithCompanyEntity = new UserWithCompanyEntity();
if (userEntity.getBeneficiary() != null) {
userWithCompanyEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
userWithCompanyEntity.setCompanyId(companyEntity.getId());
userWithCompanyEntity.setUserId(userEntity.getId());
userWithCompanyEntity.setIsLegalRepresentant(isLegalRepresentant);
return userWithCompanyRepository.save(userWithCompanyEntity);
}
@@ -97,10 +102,12 @@ public class CompanyDao {
entity.setEmail(request.getEmail());
entity.setNumberOfEmployees(request.getNumberOfEmployees());
entity.setAnnualRevenue(request.getAnnualRevenue());
entity.setContactName(request.getContactName());
entity.setContactEmail(request.getContactEmail());
return entity;
}
private CompanyResponse convertCompanyEntityToCompanyResponse(CompanyEntity entity) {
private CompanyResponse convertCompanyEntityToCompanyResponse(CompanyEntity entity, UserWithCompanyEntity userWithCompanyEntity) {
CompanyResponse response = new CompanyResponse();
response.setId(entity.getId());
response.setCompanyName(entity.getCompanyName());
@@ -116,33 +123,44 @@ public class CompanyDao {
response.setEmail(entity.getEmail());
response.setNumberOfEmployees(entity.getNumberOfEmployees());
response.setAnnualRevenue(entity.getAnnualRevenue());
if(userWithCompanyEntity!=null) {
response.setIsLegalRepresentant(userWithCompanyEntity.getIsLegalRepresentant());
}
response.setCreatedDate(entity.getCreatedDate());
response.setUpdatedDate(entity.getUpdatedDate());
response.setContactName(entity.getContactName());
response.setContactEmail(entity.getContactEmail());
return response;
}
public CompanyResponse updateCompany(UserEntity userEntity, Long companyId, CompanyRequest companyRequest) {
CompanyEntity companyEntity = validateCompany(companyId);
Utils.setIfUpdated(companyEntity::getCompanyName, companyEntity::setCompanyName,
setIfUpdated(companyEntity::getCompanyName, companyEntity::setCompanyName,
companyRequest.getCompanyName());
Utils.setIfUpdated(companyEntity::getVatNumber, companyEntity::setVatNumber, companyRequest.getVatNumber());
Utils.setIfUpdated(companyEntity::getCodiceFiscale, companyEntity::setCodiceFiscale,
setIfUpdated(companyEntity::getVatNumber, companyEntity::setVatNumber, companyRequest.getVatNumber());
setIfUpdated(companyEntity::getCodiceFiscale, companyEntity::setCodiceFiscale,
companyRequest.getCodiceFiscale());
Utils.setIfUpdated(companyEntity::getAddress, companyEntity::setAddress, companyRequest.getAddress());
Utils.setIfUpdated(companyEntity::getPhoneNumber, companyEntity::setPhoneNumber,
setIfUpdated(companyEntity::getAddress, companyEntity::setAddress, companyRequest.getAddress());
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,
setIfUpdated(companyEntity::getCity, companyEntity::setCity, companyRequest.getCity());
setIfUpdated(companyEntity::getProvince, companyEntity::setProvince, companyRequest.getProvince());
setIfUpdated(companyEntity::getCap, companyEntity::setCap, companyRequest.getCap());
setIfUpdated(companyEntity::getCountry, companyEntity::setCountry, companyRequest.getCountry());
setIfUpdated(companyEntity::getPec, companyEntity::setPec, companyRequest.getPec());
setIfUpdated(companyEntity::getEmail, companyEntity::setEmail, companyRequest.getEmail());
setIfUpdated(companyEntity::getNumberOfEmployees, companyEntity::setNumberOfEmployees,
companyRequest.getNumberOfEmployees());
Utils.setIfUpdated(companyEntity::getAnnualRevenue, companyEntity::setAnnualRevenue,
setIfUpdated(companyEntity::getAnnualRevenue, companyEntity::setAnnualRevenue,
companyRequest.getAnnualRevenue());
setIfUpdated(companyEntity::getContactName,companyEntity::setContactName,companyRequest.getContactName());
setIfUpdated(companyEntity::getContactEmail,companyEntity::setContactEmail,companyRequest.getContactEmail());
companyRepository.save(companyEntity);
return convertCompanyEntityToCompanyResponse(companyEntity);
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
Utils.setIfUpdated(userWithCompanyEntity::getIsLegalRepresentant, userWithCompanyEntity::setIsLegalRepresentant,
companyRequest.getIsLegalRepresentant());
userWithCompanyRepository.save(userWithCompanyEntity);
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
}
public CompanyEntity validateCompany(Long companyId) {
@@ -151,7 +169,8 @@ public class CompanyDao {
}
public CompanyResponse getCompany(UserEntity userEntity, Long companyId) {
return convertCompanyEntityToCompanyResponse(validateCompany(companyId));
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
return convertCompanyEntityToCompanyResponse(validateCompany(companyId), userWithCompanyEntity);
}
public void deleteCompany(UserEntity userEntity, Long companyId) {
@@ -164,12 +183,20 @@ public class CompanyDao {
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();
return list.stream().map(companyEntity->{
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyEntity.getId());
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
}).toList();
}
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
return userWithCompanyRepository.findByUserIdAndCompanyId(userId, companyId).orElseThrow(() -> new CustomValidationException(Status.UNAUTHORIZED,
Translator.toLocale(GepafinConstant.UNAUTHORIZED)));
}
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {
return userWithCompanyRepository.findByUserIdAndCompanyId(userId, compnayId).orElseThrow(
() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_COMPANY_RELATION_NOT_FOUND)));
}
}

View File

@@ -0,0 +1,256 @@
package net.gepafin.tendermanagement.dao;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.DocumentEntity;
import net.gepafin.tendermanagement.entities.UserCompanyDelegationEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.UserCompanyDelegationStatusEnum;
import net.gepafin.tendermanagement.model.request.CompanyDelegationRequest;
import net.gepafin.tendermanagement.model.response.CompanyDelegationResponse;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.repositories.DocumentRepository;
import net.gepafin.tendermanagement.repositories.UserCompanyDelegationRepository;
import net.gepafin.tendermanagement.service.AmazonS3Service;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
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 DelegationDao {
private static final String DEFAULT_PLACEHOLDER = "____________________";
@Autowired
private UserService userService;
@Autowired
private CompanyDao companyDao;
@Autowired
private AmazonS3Service amazonS3Service;
@Autowired
private DocumentRepository documentRepository;
@Value("${aws.s3.url.folder.delegation}")
private String s3Folder;
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
public ByteArrayOutputStream generateDocument(Map<String, String> placeholders, String templateName) {
try {
InputStream templateStream = amazonS3Service.getFile(s3Folder ,templateName);
XWPFDocument doc = loadTemplate(templateStream);
replacePlaceholders(doc, placeholders);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
doc.write(byteArrayOutputStream);
return byteArrayOutputStream;
} catch (Exception e) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.DELEGATION_TEMPLATE_GENERATION_ERROR));
}
}
public void replacePlaceholders(XWPFDocument doc, Map<String, String> placeholders) {
doc.getParagraphs().forEach(paragraph -> {
placeholders.forEach((placeholder, value) -> {
if (paragraph.getText().contains(placeholder)) {
String updatedText = paragraph.getText().replace(placeholder, value);
paragraph.getRuns().forEach(run -> run.setText("", 0)); // Clear the existing text
paragraph.createRun().setText(updatedText); // Insert updated text
}
});
});
}
public XWPFDocument loadTemplate(InputStream templateStream) throws IOException {
return new XWPFDocument(templateStream);
}
public ByteArrayOutputStream downloadCompanyDelegation(UserEntity userEntity, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
Map<String, String> placeholders = getDefaultPlaceholders();
UserResponseBean user = userService.getUserById(userEntity.getId());
CompanyEntity companyEntity = companyDao.validateCompany(companyId);
companyDao.getUserWithCompany(userEntity.getId(), companyId);
updatePlaceholdersForDelegation(user, companyEntity, placeholders, companyDelegationRequest);
DocumentEntity documentEntity = documentRepository.findBySource(GepafinConstant.DELEGATION_TEMPLATE).get(0);
return generateDocument(placeholders, documentEntity.getFileName());
}
private Map<String, String> updatePlaceholdersForDelegation(UserResponseBean user, CompanyEntity companyEntity,
Map<String, String> placeholders, CompanyDelegationRequest companyDelegationRequest) {
validateMandatoryFields(companyDelegationRequest);
addIfNotEmpty(placeholders, "{{company_first_name}}", companyDelegationRequest.getFirstName());
addIfNotEmpty(placeholders, "{{company_last_name}}", companyDelegationRequest.getLastName());
addIfNotEmpty(placeholders, "{{company_codice_fiscale}}", companyDelegationRequest.getCodiceFiscale());
addIfNotEmpty(placeholders, "{{company_name}}", companyEntity.getCompanyName());
addIfNotEmpty(placeholders, "{{company_city}}", companyEntity.getCity());
addIfNotEmpty(placeholders, "{{company_address}}", companyEntity.getAddress());
addIfNotEmpty(placeholders, "{{company_province}}", companyEntity.getProvince());
addIfNotEmpty(placeholders, "{{company_cap}}", companyEntity.getCap());
addIfNotEmpty(placeholders, "{{company_vat_number}}", companyEntity.getVatNumber());
addIfNotEmpty(placeholders, "{{user_first_name}}", user.getFirstName());
addIfNotEmpty(placeholders, "{{user_last_name}}", user.getLastName());
addIfNotNull(placeholders, "{{user_date_of_birth}}", user.getDateOfBirth(),
date -> DateTimeUtil.formatLocalDateTime(date, GepafinConstant.YYYY_MM_DD_SLASH));
addIfNotEmpty(placeholders, "{{user_codice_fiscale}}", user.getCodiceFiscale());
return placeholders;
}
private Map<String, String> getDefaultPlaceholders() {
Map<String, String> placeholders = new HashMap<>();
placeholders.put("{{company_first_name}}", "");
placeholders.put("{{company_last_name}}", "");
placeholders.put("{{company_codice_fiscale}}", "");
placeholders.put("{{company_name}}", "");
placeholders.put("{{company_city}}", DEFAULT_PLACEHOLDER);
placeholders.put("{{company_address}}", DEFAULT_PLACEHOLDER);
placeholders.put("{{company_province}}", DEFAULT_PLACEHOLDER);
placeholders.put("{{company_cap}}", DEFAULT_PLACEHOLDER);
placeholders.put("{{company_vat_number}}", "");
placeholders.put("{{user_first_name}}", "");
placeholders.put("{{user_last_name}}", "");
placeholders.put("{{user_date_of_birth}}", DEFAULT_PLACEHOLDER);
placeholders.put("{{user_codice_fiscale}}", "");
return placeholders;
}
private void validateMandatoryFields(CompanyDelegationRequest companyDelegationRequest) {
if (StringUtils.isAllEmpty(companyDelegationRequest.getFirstName())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_MISSING_FIRSTNAME));
}
if (StringUtils.isAllEmpty(companyDelegationRequest.getLastName())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_MISSING_LASTNAME));
}
if (StringUtils.isAllEmpty(companyDelegationRequest.getCodiceFiscale())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_MISSING_CODICEFISCALE));
}
}
private void addIfNotEmpty(Map<String, String> placeholders, String key, String value) {
if (Boolean.FALSE.equals(StringUtils.isAllEmpty(value))) {
placeholders.put(key, value);
}
}
private <T> void addIfNotNull(Map<String, String> placeholders, String key, T value, Function<T, String> formatter) {
if (value != null) {
placeholders.put(key, formatter.apply(value));
}
}
public CompanyDelegationResponse uploadCompanyDelegation(UserEntity userEntity, Long companyId, MultipartFile file) {
companyDao.validateCompany(companyId);
companyDao.getUserWithCompany(userEntity.getId(), companyId);
validateFileType(file);
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndCompanyIdAndStatus(userEntity.getId(), companyId,
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
if (userCompanyDelegationEntity != null) {
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.INACTIVE.getValue());
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
}
UploadFileOnAmazonS3 uploadFileOnAmazonS3 = uploadFileOnAmazonS3(file);
userCompanyDelegationEntity = new UserCompanyDelegationEntity();
userCompanyDelegationEntity.setCompanyId(companyId);
userCompanyDelegationEntity.setUserId(userEntity.getId());
if (userEntity.getBeneficiary() != null) {
userCompanyDelegationEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.ACTIVE.getValue());
userCompanyDelegationEntity.setFileName(uploadFileOnAmazonS3.fileName());
userCompanyDelegationEntity.setFilePath(uploadFileOnAmazonS3.filepath());
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
return convertUserCompanyDelegationToCompanyDelegationResponse(userCompanyDelegationEntity);
}
private CompanyDelegationResponse convertUserCompanyDelegationToCompanyDelegationResponse(
UserCompanyDelegationEntity userCompanyDelegationEntity) {
return Utils.convertSourceObjectToDestinationObject(userCompanyDelegationEntity, CompanyDelegationResponse.class);
}
private UploadFileOnAmazonS3 uploadFileOnAmazonS3(MultipartFile file){
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String fileName = org.springframework.util.StringUtils.cleanPath(file.getOriginalFilename());
String firstNameContain = fileName.substring(0, fileName.lastIndexOf('.'));
firstNameContain+=Utils.randomKey(5);
fileName = (firstNameContain + "." + extension);
try {
String filepath = amazonS3Service.upload(fileName, s3Folder, file);
return new UploadFileOnAmazonS3(fileName, filepath);
} catch (Exception e) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
}
}
private record UploadFileOnAmazonS3(String fileName, String filepath) {
}
private void validateFileType(MultipartFile file) {
if (file.isEmpty()) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_EMPTY));
}
String filename = file.getOriginalFilename();
if (filename == null || !filename.endsWith(".p7m")) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_INVALIDTYPE));
}
}
public CompanyDelegationResponse getCompanyDelegation(UserEntity userEntity, Long companyId) {
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndCompanyIdAndStatus(userEntity.getId(), companyId,
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
companyDao.getUserWithCompany(userEntity.getId(), companyId);
if(userCompanyDelegationEntity == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DELEGATION_NOT_FOUND));
}
return convertUserCompanyDelegationToCompanyDelegationResponse(userCompanyDelegationEntity);
}
public void deleteCompanyDelegation(UserEntity userEntity, Long companyId) {
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndCompanyIdAndStatus(userEntity.getId(), companyId,
UserCompanyDelegationStatusEnum.ACTIVE.getValue());
companyDao.getUserWithCompany(userEntity.getId(), companyId);
if(userCompanyDelegationEntity == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.DELEGATION_NOT_FOUND));
}
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.INACTIVE.getValue());
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
}
}

View File

@@ -6,6 +6,7 @@ import java.util.stream.Collectors;
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
@@ -40,6 +41,9 @@ public class DocumentDao {
@Autowired
private CallService callService;
@Value("${aws.s3.url.folder}")
private String s3Folder;
public List<DocumentResponseBean> uploadFiles(List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
List<DocumentEntity> documentEntities = new ArrayList<>();
@@ -81,7 +85,7 @@ public class DocumentDao {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
String firstNameContain = fileName.substring(0, fileName.lastIndexOf('.'));
fileName = (firstNameContain + "." + extension);
String filepath = amazonS3Service.upload(fileName, file);
String filepath = amazonS3Service.upload(fileName, s3Folder, file);
uploadFileOnAmazonS3 result = new uploadFileOnAmazonS3(fileName, filepath);
return result;
}
@@ -99,7 +103,7 @@ public class DocumentDao {
private DocumentEntity deleteFileOnAmazonS3(String fileName) {
try {
amazonS3Service.delete(fileName);
amazonS3Service.delete(s3Folder, fileName);
} catch (Exception e) {
}
return null;

View File

@@ -83,6 +83,12 @@ public class UserDao {
beneficiaryEntity.setLastName(userReq.getLastName());
beneficiaryEntity.setOrganization(userReq.getOrganization());
beneficiaryEntity.setPhoneNumber(userReq.getPhoneNumber());
beneficiaryEntity.setPrivacy(userReq.getPrivacy());
beneficiaryEntity.setTerms(userReq.getTerms());
beneficiaryEntity.setOffers(userReq.getOffers());
beneficiaryEntity.setMarketing(userReq.getMarketing());
beneficiaryEntity.setThirdParty(userReq.getThirdParty());
beneficiaryEntity.setEmailPec(userReq.getEmailPec());
beneficiaryEntity =beneficiaryRepository.save(beneficiaryEntity);
}
return beneficiaryEntity;
@@ -148,10 +154,16 @@ public class UserDao {
setIfUpdated(userEntity::getOrganization, userEntity::setOrganization, userReq.getOrganization());
setIfUpdated(userEntity::getAddress, userEntity::setAddress, userReq.getAddress());
setIfUpdated(userEntity::getPhoneNumber, userEntity::setPhoneNumber, userReq.getPhoneNumber());
setIfUpdated(userEntity::getDateOfBirth, userEntity::setDateOfBirth, userReq.getDateOfBirth());
setIfUpdated(userEntity.getBeneficiary()::getCodiceFiscale, userEntity.getBeneficiary()::setCodiceFiscale, userReq.getCodiceFiscale());
setIfUpdated(userEntity.getBeneficiary()::getMarketing, userEntity.getBeneficiary()::setMarketing, userReq.getMarketing());
setIfUpdated(userEntity.getBeneficiary()::getOffers, userEntity.getBeneficiary()::setOffers, userReq.getOffers());
setIfUpdated(userEntity.getBeneficiary()::getThirdParty, userEntity.getBeneficiary()::setThirdParty, userReq.getThirdParty());
if (userReq.getRoleId() != null) {
RoleEntity roleEntity = roleDao.validateRole(userReq.getRoleId());
setIfUpdated(userEntity::getRoleEntity, userEntity::setRoleEntity, roleEntity);
}
setIfUpdated(userEntity.getBeneficiary()::getEmailPec, userEntity.getBeneficiary()::setEmailPec, userReq.getEmailPec());
userEntity = userRepository.save(userEntity);
log.info("User updated with ID: {}", userEntity.getId());
return convertUserEntityToUserResponse(userEntity);
@@ -167,6 +179,7 @@ public class UserDao {
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());
@@ -216,6 +229,12 @@ public class UserDao {
userResponseBean.setCountry(userEntity.getBeneficiary().getCountry());
userResponseBean.setCodiceFiscale(userEntity.getBeneficiary().getCodiceFiscale());
userResponseBean.setDateOfBirth(userEntity.getBeneficiary().getDateOfBirth());
userResponseBean.setPrivacy(userEntity.getBeneficiary().getPrivacy());
userResponseBean.setTerms(userEntity.getBeneficiary().getTerms());
userResponseBean.setOffers(userEntity.getBeneficiary().getOffers());
userResponseBean.setMarketing(userEntity.getBeneficiary().getMarketing());
userResponseBean.setThirdParty(userEntity.getBeneficiary().getThirdParty());
userResponseBean.setEmailPec(userEntity.getBeneficiary().getEmailPec());
}
return userResponseBean;
}

View File

@@ -37,11 +37,28 @@ public class BeneficiaryEntity extends BaseEntity {
@Column(name = "COUNTRY")
private String country;
@Column(name = "CODICE_FISCALE")
private String codiceFiscale;
@Column(name = "DATE_OF_BIRTH")
private LocalDateTime dateOfBirth;
@Column(name = "PRIVACY")
private Boolean privacy;
@Column(name = "TERMS")
private Boolean terms;
@Column(name = "MARKETING")
private Boolean marketing;
@Column(name = "OFFERS")
private Boolean offers;
@Column(name = "THIRD_PARTY")
private Boolean thirdParty;
@Column(name = "EMAIL_PEC")
private String emailPec;
}

View File

@@ -50,4 +50,10 @@ public class CompanyEntity extends BaseEntity{
@Column(name = "ANNUAL_REVENUE")
private BigDecimal annualRevenue;
@Column(name = "CONTACT_NAME")
private String contactName;
@Column(name = "CONTACT_EMAIL")
private String contactEmail;
}

View File

@@ -0,0 +1,31 @@
package net.gepafin.tendermanagement.entities;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.Data;
@Data
@Entity
@Table(name = "user_company_delegation")
public class UserCompanyDelegationEntity extends BaseEntity{
@Column(name="USER_ID")
private Long userId;
@Column(name="COMPANY_ID")
private Long companyId;
@Column(name = "BENEFICIARY_ID")
private Long beneficiaryId;
@Column(name = "FILE_NAME")
private String fileName;
@Column(name = "FILE_PATH")
private String filePath;
@Column(name="STATUS")
private String status;
}

View File

@@ -18,5 +18,8 @@ public class UserWithCompanyEntity extends BaseEntity{
@Column(name = "COMPANY_ID")
Long companyId;
@Column(name = "IS_LEGAL_REPRESENTANT")
private Boolean isLegalRepresentant;
}

View File

@@ -0,0 +1,18 @@
package net.gepafin.tendermanagement.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum UserCompanyDelegationStatusEnum {
ACTIVE("ACTIVE"), INACTIVE("INACTIVE");
private String value;
UserCompanyDelegationStatusEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}

View File

@@ -0,0 +1,13 @@
package net.gepafin.tendermanagement.model.request;
import lombok.Data;
@Data
public class CompanyDelegationRequest {
private String firstName;
private String lastName;
private String codiceFiscale;
}

View File

@@ -20,5 +20,7 @@ public class CompanyRequest {
private String email;
private String numberOfEmployees;
private BigDecimal annualRevenue;
private Boolean isLegalRepresentant;
private String contactName;
private String contactEmail;
}

View File

@@ -4,6 +4,8 @@ import lombok.Getter;
import lombok.Setter;
import net.gepafin.tendermanagement.enums.UserStatusEnum;
import java.time.LocalDateTime;
@Getter
@Setter
public class UpdateUserReq {
@@ -17,4 +19,11 @@ public class UpdateUserReq {
private String city;
private UserStatusEnum status;
private String country;
private String codiceFiscale;
private LocalDateTime dateOfBirth;
private Boolean marketing;
private Boolean offers;
private Boolean thirdParty;
private String emailPec;
}

View File

@@ -31,5 +31,12 @@ public class UserReq {
private String codiceFiscale;
private LocalDateTime dateOfBirth;
private Boolean privacy;
private Boolean terms;
private Boolean marketing;
private Boolean offers;
private Boolean thirdParty;
private String emailPec;
}

View File

@@ -0,0 +1,15 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Data;
import net.gepafin.tendermanagement.entities.BaseEntity;
import net.gepafin.tendermanagement.enums.UserCompanyDelegationStatusEnum;
@Data
public class CompanyDelegationResponse extends BaseEntity{
private Long userId;
private Long companyId;
private Long beneficiaryId;
private String fileName;
private String filePath;
private UserCompanyDelegationStatusEnum status;
}

View File

@@ -21,5 +21,7 @@ public class CompanyResponse extends BaseBean{
private String email;
private String numberOfEmployees;
private BigDecimal annualRevenue;
private Boolean isLegalRepresentant;
private String contactName;
private String contactEmail;
}

View File

@@ -41,6 +41,18 @@ public class LoginResponse {
private LocalDateTime dateOfBirth;
private Boolean privacy;
private Boolean terms;
private Boolean marketing;
private Boolean offers;
private Boolean thirdParty;
private String emailPec;
private LocalDateTime createdDate;
private LocalDateTime updatedDate;

View File

@@ -39,4 +39,12 @@ public class UserResponseBean extends BaseBean {
private LocalDateTime dateOfBirth;
private List<CompanyResponse> companies;
private Boolean privacy;
private Boolean terms;
private Boolean marketing;
private Boolean offers;
private Boolean thirdParty;
private String emailPec;
}

View File

@@ -19,5 +19,7 @@ public interface DocumentRepository extends JpaRepository<DocumentEntity, Long>
Optional<DocumentEntity> findByIdAndSourceIdAndIsDeletedFalse(Long id, Long sourceId);
List<DocumentEntity> findBySource(String source);
}

View File

@@ -0,0 +1,10 @@
package net.gepafin.tendermanagement.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import net.gepafin.tendermanagement.entities.UserCompanyDelegationEntity;
public interface UserCompanyDelegationRepository extends JpaRepository<UserCompanyDelegationEntity, Long> {
UserCompanyDelegationEntity findByUserIdAndCompanyIdAndStatus(Long userId, Long companyId, String status);
}

View File

@@ -9,9 +9,9 @@ import java.io.InputStream;
@Component
public interface AmazonS3Service {
public String upload(String fileName, MultipartFile file) throws IOException;
public String upload(String fileName, String s3Folder, MultipartFile file) throws IOException;
public Boolean delete(String fileName);
public Boolean delete(String s3Folder, String fileName);
InputStream getFile(String filePath) throws IOException;
InputStream getFile(String s3Folder, String filePath) throws IOException;
}

View File

@@ -1,12 +1,17 @@
package net.gepafin.tendermanagement.service;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
import net.gepafin.tendermanagement.model.request.CompanyDelegationRequest;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyDelegationResponse;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
public interface CompanyService {
@@ -27,4 +32,12 @@ public interface CompanyService {
UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId);
ByteArrayOutputStream downloadCompanyDelegation(HttpServletRequest request, Long companyId, CompanyDelegationRequest companyDelegationRequest);
CompanyDelegationResponse uploadCompanyDelegation(HttpServletRequest request, Long companyId, MultipartFile file);
CompanyDelegationResponse getCompanyDelegation(HttpServletRequest request, Long companyId);
void deleteCompanyDelegation(HttpServletRequest request, Long companyId);
}

View File

@@ -29,18 +29,16 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
@Value("${aws.s3.bucket.name}")
private String bucketName;
@Value("${aws.s3.url.folder}")
private String s3Folder;
@Value("${aws.s3.url}")
private String s3Url;
@Override
public String upload(String fileName,
public String upload(String fileName, String s3Folder,
MultipartFile file) throws IOException {
String path = bucketName+"/"+s3Folder;
// String path = bucketName+"/"+s3Folder;
String path = s3Folder +"/"+fileName;
InputStream inputStream = file.getInputStream();
@@ -57,15 +55,15 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
});
if(Boolean.FALSE.equals(isTestProfileActivated())) {
amazonS3.putObject(path, fileName, inputStream, objectMetadata);
amazonS3.putObject(bucketName, path, inputStream, objectMetadata);
}
return s3Url + s3Folder +"/"+ fileName;
}
@Override
public Boolean delete(String fileName) {
final DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, fileName);
public Boolean delete(String s3Folder, String fileName) {
String path = s3Folder +"/"+fileName;
final DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, path);
if(Boolean.FALSE.equals(isTestProfileActivated())) {
amazonS3.deleteObject(deleteObjectRequest);
}
@@ -78,10 +76,10 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
}
@Override
public InputStream getFile(String filePath) throws IOException {
public InputStream getFile(String s3Folder, String filePath) throws IOException {
try {
String path = bucketName+ s3Folder +"/";
GetObjectRequest getObjectRequest = new GetObjectRequest(path, filePath);
String path = s3Folder +"/"+filePath;
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
S3Object s3Object = amazonS3.getObject(getObjectRequest);
return s3Object.getObjectContent();
} catch (AmazonS3Exception e) {

View File

@@ -125,6 +125,12 @@ public class AuthenticationService {
loginResponse.setCity(user.getBeneficiary().getCity());
loginResponse.setCodiceFiscale(user.getBeneficiary().getCodiceFiscale());
loginResponse.setDateOfBirth(user.getBeneficiary().getDateOfBirth());
loginResponse.setPrivacy(user.getBeneficiary().getPrivacy());
loginResponse.setMarketing(user.getBeneficiary().getMarketing());
loginResponse.setOffers(user.getBeneficiary().getOffers());
loginResponse.setTerms(user.getBeneficiary().getTerms());
loginResponse.setThirdParty(user.getBeneficiary().getThirdParty());
loginResponse.setEmailPec(user.getBeneficiary().getEmailPec());
}
return loginResponse;
@@ -153,7 +159,7 @@ public class AuthenticationService {
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscale(cf)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
samlResponseLogRepository.delete(samlResponseLogEntity);
//samlResponseLogRepository.delete(samlResponseLogEntity);
return getJWTTokenBean(userEntity, Boolean.TRUE);
}

View File

@@ -1,19 +1,24 @@
package net.gepafin.tendermanagement.service.impl;
import java.io.ByteArrayOutputStream;
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 org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.CompanyDao;
import net.gepafin.tendermanagement.dao.DelegationDao;
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.CompanyDelegationRequest;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyDelegationResponse;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.util.Validator;
@@ -30,6 +35,9 @@ public class CompanyServiceImpl implements CompanyService {
@Autowired
private VatCheckDao vatCheckDao;
@Autowired
private DelegationDao delegationDao;
@Override
@Transactional(rollbackFor = Exception.class)
public CompanyResponse createCompany(HttpServletRequest request, CompanyRequest companyRequest) {
@@ -61,7 +69,7 @@ public class CompanyServiceImpl implements CompanyService {
@Override
@Transactional(readOnly = true)
public List<CompanyResponse> getCompanyByUserId(HttpServletRequest request, Long userId) {
UserEntity userEntity = validator.validateUser(request);
validator.validateUser(request);
return companyDao.getCompanyByUserId(userId);
}
@@ -80,4 +88,30 @@ public class CompanyServiceImpl implements CompanyService {
return companyDao.validateUserWithCompny(userId, companyId);
}
@Override
@Transactional(readOnly = true)
public ByteArrayOutputStream downloadCompanyDelegation(HttpServletRequest request, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
UserEntity userEntity =validator.validateUser(request);
return delegationDao.downloadCompanyDelegation(userEntity, companyId, companyDelegationRequest);
}
@Override
@Transactional(rollbackFor = Exception.class)
public CompanyDelegationResponse uploadCompanyDelegation(HttpServletRequest request, Long companyId, MultipartFile file) {
UserEntity userEntity =validator.validateUser(request);
return delegationDao.uploadCompanyDelegation(userEntity, companyId, file);
}
@Override
@Transactional(readOnly = true)
public CompanyDelegationResponse getCompanyDelegation(HttpServletRequest request, Long companyId) {
UserEntity userEntity =validator.validateUser(request);
return delegationDao.getCompanyDelegation(userEntity, companyId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteCompanyDelegation(HttpServletRequest request, Long companyId) {
UserEntity userEntity =validator.validateUser(request);
delegationDao.deleteCompanyDelegation(userEntity, companyId);
}
}

View File

@@ -1,13 +1,9 @@
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;
@@ -86,4 +82,14 @@ public class DateTimeUtil {
// If all parsing attempts fail, throw an exception
throw new CustomValidationException(Status.BAD_REQUEST,"Failed to parse time: " + timeString);
}
public static String formatLocalDateTime(LocalDateTime dateTime, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return dateTime.format(formatter);
}
public static LocalDateTime parseStringToLocalDateTime(String dateTimeStr, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.parse(dateTimeStr, formatter);
}
}

View File

@@ -227,6 +227,12 @@ public class Utils {
Pattern pattern = Pattern.compile(EMAIL_REGEX);
return pattern.matcher(email).matches();
}
public static String randomKey(Integer range) {
String data = String.valueOf(System.currentTimeMillis());
return data.substring(data.length() - range);
}
public static String convertObjectToJsonString(Object object) {
try {
// Check if the object is a string

View File

@@ -37,8 +37,7 @@ public class Validator {
}
public UserEntity validateUser(HttpServletRequest request) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
return userService.validateUser(Long.parseLong(userInfo.get("userId").toString()));
return userService.validateUser(getUserIdFromToken(request));
}
public Boolean checkIsSuperAdmin() {
@@ -86,5 +85,18 @@ public class Validator {
}
return false;
}
public UserEntity validateUserId(HttpServletRequest request, Long userId) {
UserEntity user = validateUser(request);
if(user.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue()) && Boolean.FALSE.equals(user.getId().equals(userId))) {
throw new UnauthorizedAccessException(Status.UNAUTHORIZED, Translator.toLocale(GepafinConstant.INVALID_REQUEST));
}
return userService.validateUser(userId);
}
private Long getUserIdFromToken(HttpServletRequest request) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
return Long.parseLong(userInfo.get("userId").toString());
}
}

View File

@@ -12,6 +12,7 @@ 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 org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -19,7 +20,9 @@ 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.CompanyDelegationRequest;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyDelegationResponse;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
@@ -81,7 +84,7 @@ public interface CompanyApi {
@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);
@Parameter(description = "The user 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 = {
@@ -93,5 +96,51 @@ public interface CompanyApi {
@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);
@Operation(summary = "Api to download company delegation template", 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 = "{companyId}/delegation/download", produces = { "application/json" })
ResponseEntity<byte[]> downloadCompanyDelegation(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId,
@Parameter(description = "Company delegation request object", required = true) @RequestBody CompanyDelegationRequest companyDelegationRequest);
@Operation(summary = "Api to upload company delegation (only p7m file format is supported)", 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 = "{companyId}/delegation/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<Response<CompanyDelegationResponse>> uploadCompanyDelegation(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId,
@Parameter(description = "The company delegation", required = true) @RequestParam("file") MultipartFile file);
@Operation(summary = "Api to get company delegation", 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}/delegation", produces = { "application/json" })
ResponseEntity<Response<CompanyDelegationResponse>> getCompanyDelegation(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId);
@Operation(summary = "Api to delete company delegation", 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}/delegation", produces = { "application/json" })
ResponseEntity<Response<Void>> deleteCompanyDelegation(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable("companyId") Long companyId);
}

View File

@@ -1,20 +1,26 @@
package net.gepafin.tendermanagement.web.rest.api.impl;
import java.io.ByteArrayOutputStream;
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.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.model.request.CompanyDelegationRequest;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyDelegationResponse;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.service.CompanyService;
@@ -86,4 +92,40 @@ public class CompanyApiController implements CompanyApi{
.body(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.CHECK_VATNUMBER_SUCCESS_MSG)));
}
@Override
public ResponseEntity<byte[]> downloadCompanyDelegation(HttpServletRequest request, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
log.info("download company delegation with companyId: {}", companyId);
ByteArrayOutputStream data = companyService.downloadCompanyDelegation(request, companyId, companyDelegationRequest);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "delegation-template.docx");
return new ResponseEntity<>(data.toByteArray(), headers, HttpStatus.OK);
}
@Override
public ResponseEntity<Response<CompanyDelegationResponse>> uploadCompanyDelegation(HttpServletRequest request, Long companyId,
MultipartFile file) {
log.info("upload company delegation with companyId: {}", companyId);
CompanyDelegationResponse companyDelegationResponse = companyService.uploadCompanyDelegation(request, companyId, file);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(companyDelegationResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.DELEGATION_FILE_UPLOAD_SUCCESS)));
}
@Override
public ResponseEntity<Response<CompanyDelegationResponse>> getCompanyDelegation(HttpServletRequest request,
Long companyId) {
log.info("get company delegation with companyId: {}", companyId);
CompanyDelegationResponse companyDelegationResponse = companyService.getCompanyDelegation(request, companyId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(companyDelegationResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.DELEGATION_FETCH_SUCCESS)));
}
@Override
public ResponseEntity<Response<Void>> deleteCompanyDelegation(HttpServletRequest request,
Long companyId) {
log.info("delete company delegation with companyId: {}", companyId);
companyService.deleteCompanyDelegation(request, companyId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.DELEGATION_DELETE_SUCCESS)));
}
}