661 lines
30 KiB
Java
661 lines
30 KiB
Java
package net.gepafin.tendermanagement.dao;
|
|
|
|
import org.springframework.data.domain.Pageable; // Correct package
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import lombok.extern.log4j.Log4j2;
|
|
import net.gepafin.tendermanagement.entities.*;
|
|
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
|
|
import net.gepafin.tendermanagement.enums.UserCompanyDelegationStatusEnum;
|
|
import net.gepafin.tendermanagement.model.request.LimitRequest;
|
|
import net.gepafin.tendermanagement.model.response.VatCheckResponseBean;
|
|
import net.gepafin.tendermanagement.repositories.*;
|
|
import net.gepafin.tendermanagement.service.CompanyService;
|
|
import net.gepafin.tendermanagement.enums.VersionActionTypeEnum;
|
|
import net.gepafin.tendermanagement.model.request.VersionHistoryRequest;
|
|
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
|
import net.gepafin.tendermanagement.repositories.FaqRepository;
|
|
import net.gepafin.tendermanagement.util.LoggingUtil;
|
|
import net.gepafin.tendermanagement.web.rest.api.errors.*;
|
|
import org.apache.commons.lang3.StringUtils;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.data.domain.Page;
|
|
import org.springframework.data.domain.PageRequest;
|
|
import org.springframework.data.domain.Sort;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
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.service.UserService;
|
|
import net.gepafin.tendermanagement.util.Utils;
|
|
|
|
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
|
|
|
|
@Component
|
|
@Log4j2
|
|
public class CompanyDao {
|
|
|
|
@Autowired
|
|
private CompanyRepository companyRepository;
|
|
|
|
@Autowired
|
|
private UserService userService;
|
|
|
|
@Autowired
|
|
private UserWithCompanyRepository userWithCompanyRepository;
|
|
@Autowired
|
|
private ApplicationRepository applicationRepository;
|
|
@Autowired
|
|
private FaqRepository faqRepository;
|
|
|
|
@Autowired
|
|
private BeneficiaryPreferredCallRepository beneficiaryPreferredCallRepository;
|
|
|
|
@Autowired
|
|
private UserCompanyDelegationRepository userCompanyDelegationRepository;
|
|
|
|
@Autowired
|
|
private CompanyService companyService;
|
|
|
|
@Autowired
|
|
private LoggingUtil loggingUtil;
|
|
|
|
@Autowired
|
|
private HttpServletRequest request;
|
|
|
|
|
|
private static final String NOT_FOUND_JSON = "{\"data\": \"not found\"}";
|
|
|
|
public CompanyResponse createCompany(UserEntity userEntity, CompanyRequest companyRequest) {
|
|
|
|
log.info("Initiating company creation by userId: {}", userEntity.getId());
|
|
CompanyEntity existingCompany = companyRepository.findByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId());
|
|
UserWithCompanyEntity userWithCompanyEntity = null;
|
|
if (existingCompany != null) {
|
|
UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), existingCompany.getId()).orElse(null);
|
|
if (existingRelation == null) {
|
|
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, existingCompany, companyRequest.getIsLegalRepresentant(),companyRequest);
|
|
|
|
/** This code is responsible for adding a version history log for "adding user with company" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(userWithCompanyEntity).build());
|
|
} else {
|
|
log.warn("User already connected to company. userId: {}, companyId: {}", userEntity.getId(), existingCompany.getId());
|
|
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.USER_ALREADY_CONNECTED_TO_COMPANY));
|
|
}
|
|
return convertCompanyEntityToCompanyResponse(existingCompany, userWithCompanyEntity);
|
|
} else {
|
|
validateCompany(userEntity, companyRequest);
|
|
CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(userEntity, companyRequest);
|
|
CompanyEntity companyData = companyRepository.save(companyEntity);
|
|
|
|
/** This code is responsible for adding a version history log for "creating company" operation. **/
|
|
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(companyData).build());
|
|
|
|
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, companyEntity, companyRequest.getIsLegalRepresentant(),companyRequest);
|
|
|
|
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
|
|
}
|
|
}
|
|
|
|
|
|
private void validateCompany(UserEntity userEntity, 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.existsByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId())) {
|
|
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
|
Translator.toLocale(GepafinConstant.VATNUMBER_ALREADY_EXISTS));
|
|
}
|
|
}
|
|
|
|
private UserWithCompanyEntity createUserWithCompanyRelation(UserEntity userEntity, CompanyEntity companyEntity, Boolean isLegalRepresentant,CompanyRequest companyRequest) {
|
|
|
|
log.info("Creating user-company relation. userId: {}, companyId: {}, isLegalRep: {}", userEntity.getId(), companyEntity.getId(), isLegalRepresentant);
|
|
UserWithCompanyEntity userWithCompanyEntity = new UserWithCompanyEntity();
|
|
if (userEntity.getBeneficiary() != null) {
|
|
userWithCompanyEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
|
|
}
|
|
userWithCompanyEntity.setIsDeleted(Boolean.FALSE);
|
|
userWithCompanyEntity.setCompanyId(companyEntity.getId());
|
|
userWithCompanyEntity.setUserId(userEntity.getId());
|
|
userWithCompanyEntity.setIsLegalRepresentant(isLegalRepresentant);
|
|
userWithCompanyEntity.setEmail(companyRequest.getEmail());
|
|
userWithCompanyEntity.setPec(companyRequest.getPec());
|
|
userWithCompanyEntity.setContactName(companyRequest.getContactName());
|
|
userWithCompanyEntity.setContactEmail(companyRequest.getContactEmail());
|
|
UserWithCompanyEntity userWithCompany = userWithCompanyRepository.save(userWithCompanyEntity);
|
|
/** This code is responsible for adding a version history log for the "adding user with company" operation. **/
|
|
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(null).newData(userWithCompany).build());
|
|
if (StringUtils.isEmpty(companyEntity.getJson())) {
|
|
companyEntity.setJson(Utils.convertMapIntoJsonString(companyRequest.getVatCheckResponse()));
|
|
updateCodiceAtecoFieldWithNewJson(companyEntity);
|
|
companyEntity = companyRepository.save(companyEntity);
|
|
log.info("Updated company JSON field and saved. companyId: {}", companyEntity.getId());
|
|
|
|
/** This code is responsible for adding a version history log for "updating company json field" operation. **/
|
|
loggingUtil.addVersionHistory(VersionHistoryRequest.builder()
|
|
.request(request)
|
|
.actionType(VersionActionTypeEnum.INSERT)
|
|
.oldData(null)
|
|
.newData(companyEntity)
|
|
.build());
|
|
}
|
|
|
|
return userWithCompany;
|
|
}
|
|
|
|
private CompanyEntity convertCompanyRequestToCompanyEntity(UserEntity userEntity, 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.setNumberOfEmployees(request.getNumberOfEmployees());
|
|
entity.setAnnualRevenue(request.getAnnualRevenue());
|
|
entity.setHub(userEntity.getHub());
|
|
entity.setJson(Utils.convertMapIntoJsonString(request.getVatCheckResponse()));
|
|
updateCodiceAtecoFieldWithNewJson(entity);
|
|
|
|
return entity;
|
|
}
|
|
|
|
private CompanyResponse convertCompanyEntityToCompanyResponse(CompanyEntity entity, UserWithCompanyEntity userWithCompanyEntity) {
|
|
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(userWithCompanyEntity.getPec());
|
|
response.setEmail(userWithCompanyEntity.getEmail());
|
|
response.setNumberOfEmployees(entity.getNumberOfEmployees());
|
|
response.setAnnualRevenue(entity.getAnnualRevenue());
|
|
if(userWithCompanyEntity!=null) {
|
|
response.setIsLegalRepresentant(userWithCompanyEntity.getIsLegalRepresentant());
|
|
response.setCodiceAteco(entity.getCodiceAteco());
|
|
}
|
|
response.setCreatedDate(entity.getCreatedDate());
|
|
response.setUpdatedDate(entity.getUpdatedDate());
|
|
response.setContactName(userWithCompanyEntity.getContactName());
|
|
response.setContactEmail(userWithCompanyEntity.getContactEmail());
|
|
return response;
|
|
}
|
|
|
|
public CompanyResponse updateCompany(UserEntity userEntity, Long companyId, CompanyRequest companyRequest) {
|
|
|
|
log.info("Updating company. companyId: {}, userId: {}", companyId, userEntity.getId());
|
|
CompanyEntity companyEntity = validateCompany(companyId);
|
|
//cloned entity for old data
|
|
CompanyEntity oldCompanyData = Utils.getClonedEntityForData(companyEntity);
|
|
|
|
setIfUpdated(companyEntity::getCompanyName, companyEntity::setCompanyName, companyRequest.getCompanyName());
|
|
setIfUpdated(companyEntity::getCodiceFiscale, companyEntity::setCodiceFiscale, companyRequest.getCodiceFiscale());
|
|
setIfUpdated(companyEntity::getAddress, companyEntity::setAddress, companyRequest.getAddress());
|
|
setIfUpdated(companyEntity::getPhoneNumber, companyEntity::setPhoneNumber, companyRequest.getPhoneNumber());
|
|
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::getNumberOfEmployees, companyEntity::setNumberOfEmployees, companyRequest.getNumberOfEmployees());
|
|
setIfUpdated(companyEntity::getAnnualRevenue, companyEntity::setAnnualRevenue, companyRequest.getAnnualRevenue());
|
|
//
|
|
// if(StringUtils.isNotBlank(companyRequest.getVatNumber())) {
|
|
// CompanyEntity existingCompany = companyRepository.findByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId());
|
|
// if(existingCompany!=null){
|
|
// throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.VATNUMBER_ALREADY_EXISTS));
|
|
// }
|
|
// companyEntity.setVatNumber(companyRequest.getVatNumber());
|
|
//
|
|
// }
|
|
companyRepository.save(companyEntity);
|
|
log.info("Company updated and saved. companyId: {}", companyEntity.getId());
|
|
|
|
/** This code is responsible for adding a version history log for the "Update company" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldCompanyData).newData(companyEntity).build());
|
|
|
|
log.info("Logged version history for company update. companyId: {}", companyEntity.getId());
|
|
|
|
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
|
|
//cloned entity for old data
|
|
UserWithCompanyEntity oldUserWithCompanyData = Utils.getClonedEntityForData(userWithCompanyEntity);
|
|
// if(StringUtils.isNotBlank(companyRequest.getVatNumber())) {
|
|
// String responseJson = companyRequest.getVatCheckResponse() != null ? Utils.convertMapIntoJsonString(companyRequest.getVatCheckResponse()) : null;
|
|
// setIfUpdated(companyEntity::getJson, companyEntity::setJson, responseJson);
|
|
// }
|
|
setIfUpdated(userWithCompanyEntity::getPec, userWithCompanyEntity::setPec, companyRequest.getPec());
|
|
setIfUpdated(userWithCompanyEntity::getEmail, userWithCompanyEntity::setEmail, companyRequest.getEmail());
|
|
setIfUpdated(userWithCompanyEntity::getContactName, userWithCompanyEntity::setContactName, companyRequest.getContactName());
|
|
setIfUpdated(userWithCompanyEntity::getContactEmail, userWithCompanyEntity::setContactEmail, companyRequest.getContactEmail());
|
|
setIfUpdated(userWithCompanyEntity::getIsLegalRepresentant, userWithCompanyEntity::setIsLegalRepresentant, companyRequest.getIsLegalRepresentant());
|
|
userWithCompanyEntity = userWithCompanyRepository.save(userWithCompanyEntity);
|
|
|
|
/** This code is responsible for adding a version history log for the "Update company" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldUserWithCompanyData).newData(userWithCompanyEntity).build());
|
|
|
|
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
|
|
}
|
|
|
|
public CompanyEntity validateCompany(Long companyId) {
|
|
log.info("Validating company. companyId: {}", 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) {
|
|
log.info("Fetching company details. userId: {}, companyId: {}", userEntity.getId(), companyId);
|
|
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
|
|
return convertCompanyEntityToCompanyResponse(validateCompany(companyId), userWithCompanyEntity);
|
|
}
|
|
|
|
public void deleteCompany(UserEntity userEntity, Long companyId) {
|
|
log.info("Deleting company. userId: {}, companyId: {}", userEntity.getId(), companyId);
|
|
CompanyEntity companyEntity = validateCompany(companyId);
|
|
|
|
/** This code is responsible for adding a version history log for the "delete company" operation. **/
|
|
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.DELETE).oldData(companyEntity).newData(null).build());
|
|
|
|
companyRepository.delete(companyEntity);
|
|
|
|
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyId);
|
|
|
|
/** This code is responsible for adding a version history log for the "delete user with company" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.DELETE).oldData(userWithCompanyEntity).newData(null).build());
|
|
|
|
userWithCompanyRepository.deleteByCompanyIdAndIsDeletedFalse(companyId);
|
|
}
|
|
|
|
public List<CompanyResponse> getCompanyByUserId(Long userId) {
|
|
log.info("Fetching companies by userId: {}", userId);
|
|
UserEntity userEntity = userService.validateUser(userId);
|
|
List<Long> activeCompanyIds = userWithCompanyRepository.findActiveCompanyIdsByUserId(userEntity.getId());
|
|
List<CompanyEntity> companies = companyRepository.findByIdInAndHubId(activeCompanyIds, userEntity.getHub().getId());
|
|
return companies.stream().map(companyEntity -> {
|
|
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyEntity.getId());
|
|
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
|
|
}).toList();
|
|
}
|
|
|
|
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
|
|
log.info("Validating user-company access. userId: {}, companyId: {}", userId, companyId);
|
|
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
|
|
Translator.toLocale(GepafinConstant.PERMISSION_DENIED)));
|
|
}
|
|
|
|
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {
|
|
log.info("Fetching user-company relation. userId: {}, companyId: {}", userId, compnayId);
|
|
return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, compnayId).orElseThrow(
|
|
() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_COMPANY_RELATION_NOT_FOUND)));
|
|
}
|
|
public void removeCompanyFromList(UserEntity userEntity, Long companyId) {
|
|
log.info("Initiating removal of company from user list. userId: {}, companyId: {}", userEntity.getId(), companyId);
|
|
CompanyEntity companyEntity = validateCompany(companyId);
|
|
UserWithCompanyEntity existingRelation=companyService.getUserWithCompany(userEntity.getId(),companyEntity.getId());
|
|
List<ApplicationEntity> userApplications = applicationRepository.findByUserWithCompanyIdAndUserIdAndIsDeletedFalse(existingRelation.getId(), userEntity.getId());
|
|
List<FaqEntity> faqs = faqRepository.findByUserWithCompanyIdAndIsDeletedFalse(existingRelation.getId());
|
|
List<BeneficiaryPreferredCallEntity> preferredCallEntities= beneficiaryPreferredCallRepository.findByUserIdAndUserWithCompanyIdAndIsDeletedFalse(userEntity.getId(),existingRelation.getId());
|
|
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository.findByUserIdAndUserWithCompanyIdAndStatus(userEntity.getId(),existingRelation.getId(), UserCompanyDelegationStatusEnum.ACTIVE.getValue());
|
|
List<String> applicationStatusAllowed = List.of(
|
|
ApplicationStatusTypeEnum.DRAFT.getValue(),
|
|
ApplicationStatusTypeEnum.AWAITING.getValue(),
|
|
ApplicationStatusTypeEnum.READY.getValue()
|
|
);
|
|
boolean notAllowedStatus = userApplications.stream()
|
|
.anyMatch(application -> !applicationStatusAllowed.contains(application.getStatus()));
|
|
if (notAllowedStatus) {
|
|
log.warn("Cannot remove company. One or more applications in non-removable status. userId: {}, companyId: {}", userEntity.getId(), companyId);
|
|
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT));
|
|
}
|
|
|
|
userApplications = userApplications.stream()
|
|
.peek(application -> {
|
|
ApplicationEntity oldApplication = Utils.getClonedEntityForData(application);
|
|
application.setIsDeleted(Boolean.TRUE);
|
|
|
|
/** This code is responsible for adding a version history log for the "Soft delete Faq" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder()
|
|
.request(request)
|
|
.actionType(VersionActionTypeEnum.SOFT_DELETE)
|
|
.oldData(oldApplication)
|
|
.newData(application)
|
|
.build()
|
|
);
|
|
})
|
|
.toList();
|
|
applicationRepository.saveAll(userApplications);
|
|
|
|
faqs = faqs.stream()
|
|
.peek(faq -> {
|
|
FaqEntity oldFaq = Utils.getClonedEntityForData(faq);
|
|
faq.setIsDeleted(Boolean.TRUE);
|
|
/** This code is responsible for adding a version history log for the "Soft delete Faq" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder()
|
|
.request(request)
|
|
.actionType(VersionActionTypeEnum.SOFT_DELETE)
|
|
.oldData(oldFaq)
|
|
.newData(faq)
|
|
.build()
|
|
);
|
|
})
|
|
.toList();
|
|
faqRepository.saveAll(faqs);
|
|
|
|
preferredCallEntities = preferredCallEntities.stream()
|
|
.peek(beneficiaryPreferredCall -> {
|
|
BeneficiaryPreferredCallEntity oldPreferredCall = Utils.getClonedEntityForData(beneficiaryPreferredCall);
|
|
beneficiaryPreferredCall.setIsDeleted(Boolean.TRUE);
|
|
/** This code is responsible for adding a version history log for the "Soft Delete BeneficiaryPreferredCall" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder()
|
|
.request(request)
|
|
.actionType(VersionActionTypeEnum.SOFT_DELETE)
|
|
.oldData(oldPreferredCall)
|
|
.newData(beneficiaryPreferredCall)
|
|
.build()
|
|
);
|
|
})
|
|
.toList();
|
|
beneficiaryPreferredCallRepository.saveAll(preferredCallEntities);
|
|
|
|
if(userCompanyDelegationEntity!=null){
|
|
UserCompanyDelegationEntity oldUserWithCompanyDelegation = Utils.getClonedEntityForData(userCompanyDelegationEntity);
|
|
userCompanyDelegationEntity.setStatus( UserCompanyDelegationStatusEnum.INACTIVE.getValue());
|
|
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
|
|
|
|
/** This code is responsible for adding a version history log for the "Update UserWithCompanyDelegation" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldUserWithCompanyDelegation).newData(userCompanyDelegationEntity).build());
|
|
}
|
|
UserWithCompanyEntity oldUserWithCompanyData = Utils.getClonedEntityForData(existingRelation);
|
|
existingRelation.setIsDeleted(Boolean.TRUE);
|
|
userWithCompanyRepository.save(existingRelation);
|
|
|
|
/** This code is responsible for adding a version history log for the "soft deleting existing user relation" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.SOFT_DELETE).oldData(oldUserWithCompanyData).newData(existingRelation).build());
|
|
}
|
|
|
|
|
|
|
|
public void updateMissingVatCheckResponses(HttpServletRequest request, LimitRequest limitRequest) {
|
|
long limit = limitRequest.getLimit();
|
|
|
|
if (limit <= 0 || limit > 3000) {
|
|
log.error("Invalid limit: {}. Limit should be between 1 and 3000.", limit);
|
|
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
|
Translator.toLocale(GepafinConstant.INVALID_LIMIT));
|
|
}
|
|
|
|
int successfulUpdates = 0;
|
|
int failedUpdates = 0;
|
|
int invalidVatNumbers = 0;
|
|
|
|
Pageable pageable = PageRequest.of(0, (int) limit, Sort.by("id").ascending());
|
|
Page<CompanyEntity> companyPage = companyRepository.findCompaniesWithMissingVatCheck(pageable);
|
|
List<CompanyEntity> companies = companyPage.getContent();
|
|
|
|
if (companies.isEmpty()) {
|
|
log.info("No companies found with missing VAT check responses.");
|
|
return;
|
|
}
|
|
|
|
log.info("Processing {} companies with missing VAT check responses...", companies.size());
|
|
|
|
for (CompanyEntity company : companies) {
|
|
try {
|
|
log.info("Processing company ID: {} with VAT number: {}", company.getId(), company.getVatNumber());
|
|
|
|
VatCheckResponseBean vatResponse = companyService.checkVatNumber(request, company.getVatNumber());
|
|
CompanyEntity oldCompanyData = Utils.getClonedEntityForData(company);
|
|
|
|
if (vatResponse != null && vatResponse.getVatCheckResponse() != null) {
|
|
// Convert response to JSON and update the JSON field
|
|
String jsonResponse = Utils.convertMapIntoJsonString(vatResponse.getVatCheckResponse());
|
|
company.setJson(jsonResponse);
|
|
log.info("Company ID {}: JSON field updated successfully.", company.getId());
|
|
|
|
// Extract and set codiceAteco field
|
|
updateCodiceAtecoFieldWithNewJson(company);
|
|
|
|
successfulUpdates++;
|
|
} else {
|
|
company.setJson(NOT_FOUND_JSON);
|
|
invalidVatNumbers++;
|
|
log.warn("Company ID {}: Invalid or null VAT check response. JSON set to '{}'", company.getId(), NOT_FOUND_JSON);
|
|
}
|
|
|
|
// Adding version history log
|
|
/** This code is responsible for adding a version history log for the "Update MissingVatCheckResponses" operation. **/
|
|
loggingUtil.addVersionHistory(
|
|
VersionHistoryRequest.builder()
|
|
.request(request)
|
|
.actionType(VersionActionTypeEnum.UPDATE)
|
|
.oldData(oldCompanyData)
|
|
.newData(company)
|
|
.build());
|
|
|
|
} catch (Exception e) {
|
|
failedUpdates++;
|
|
log.error("Error updating VAT check response for company ID {}: {}", company.getId(), e.getMessage(), e);
|
|
}
|
|
}
|
|
|
|
companyRepository.saveAll(companies);
|
|
|
|
log.info("VAT check update completed. Limit: {} | Successful: {} | Invalid VAT numbers: {} | Failed: {}",
|
|
limit, successfulUpdates, invalidVatNumbers, failedUpdates);
|
|
}
|
|
|
|
private void updateCodiceAtecoField(CompanyEntity company) {
|
|
Map<String, Object> vatCheckResponse = Utils.convertJsonStringToMap(company.getJson());
|
|
|
|
if (vatCheckResponse == null) {
|
|
log.warn("Company ID {}: Invalid JSON response.", company.getId());
|
|
return;
|
|
}
|
|
|
|
Object dataObj = vatCheckResponse.get("data");
|
|
if (!(dataObj instanceof Map<?, ?> dataMap)) {
|
|
log.warn("Company ID {}: 'data' is missing or not a valid object.", company.getId());
|
|
return;
|
|
}
|
|
|
|
if (!dataMap.containsKey("dettaglio")) {
|
|
log.warn("Company ID {}: 'dettaglio' not present inside 'data'. Skipping codiceAteco update.", company.getId());
|
|
return;
|
|
}
|
|
|
|
Object dettaglioObj = dataMap.get("dettaglio");
|
|
if (!(dettaglioObj instanceof Map<?, ?> dettaglio)) {
|
|
log.warn("Company ID {}: 'dettaglio' is not a valid object.", company.getId());
|
|
return;
|
|
}
|
|
|
|
|
|
Object pecEmailObj = dettaglio.get("pec");
|
|
if (pecEmailObj instanceof String pec && !pec.isEmpty()) {
|
|
company.setPec(pec); // Only set if valid string
|
|
} else {
|
|
log.warn("Company ID {}: 'pec' is missing, empty, or not a string.", company.getId());
|
|
}
|
|
|
|
Object codiceAtecoObj = dettaglio.get("codice_ateco");
|
|
if (!(codiceAtecoObj instanceof String codiceAteco) || codiceAteco.isEmpty()) {
|
|
log.warn("Company ID {}: 'codice_ateco' is missing, empty, or not a string.", company.getId());
|
|
return;
|
|
}
|
|
company.setCodiceAteco(codiceAteco);
|
|
logCodiceAtecoUpdate(company, codiceAteco);
|
|
}
|
|
|
|
private void updateCodiceAtecoFieldWithNewJson(CompanyEntity company) {
|
|
if (company == null || company.getJson() == null || company.getJson().isEmpty()) {
|
|
log.warn("Company is null or JSON data is empty.");
|
|
return;
|
|
}
|
|
|
|
Map<String, Object> companyDataMap = Utils.convertJsonStringToMap(company.getJson());
|
|
if (companyDataMap == null) {
|
|
log.warn("Company ID {}: Failed to parse JSON data.", company.getId());
|
|
return;
|
|
}
|
|
|
|
// Extract 'data' section
|
|
Map<String, Object> dataMap = Utils.extractMap(companyDataMap, "data");
|
|
Object dataObj = companyDataMap.get("data");
|
|
|
|
if (dataObj instanceof Map<?, ?> singleMap) {
|
|
dataMap = (Map<String, Object>) singleMap;
|
|
} else if (dataObj instanceof List<?> list && !list.isEmpty() && list.get(0) instanceof Map<?, ?> firstMap) {
|
|
dataMap = (Map<String, Object>) firstMap;
|
|
} else {
|
|
log.warn("Company ID {}: 'data' section is missing or invalid in the JSON.", company.getId());
|
|
return;
|
|
}
|
|
if (dataObj instanceof Map<?, ?>) {
|
|
// if data is a single object
|
|
updateCodiceAtecoField(company);
|
|
} else {
|
|
|
|
Object pecEmail = dataMap.get("pec");
|
|
if (pecEmail == null) {
|
|
log.warn("Company ID {}: 'pec' section is missing or invalid.", company.getId());
|
|
}
|
|
company.setPec((String) pecEmail);
|
|
|
|
// Extract 'atecoClassification' section
|
|
Map<String, Object> atecoClassificationMap = Utils.extractMap(dataMap, "atecoClassification");
|
|
if (atecoClassificationMap == null) {
|
|
log.warn("Company ID {}: 'atecoClassification' section is missing or invalid.", company.getId());
|
|
return;
|
|
}
|
|
|
|
// Extract 'ateco' section
|
|
Map<String, Object> atecoMap = Utils.extractMap(atecoClassificationMap, "ateco");
|
|
if (atecoMap == null) {
|
|
log.warn("Company ID {}: 'ateco' section is missing or invalid.", company.getId());
|
|
return;
|
|
}
|
|
|
|
// Extract and set 'code'
|
|
String atecoCode = Utils.extractString(atecoMap, "code");
|
|
if (atecoCode != null && !atecoCode.isEmpty()) {
|
|
company.setCodiceAteco(atecoCode);
|
|
logCodiceAtecoUpdate(company, atecoCode);
|
|
} else {
|
|
log.warn("Company ID {}: 'code' inside 'ateco' is empty or missing.", company.getId());
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void logCodiceAtecoUpdate(CompanyEntity company, String atecoCode) {
|
|
|
|
log.info("Company ID {}: codiceAteco updated to {}", company.getId(), atecoCode);
|
|
}
|
|
|
|
public void getCompanyEntity() {
|
|
List<CompanyEntity> companyEntities=companyRepository.findByJsonIsNotNullAndPecIsNull();
|
|
List<CompanyEntity> companyEntityList=new ArrayList<>();
|
|
for (CompanyEntity company:companyEntities){
|
|
if(company.getJson()!=null && company.getPec()==null){
|
|
if (company == null || company.getJson() == null || company.getJson().isEmpty()) {
|
|
log.warn("Company is null or JSON data is empty.");
|
|
continue;
|
|
}
|
|
Map<String, Object> vatCheckResponse = Utils.convertJsonStringToMap(company.getJson());
|
|
|
|
if (vatCheckResponse == null) {
|
|
log.warn("Company ID {}: Invalid JSON response.", company.getId());
|
|
continue;
|
|
}
|
|
Map<String, Object> companyDataMap = Utils.convertJsonStringToMap(company.getJson());
|
|
if (companyDataMap == null) {
|
|
log.warn("Company ID {}: Failed to parse JSON data.", company.getId());
|
|
continue;
|
|
}
|
|
|
|
|
|
Object dataObj = vatCheckResponse.get("data");
|
|
Map<String, Object> dataMap=null;
|
|
// if (!(dataObj instanceof Map<?, ?> dataMap)) {
|
|
// log.warn("Company ID {}: 'data' is missing or not a valid object.", company.getId());
|
|
// continue;
|
|
// }
|
|
|
|
if (dataObj instanceof Map<?, ?> singleMap) {
|
|
dataMap = (Map<String, Object>) singleMap;
|
|
} else if (dataObj instanceof List<?> list && !list.isEmpty() && list.get(0) instanceof Map<?, ?> firstMap) {
|
|
dataMap = (Map<String, Object>) firstMap;
|
|
} else {
|
|
log.warn("Company ID {}: 'data' section is missing or invalid in the JSON.", company.getId());
|
|
continue;
|
|
}
|
|
|
|
|
|
if (dataMap.containsKey("pec")) {
|
|
Object pecEmailObj = dataMap.get("pec");
|
|
if (pecEmailObj instanceof String pec && !pec.isEmpty()) {
|
|
company.setPec(pec); // Only set if valid string
|
|
companyEntityList.add(company);
|
|
} else {
|
|
log.warn("Company ID {}: 'pec' is missing, empty, or not a string.", company.getId());
|
|
continue;
|
|
}
|
|
}
|
|
|
|
|
|
if (!dataMap.containsKey("dettaglio")) {
|
|
log.warn("Company ID {}: 'dettaglio' not present inside 'data'. Skipping codiceAteco update.", company.getId());
|
|
continue;
|
|
}
|
|
|
|
|
|
Object dettaglioObj = dataMap.get("dettaglio");
|
|
if (!(dettaglioObj instanceof Map<?, ?> dettaglio)) {
|
|
log.warn("Company ID {}: 'dettaglio' is not a valid object.", company.getId());
|
|
continue;
|
|
}
|
|
Object pecEmailObj = dettaglio.get("pec");
|
|
if (pecEmailObj instanceof String pec && !pec.isEmpty()) {
|
|
if(pec!=null) {
|
|
company.setPec(pec); // Only set if valid string
|
|
companyEntityList.add(company);
|
|
}
|
|
} else {
|
|
log.warn("Company ID {}: 'pec' is missing, empty, or not a string.", company.getId());
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
companyRepository.saveAll(companyEntityList);
|
|
}
|
|
}
|