Resolved conflicts

This commit is contained in:
Piyush
2025-02-14 13:04:55 +05:30
43 changed files with 954 additions and 213 deletions

View File

@@ -180,27 +180,27 @@ 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 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";
public static final String HH_MM_SS = "HH:mm:ss";
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";
public static final String HH_MM_SS = "HH:mm:ss";
public static final String USER_NOT_AUTHORIZED_TO_CREATE_APPLICATION = "user.not.authorized.create.application";
public static final String APPLICATION_SUBMITTED_CANNOT_CHANGE = "application.submitted.cannot.change";
@@ -218,11 +218,11 @@ public class GepafinConstant {
public static final String USER_ID_AND_BENEFICIARY_ID_ERROR = "userId.and.beneficiaryId.error";
public static final String EITHER_USER_OR_BENEFICIARY_ID_REQUIRED = "either.user.or.beneficiary.id.required";
public static final String USER_NOT_FOUND_WITH_BENEFICIARYID_MSG = "User.not.found.with.the.given.beneficiaryID";
public static final String PERMISSION_DENIED = "permission.denied";
public static final String SIGNED_DOCUMENT_FILE_UPLOAD_SUCCESS = "signed.document.file.upload.success";
public static final String GET_SIGNED_DOCUMENT_FILE_SUCCESS = "get.signed.document.file.success";
public static final String APPLICATION_SIGNED_DOCUMENT_NOT_FOUND = "application.signed.document.not.found";
public static final String DELETE_SIGNED_DOCUMENT_FILE_SUCCESS = "delete.signed.document.file.success";
public static final String PERMISSION_DENIED = "permission.denied";
public static final String SIGNED_DOCUMENT_FILE_UPLOAD_SUCCESS = "signed.document.file.upload.success";
public static final String GET_SIGNED_DOCUMENT_FILE_SUCCESS = "get.signed.document.file.success";
public static final String APPLICATION_SIGNED_DOCUMENT_NOT_FOUND = "application.signed.document.not.found";
public static final String DELETE_SIGNED_DOCUMENT_FILE_SUCCESS = "delete.signed.document.file.success";
public static final String DD_MM_YYYY = "dd/MM/yyyy";
public static final String DASHBOARD_WIDGET_FETCHED_SUCCESSFULLY="dashboard.widget.fetched.successfully";
@@ -251,16 +251,16 @@ public class GepafinConstant {
public static final String DELETE_ASSIGNED_APPLICATION_SUCCESS_MSG = "assigned.application.deleted.success";
public static final String GET_ASSIGNED_APPLICATION_SUCCESS_MSG = "assigned.application.get.success";
public static final String ASSIGNED_APPLICATION_UPDATE_SUCCESSFULLY_MSG = "assigned.application.update.successfully";
public static final String HUB_CREATE_SUCCESS = "hub_create_success";
public static final String HUB_UPDATE_SUCCESS = "hub_update_success";
public static final String HUB_GET_SUCCESS = "hub_get_success";
public static final String HUB_GET_ALL_SUCCESS = "hub_get_all_success";
public static final String HUB_DELETE_SUCCESS = "hub_delete_success";
public static final String HUB_NOT_FOUND = "hub_not_found";
public static final String EVALUATIONCRITERIA_INVALID = "evaluationCriteria.invalid";
public static final String EVALUATIONCRITERIA_INVALID = "evaluationCriteria.invalid";
public static final String APPLICATION_NOT_IN_DRAFT_STATUS="application.not.in.draft.status";
public static final String GET_ERROR_S3 = "get.error.s3";
public static final String GET_ERROR_S3 = "get.error.s3";
public static final String BENEFICIARY_EMAIL_NOT_FOUND_MSG = "beneficiary.email.not.found.msg";
public static final String ADDED_S3_PATH_STRUCTURE ="added.s3.path.structure";
public static final String S3_PATH_STRUCTURE_BY_TYPE ="fetched.s3.path.structure.by.type.successfully";
@@ -391,7 +391,7 @@ public class GepafinConstant {
public static final String NON_EMPTY_TABLES="nonEmptyTables";
public static final String VALIDATION_IN_TABLE = "validation.table.message";
public static final String CALL_EXPIRED="call.expired";
public static final String AMOUNT_REQUEST_SHOULD_GREATED_THEN_ZERO = "amount.request.should.greated.then.zero";
public static final String AMOUNT_REQUEST_SHOULD_GREATED_THEN_ZERO = "amount.request.should.greated.then.zero";
@@ -408,45 +408,23 @@ public class GepafinConstant {
public static final String ASSIGNED_APPLICATION_STATUS_UPDATED_SUCCESSFULLY = "assigned.application.status.updated.successfully";
public static final String REQUIRED_REQUESTED_AMOUNT_MSG = "validation.required.requested.amount";
public static final String REQUESTED_VS_APPROVED_AMOUNTS="requestedVsApprovedAmount";
public static final String MONTH="month";
public static final String TOTAL_REQUESTED="totalRequested";
public static final String TOTAL_APPROVED="totalApproved";
public static final String NUMBER_OF_APPLICATION="numberOfApplication";
public static final String COMPANY_ID_NOT_NULL_MSG = "company.id.not.null";
public static final String USER_WITH_COMPANY="userWithCompany";
public static final String FORMULA_AMOUNT_NOT_MATCHED="formula.amount.not.matches.requested.amount";
public static final String CRITERIA_TABLE_COLUMNS="criteria_table_columns";
public static final String DOCUMENTATION_INTEGRATION_REQUEST_SVILUPPUMBRIA= "<html>\n" +
" <body style=\"font-family: Arial, sans-serif; color: #000; line-height: 1.6;\">\n" +
" <div style=\"padding: 20px; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto;\">\n" +
" <p><strong>RICHIESTA INTEGRAZIONE DOCUMENTALE</strong></p>\n" +
" <p>Buongiorno,</p>\n" +
" <p>In riferimento alla domanda di concessione di Finanziamento agevolato a valere sul Bando \n" +
" “<strong>{{call_name}}</strong>“ di cui al <strong>Protocollo n. {{protocol_number}} del\n" +
" {{protocol_date}} e {{protocol_time}}</strong>, alla luce dell'attività istruttoria svolta,\n" +
" segnaliamo quanto segue:\n" +
" </p>\n" +
" {{note}}\n" +
" <p>Vi invitiamo a fornire quanto sopra richiesto integrando la documentazione caricandola all'interno dello sportello\n" +
" online <a href=\"{{platform_link}}\">{{platform_link}}</a> entro e <strong>non oltre {{response_days}} giorni</strong> dal ricevimento della presente comunicazione,\n" +
" precisando che, in caso di mancata ricezione nei termini indicati, saremo costretti a non prendere in considerazione la Vostra richiesta di finanziamento.\n" +
" </p>\n" +
" <p>La documentazione trasmessa e le informazioni fornite saranno processate dall'istruttore assegnatario della pratica.\n" +
" </p>\n" +
" <p>Distinti Saluti,</p>\n" +
" <p><strong>{{email_signature}}</strong></p>\n" +
" </div>\n" +
" </body>\n" +
"</html>";
public static final String APPLICATION_REJECTED_SVILUPPUMBRIA = "<html>\n" +
" <body style=\"font-family: Arial, sans-serif; color: #000; line-height: 1.6;\">\n" +
" <div style=\"padding: 20px; border: 1px solid #ddd; border-radius: 8px; max-width: 600px; margin: auto;\">\n" +
" <p>Buongiorno,</p>\n" +
" <p>Si comunica che, in riferimento alla domanda a valere sul bando “<strong>{{call_name}}</strong>” di cui al\n" +
" <strong>Protocollo n. {{protocol_number}} del {{protocol_date}} alle {{protocol_time}}</strong>,\n" +
" la stessa è stata sottoposta ad istruttoria di ammissibilità con esito negativo.</p>\n" +
" <p>Le motivazioni sono le seguenti: <strong>{{form_text}}</strong></p>\n" +
" <p>Vi ricordiamo che i Beneficiari che hanno presentato richieste valutate non ammissibili entro 10 giorni dalla data di ricevimento della presente potranno finoltrare richiesta di chiarimenti e/o osservazioni alla scrivente Società ai sensi e per gli effetti dellart.10 bis della L.241/1990 e s.m.i.</p>\n" +
" <p>Distinti Saluti,</p>\n" +
" <p><strong>{{email_signature}}</strong></p>\n" +
" </div>\n" +
" </body>\n" +
"</html>";
}

View File

@@ -1083,7 +1083,7 @@ public class ApplicationAmendmentRequestDao {
List<ApplicationAmendmentRequestResponse> response = new ArrayList<>();
if (applicationAmendmentRequestEntity != null) {
response = applicationAmendmentRequestEntity.stream()
.map(entity -> convertEntityToResponse(entity, false))
.map(entity -> convertEntityToResponse(entity, true))
.collect(Collectors.toList());
}
return response;

View File

@@ -31,6 +31,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundExceptio
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.h2.util.IOUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -49,11 +50,16 @@ import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -94,29 +100,29 @@ public class ApplicationDao {
@Autowired
private FlowDataRepository flowDataRepository;
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
@Autowired
private Validator validator;
@Autowired
private CompanyService companyService;
@Autowired
private S3PathConfig s3PathConfig;
@Autowired
private SystemEmailTemplatesService systemEmailTemplatesService;
@Autowired
private AssignedApplicationsRepository assignedApplicationsRepository;
@Value("${default_System_Receiver_Email}")
private String defaultSystemReceiverEmail;
@Value("${rinaldo_email}")
private String rinaldoEmail;
@Value("${carlo_email}")
private String carloEmail;
@@ -125,37 +131,37 @@ public class ApplicationDao {
@Autowired
private AmazonS3Service amazonS3Service;
@Autowired
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
// @Value("${aws.s3.url.folder.signed.document}")
// private String signedDocumentS3Folder;
@Value("${default.hub.uuid}")
private String defaultHubUuid;
@Autowired
private UserService userService;
@Autowired
private S3PathConfig s3ConfigBean;
@Autowired
private ProtocolDao protocolDao;
@Autowired
private HubService hubService;
@Autowired
private EmailNotificationDao emailNotificationDao;
@Autowired
private FormDao formDao;
@Autowired
private EmailLogDao emailLogDao;
@Autowired
private UserWithCompanyRepository userWithCompanyRepository;
@@ -183,6 +189,7 @@ public class ApplicationDao {
@Autowired
private ApplicationEvaluationRepository applicationEvaluationRepository;
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
FormEntity formEntity = formService.validateForm(formId);
// callService.validatePublishedCall(formEntity.getCall().getId());
@@ -258,7 +265,7 @@ public class ApplicationDao {
// List<ContentResponseBean> contentResponseBeans = Utils.convertJsonStringToList(
// applicationFormEntity.getForm().getContent(), ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans = formDao.convertFormEntityToFormResponseBean(applicationFormEntity.getForm()).getContent();
for (ApplicationFormFieldEntity applicationFormFieldEntity : applicationFormFieldEntities) {
@@ -309,7 +316,7 @@ public class ApplicationDao {
);
}
ApplicationEntity oldApplicationDataEntity = Utils.getClonedEntityForData(applicationEntity);
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
applicationEntity.setIsDeleted(true);
applicationEntity = applicationRepository.save(applicationEntity);
@@ -356,9 +363,9 @@ public class ApplicationDao {
//
// return applicationResponses;
// }
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId,List<ApplicationStatusTypeEnum> statusList) {
log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
Specification<ApplicationEntity> spec = search(userEntity, callId, companyId,statusList);
@@ -482,15 +489,18 @@ public class ApplicationDao {
public List<ApplicationFormFieldEntity> createOrUpdateMultipleFormFields(List<ApplicationFormFieldRequestBean> formFieldResponseBeans,
ApplicationFormEntity applicationFormEntity, FormEntity formEntity) {
FieldValidator fieldValidator = FieldValidator.create();
List<ApplicationFormFieldEntity> existingFields = applicationFormFieldRepository.findByApplicationFormId(applicationFormEntity.getId());
return formFieldResponseBeans.stream().map(requestBean -> createOrUpdateApplicationFormField(requestBean, applicationFormEntity, existingFields, formEntity))
List<ApplicationFormFieldEntity> applicationFormFieldEntities=formFieldResponseBeans.stream().map(requestBean -> createOrUpdateApplicationFormField(requestBean, applicationFormEntity, existingFields, formEntity,fieldValidator))
.collect(Collectors.toList());
fieldValidator.validate();
return applicationFormFieldEntities;
}
public ApplicationFormFieldEntity createOrUpdateApplicationFormField(ApplicationFormFieldRequestBean applicationFormFieldRequestBean,
ApplicationFormEntity applicationFormEntity, List<ApplicationFormFieldEntity> applicationFormFieldEntities, FormEntity formEntity) {
ApplicationFormEntity applicationFormEntity, List<ApplicationFormFieldEntity> applicationFormFieldEntities, FormEntity formEntity,FieldValidator fieldValidator) {
ApplicationFormFieldEntity applicationFormFieldEntity = new ApplicationFormFieldEntity();
@@ -506,7 +516,6 @@ public class ApplicationDao {
.filter(setting -> "isRequestedAmount".equals(setting.getName()) && Boolean.TRUE.equals(setting.getValue()))
.findFirst()
.ifPresent(setting -> {
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
if(fieldValue!=null) {
try {
@@ -538,6 +547,7 @@ public class ApplicationDao {
}
}
}
calculationProcessForFormula(applicationFormEntity,contentResponseBeans,applicationFormFieldRequestBean,fieldValidator);
Utils.setIfUpdated(applicationFormFieldEntity::getFieldId, applicationFormFieldEntity::setFieldId, applicationFormFieldRequestBean.getFieldId());
if (applicationFormFieldRequestBean.getFieldValue() != null) {
@@ -560,7 +570,6 @@ public class ApplicationDao {
VersionHistoryRequest.builder().request(request).actionType(actionType).oldData(oldApplicationFormFieldData).newData(applicationFormField).build());
log.info("Version history logged for action: {}, Field ID: {}", actionType, applicationFormFieldEntity.getFieldId());
return applicationFormField;
}
@@ -818,7 +827,7 @@ public class ApplicationDao {
if(formApplicationResponse.getContent() != null && formApplicationResponse.getFormFields() != null) {
formApplicationResponses.add(formApplicationResponse);
}
}
public FormApplicationResponse processForm(FormEntity formEntity, ApplicationEntity applicationEntity) {
@@ -878,6 +887,10 @@ public class ApplicationDao {
checkCallEndDate(call);
// call = callService.validatePublishedCall(call.getId());
// checkIfApplicationExists(call, userWithCompanyEntity, userEntity);
HubEntity hubEntity = hubService.valdateHub(call.getHub().getId());
if(hubEntity.getUniqueUuid().equals(defaultHubUuid)){
checkIfApplicationExists(call, userWithCompanyEntity, userEntity);
}
ApplicationEntity applicationEntity = createApplicationEntity(userEntity, call, userWithCompanyEntity);
applicationEntity.setComments(applicationRequest.getComments());
applicationEntity = saveApplicationEntity(applicationEntity);
@@ -890,6 +903,18 @@ public class ApplicationDao {
// }
// }
public void checkIfApplicationExists(CallEntity call, UserWithCompanyEntity userWithCompanyEntity, UserEntity userEntity){
List<ApplicationEntity> applications = applicationRepository.findByUserIdAndUserWithCompany_IdAndCall_IdAndIsDeletedFalseAndStatusNot(
userEntity.getId(), userWithCompanyEntity.getId(), call.getId(), ApplicationStatusTypeEnum.REJECTED.name()
);
if (!applications.isEmpty()) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
}
}
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
@@ -954,7 +979,7 @@ public class ApplicationDao {
return (int) Math.round(progress);
}
public void validateFormFields(ApplicationRequestBean request, FormEntity formEntity) {
// List<ContentResponseBean> contentResponseBeans=Utils.convertJsonStringToList(formEntity.getContent(),ContentResponseBean.class);
List<ContentResponseBean> contentResponseBeans=formDao.convertFormEntityToFormResponseBean(formEntity).getContent();
@@ -1034,7 +1059,7 @@ public class ApplicationDao {
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_TO_USER_AND_COMPANY,
hub, null);
// Create the map for subject placeholders
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
@@ -1107,15 +1132,28 @@ public class ApplicationDao {
// mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
// mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
// mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
if(validator.isProductionProfileActivated()) {
emailLogRequest.setRecipientEmails(carloEmail);
// mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(carloEmail),emailLogRequest);
}
// if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(defaultHubUuid))) {
// if (validator.isProductionProfileActivated()) {
// emailLogRequest.setRecipientEmails(carloEmail);
//// mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
// emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(carloEmail),emailLogRequest);
// }
// List<String> listDefaultSystemReceiverEmail = Arrays.stream(defaultSystemReceiverEmail.split(","))
// .map(String::trim)
// .filter(email -> !email.isEmpty())
// .toList();
//
// emailLogRequest.setRecipientEmails(defaultSystemReceiverEmail);
// emailNotificationDao.sendMail(hub.getId(), subject, body, listDefaultSystemReceiverEmail, emailLogRequest);
// }
List<String> hubEmails = Arrays.stream(hub.getEmail().split(","))
.map(String::trim)
.filter(email -> !email.isEmpty())
.toList();
emailLogRequest.setRecipientEmails(hub.getEmail());
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(hub.getEmail()),emailLogRequest);
emailLogRequest.setRecipientEmails(defaultSystemReceiverEmail);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(defaultSystemReceiverEmail),emailLogRequest);
emailNotificationDao.sendMail(hub.getId(), subject, body,hubEmails,emailLogRequest);
emailLogRequest.setRecipientEmails(rinaldoEmail);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(rinaldoEmail),emailLogRequest);
}
@@ -1211,17 +1249,17 @@ public class ApplicationDao {
}
public ApplicationSignedDocumentResponse getSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
// validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
if (validator.checkIsPreInstructor()) {
ApplicationEvaluationEntity applicationEvaluationEntity = applicationEvaluationService.validateApplicationEvaluationByApplicationId(applicationId);
validator.validatePreInstructor(request, applicationEvaluationEntity.getUserId());
} else {
validator.validateUserId(request, applicationEntity.getUserId());
}
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
@@ -1230,11 +1268,11 @@ public class ApplicationDao {
}
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
public void deleteSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
//cloned entity for old data
@@ -1404,6 +1442,9 @@ public class ApplicationDao {
public PageableResponseBean<List<ApplicationResponse>> getAllApplicationByPagination(UserEntity userEntity, Long callId, Long companyId, ApplicationPageableRequestBean applicationPageableRequestBean) {
Integer pageNo = null;
Integer pageLimit = null;
UserWithCompanyEntity userWithCompany= userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), companyId).orElse(null);
if (applicationPageableRequestBean.getGlobalFilters() != null) {
pageNo = applicationPageableRequestBean.getGlobalFilters().getPage();
pageLimit = applicationPageableRequestBean.getGlobalFilters().getLimit();
@@ -1414,7 +1455,7 @@ public class ApplicationDao {
if (pageNo == null || pageNo <= 0) {
pageNo = GepafinConstant.DEFAULT_PAGE;
}
Specification<ApplicationEntity> spec = search(callId, companyId, applicationPageableRequestBean, userEntity);
Specification<ApplicationEntity> spec = search(callId,companyId, userWithCompany.getId(), applicationPageableRequestBean, userEntity);
Page<ApplicationEntity> entityPage = applicationRepository.findAll(spec, PageRequest.of(pageNo - 1, pageLimit));
// Prepare the response
@@ -1437,10 +1478,10 @@ public class ApplicationDao {
return pageableResponseBean;
}
public Specification<ApplicationEntity> search(Long callId, Long companyId, ApplicationPageableRequestBean applicationPageableRequestBean, UserEntity userEntity) {
public Specification<ApplicationEntity> search(Long callId, Long companyId, Long userWithCompanyId, ApplicationPageableRequestBean applicationPageableRequestBean, UserEntity userEntity) {
return (root, query, criteriaBuilder) -> {
List<Predicate> predicates = getPredicates(applicationPageableRequestBean, criteriaBuilder, root, callId, companyId, userEntity);
List<Predicate> predicates = getPredicates(applicationPageableRequestBean, criteriaBuilder, root, callId,companyId, userWithCompanyId, userEntity);
SortBy sortBy = new SortBy(GepafinConstant.CREATED_DATE, true);
if (applicationPageableRequestBean.getGlobalFilters() != null
@@ -1464,13 +1505,15 @@ public class ApplicationDao {
private List<Predicate> getPredicates(ApplicationPageableRequestBean applicationPageableRequestBean,
CriteriaBuilder criteriaBuilder, Root<ApplicationEntity> root, Long callId, Long companyId, UserEntity userEntity) {
CriteriaBuilder criteriaBuilder, Root<ApplicationEntity> root, Long callId,Long companyId, Long userWithCompanyId, UserEntity userEntity) {
Integer year = null;
String search = null;
Integer daysRange = null;
if (applicationPageableRequestBean.getGlobalFilters() != null) {
year = applicationPageableRequestBean.getGlobalFilters().getYear();
search = applicationPageableRequestBean.getGlobalFilters().getSearch();
daysRange = applicationPageableRequestBean.getDaysRange();
}
List<Predicate> predicates = new ArrayList<>();
@@ -1512,16 +1555,24 @@ public class ApplicationDao {
}
// Optional companyId filter
if (userWithCompanyId != null) {
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.USER_WITH_COMPANY).get(GepafinConstant.ID), userWithCompanyId));
}
if (companyId != null) {
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.COMPANY_ID), companyId));
}
if (daysRange != null && daysRange >= 0) {
LocalDateTime today = LocalDateTime.now();
LocalDateTime pastDate = today.minusDays(daysRange);
predicates.add(criteriaBuilder.between(root.get(GepafinConstant.CREATED_DATE), pastDate, today));
}
predicates.add(criteriaBuilder.isFalse(root.get(GepafinConstant.IS_DELETED)));
predicates.add(criteriaBuilder.equal(root.get(GepafinConstant.HUB_ID), userEntity.getHub().getId()));
return predicates;
}
public void checkCallEndDate(CallEntity call) {
LocalDateTime now = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
@@ -1539,5 +1590,135 @@ public class ApplicationDao {
}
}
public void calculationProcessForFormula(ApplicationFormEntity applicationFormEntity, List<ContentResponseBean> contentResponseBeans, ApplicationFormFieldRequestBean applicationFormFieldRequestBean,FieldValidator fieldValidator) {
List<String> formulaValue = new ArrayList<>();
String formulaValueOpt=null;
String label=null;
for (ContentResponseBean contentResponseBean:contentResponseBeans){
if(contentResponseBean.getId().equals(applicationFormFieldRequestBean.getFieldId())){
for (SettingResponseBean settingResponseBean:contentResponseBean.getSettings()){
if (settingResponseBean.getName().equals("label")){
label= String.valueOf(settingResponseBean.getValue());
}
if(settingResponseBean.getName().equals("formula")){
String value= (String) settingResponseBean.getValue();
formulaValueOpt=value;
formulaValue=Utils.extractValues(value);
}
}
}
}
Map<String, String> mappedFormulaValue = new HashMap<>();
Object fieldValue = applicationFormFieldRequestBean.getFieldValue();
if (formulaValueOpt != null && fieldValue==null) {
fieldValue=0;
}
for (ContentResponseBean contentResponseBean : contentResponseBeans) {
String contentId = contentResponseBean.getId();
// Extract variable values once per contentResponseBean to avoid repeated stream operations
Set<String> variableValues = contentResponseBean.getSettings().stream()
.filter(setting -> "variable".equals(setting.getName()))
.flatMap(setting -> {
Object value = setting.getValue(); // Get the raw value
if (value instanceof String) {
return Stream.of((String) value); // Handle single String case
} else if (value instanceof List) {
return ((List<?>) value).stream()
.filter(item -> item instanceof String) // Ensure it's a String
.map(item -> (String) item); // Convert to String
} else {
return Stream.empty(); // Ignore unexpected types
}
})
.collect(Collectors.toSet()); // Collect into a Set for uniqueness
for (String formula : formulaValue) {
if (variableValues.contains(formula)) { // O(1) lookup instead of O(n)
mappedFormulaValue.put(formula, contentId);
}
}
}
Map<String, String> updatedMappedFormulaValue = new HashMap<>();
for (Map.Entry<String, String> entry : mappedFormulaValue.entrySet()) {
String variable = entry.getKey();
String contentId = entry.getValue();
// Repository call using contentId
Optional<ApplicationFormFieldEntity> optionalEntity = applicationFormFieldRepository.findByApplicationFormIdAndFieldId(applicationFormEntity.getId(),contentId);
// If entity is found, extract fieldValue and fieldId
optionalEntity.ifPresent(entity -> {
String entityFieldValue = entity.getFieldValue(); // Assuming getter method exists
String fieldId = entity.getFieldId(); // Assuming getter method exists
String tableType = contentResponseBeans.stream()
.filter(content -> content.getId().equals(fieldId)) // Match Content ID with fieldId
.flatMap(content -> content.getSettings().stream()) // Extract settings
.filter(setting -> "criteria_table_columns".equals(setting.getName())) // Match name
.map(setting -> setting.getName()) // Return the name of the setting
.findFirst() // Get the first match
.orElse(null); // Default to null if no match
if(tableType!=null){
JSONObject jsonObject = new JSONObject(entityFieldValue);
// Extract the value of total
entityFieldValue = jsonObject.getString("total");
}
updatedMappedFormulaValue.put(fieldId, entityFieldValue);
});
}
if(formulaValueOpt==null || formulaValueOpt.isEmpty()){
return;
}
double finalValue = evaluateFormula(formulaValueOpt, mappedFormulaValue, updatedMappedFormulaValue);
fieldValidator.formulaValidation(fieldValue, finalValue, label);
}
public static double evaluateFormula(String formula, Map<String, String> mappedFormulaValue, Map<String, String> updatedMappedFormulaValue) {
// Step 1: Extract all placeholders (variables) like {rest}, {another_var}, etc.
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher matcher = pattern.matcher(formula);
List<String> variables = new ArrayList<>();
while (matcher.find()) {
variables.add(matcher.group(1)); // Extract variable names inside the curly braces
}
// Step 2: Replace placeholders with corresponding fieldValue
Map<String, Double> variableValues = new HashMap<>();
for (String variable : variables) {
String fieldId = mappedFormulaValue.get(variable);
if (fieldId != null && updatedMappedFormulaValue.containsKey(fieldId)) {
String fieldValueStr = updatedMappedFormulaValue.get(fieldId);
try {
double fieldValue = Double.parseDouble(fieldValueStr); // Assuming fieldValue is numeric
variableValues.put(variable, fieldValue);
} catch (NumberFormatException e) {
// Handle invalid number format gracefully (e.g., log an error or default to 0)
variableValues.put(variable, 0.0);
}
}
}
// Step 3: Replace variables in the formula with their corresponding values
String expression = formula;
for (String variable : variables) {
Double value = variableValues.get(variable);
if (value != null) {
// Replace {variable} with its corresponding value in the formula
expression = expression.replace("{" + variable + "}", String.valueOf(value));
}
}
// Step 4: Evaluate the mathematical expression
return Utils.evaluateExpression(expression);
}
}

View File

@@ -153,7 +153,7 @@ public class ApplicationEvaluationDao {
Long hubId = application.getHubId();
HubEntity hub = hubService.valdateHub(hubId);
Long initialDays = (hub != null) ? hub.getEvaluationExpirationDays() : 0L;
Long initialDays = (hub != null) ? hub.getEvaluationExpirationDays() : 30L;
entity.setApplicationId(application.getId());
entity.setAssignedApplicationsEntity(assignedApplications);
@@ -165,10 +165,10 @@ public class ApplicationEvaluationDao {
entity.setMotivation(req.getMotivation());
entity.setIsDeleted(false);
entity.setInitialDays(initialDays);
entity.setRemainingDays(30L);
entity.setRemainingDays(initialDays);
entity.setSuspendedDays(0L);
entity.setStartDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
entity.setEndDate(DateTimeUtil.DateServerToUTC(application.getSubmissionDate().plusDays(30)));
entity.setEndDate(DateTimeUtil.DateServerToUTC(application.getSubmissionDate().plusDays(initialDays)));
entity.setEvaluationVersion(application.getEvaluationVersion());
entity.setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
return entity;
@@ -295,6 +295,9 @@ public class ApplicationEvaluationDao {
response.setEvaluationEndDate(entity.getEndDate());
response.setCreatedDate(entity.getCreatedDate());
response.setUpdatedDate(entity.getUpdatedDate());
response.setNumberOfCheck(entity.getAssignedApplicationsEntity().getApplication().getCall().getNumberOfCheck());
response.setProductId(entity.getAssignedApplicationsEntity().getApplication().getCall().getProductId());
}
@@ -1153,6 +1156,8 @@ public class ApplicationEvaluationDao {
response.setEvaluationEndDate(entity.getEndDate());
LocalDateTime callEndDate = application.getCall().getEndDate();
response.setCallEndDate(callEndDate);
response.setNumberOfCheck(call.getNumberOfCheck());
response.setProductId(call.getProductId());
setCriteriaResponses(entity, application.getId(), response, evaluationCriterias);
setChecklistResponses(entity, application.getId(), response, checklistEntities);
setFileResponses(entity, application.getId(), response, applicationFormEntities);

View File

@@ -200,6 +200,8 @@ public class AssignedApplicationsDao {
if(applicationEvaluationEntity.isPresent()){
assignedApplicationsResponse.setEvaluationEndDate(applicationEvaluationEntity.get().getEndDate());
}
assignedApplicationsResponse.setNumberOfCheck(application.getCall().getNumberOfCheck());
assignedApplicationsResponse.setProductId(application.getCall().getProductId());
return assignedApplicationsResponse;
}

View File

@@ -201,6 +201,8 @@ public class CallDao {
callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime()));
callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime()));
callEntity.setHub(userEntity.getHub());
callEntity.setNumberOfCheck(createCallRequest.getNumberOfCheck());
callEntity.setProductId(createCallRequest.getProductId());
callEntity = callRepository.save(callEntity);
/** This code is responsible for adding a version history log for the "Create Call" operation. **/
@@ -607,6 +609,8 @@ public class CallDao {
setIfUpdated(callEntity::getEndTime, callEntity::setEndTime, DateTimeUtil.parseTime(updateCallRequest.getEndTime()));
setIfUpdated(callEntity::getConfidi, callEntity::setConfidi, updateCallRequest.getConfidi());
setIfUpdated(callEntity::getEvaluationVersion, callEntity::setEvaluationVersion, updateCallRequest.getEvaluationVersion().getValue());
setIfUpdated(callEntity::getNumberOfCheck, callEntity::setNumberOfCheck, updateCallRequest.getNumberOfCheck());
setIfUpdated(callEntity::getProductId, callEntity::setProductId, updateCallRequest.getProductId());
callEntity = callRepository.save(callEntity);
/** This code is responsible for adding a version history log for the "update call step 1" operation **/
@@ -713,7 +717,8 @@ public class CallDao {
callDetailsResponseBean.setPhoneNumber(callEntity.getPhoneNumber());
callDetailsResponseBean.setCreatedDate(callEntity.getCreatedDate());
callDetailsResponseBean.setUpdatedDate(callEntity.getUpdatedDate());
callDetailsResponseBean.setNumberOfCheck(callEntity.getNumberOfCheck());
callDetailsResponseBean.setProductId(callEntity.getProductId());
return callDetailsResponseBean;
}
@@ -737,6 +742,8 @@ public class CallDao {
createCallResponseBean.setFaq(faqService.getFaqByCallId(callEntity.getId()));
createCallResponseBean.setAimedTo(amiedTo);
createCallResponseBean.setCheckList(checkList);
createCallResponseBean.setNumberOfCheck(callEntity.getNumberOfCheck());
createCallResponseBean.setProductId(callEntity.getProductId());
return createCallResponseBean;
}

View File

@@ -65,8 +65,8 @@ public class DashboardDao {
public SuperAdminWidgetResponseBean getDashboardWidget(UserEntity requestedUserEntity) {
SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean();
widgetResponseBean.setWidget1(createWidget1(requestedUserEntity));
Map<String, Object> widgetBars =getStatistics(requestedUserEntity);
widgetResponseBean.setWidgetBars(widgetBars);
Map<String, Object> widgetBars = getStatistics(requestedUserEntity);
widgetResponseBean.setWidgetBars(widgetBars);
return widgetResponseBean;
}
@@ -79,8 +79,8 @@ public class DashboardDao {
setSubmittedApplications(widget1, requestedUserEntity);
setDraftApplications(widget1, requestedUserEntity);
setNumberOfCompanies(widget1, requestedUserEntity);
setAmountRequested(widget1,requestedUserEntity);
setAmountAccepted(widget1,requestedUserEntity);
setAmountRequested(widget1, requestedUserEntity);
setAmountAccepted(widget1, requestedUserEntity);
return widget1;
}
@@ -198,7 +198,8 @@ public class DashboardDao {
return stats;
}
// public Page<UserActionEntity> getUserAction(UserEntity requestedUserEntity){
// public Page<UserActionEntity> getUserAction(UserEntity requestedUserEntity){
// Pageable pageable = PageRequest.of(0, 20); // Get the first 20 records
// List<String> roles=List.of(RoleStatusEnum.ROLE_PRE_INSTRUCTOR.getValue(),RoleStatusEnum.ROLE_GEPAFIN_OPERATOR.getValue(),RoleStatusEnum.ROLE_INSTRUCTOR_MANAGER.getValue());
// Page<UserActionEntity> userActionEntities=userActionsRepository.findActionsByRoleNamesAndHubId(roles,requestedUserEntity.getHub().getId(),pageable);
@@ -256,7 +257,7 @@ public class DashboardDao {
responseBean.setEvaluationAverageTime(averageTime != null ? averageTime.setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO);
}
LocalDate twoDaysLater = LocalDate.now().plusDays(2);
List<String> statusList =Arrays.asList( ApplicationEvaluationStatusTypeEnum.OPEN.getValue(), ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
List<String> statusList = Arrays.asList(ApplicationEvaluationStatusTypeEnum.OPEN.getValue(), ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
Long dueApplications = applicationEvaluationRepository.countDueApplicationsBetween(
applicationIds,
LocalDate.now(),
@@ -268,6 +269,7 @@ public class DashboardDao {
responseBean.setNumberOfDueApplication(dueApplications);
}
}
private AmendmentWidgetResponseBean initializeAmendmentResponseBean() {
return AmendmentWidgetResponseBean.builder()
.totalAmendments(0L)
@@ -279,17 +281,18 @@ public class DashboardDao {
.build();
}
public AmendmentWidgetResponseBean getAmendmentDetails(UserEntity userEntity) {
AmendmentWidgetResponseBean amendmentWidgetResponseBean = initializeAmendmentResponseBean();
public AmendmentWidgetResponseBean getAmendmentDetails(UserEntity userEntity) {
AmendmentWidgetResponseBean amendmentWidgetResponseBean = initializeAmendmentResponseBean();
Long hubId = userEntity.getHub().getId();
List<Long> applicationIds = getApplicationIdsForUserOrHub(userEntity,hubId,null);
setAmendmentCounts(applicationIds,amendmentWidgetResponseBean, hubId);
calculateExpiringRequestsIn48Hours(applicationIds,amendmentWidgetResponseBean, hubId);
calculateAverageResponseDays(applicationIds,amendmentWidgetResponseBean,hubId);
return amendmentWidgetResponseBean;
}
public List<Long> getApplicationIdsForUserOrHub(UserEntity userEntity, Long hubId , Long userId) {
Long hubId = userEntity.getHub().getId();
List<Long> applicationIds = getApplicationIdsForUserOrHub(userEntity, hubId, null);
setAmendmentCounts(applicationIds, amendmentWidgetResponseBean, hubId);
calculateExpiringRequestsIn48Hours(applicationIds, amendmentWidgetResponseBean, hubId);
calculateAverageResponseDays(applicationIds, amendmentWidgetResponseBean, hubId);
return amendmentWidgetResponseBean;
}
public List<Long> getApplicationIdsForUserOrHub(UserEntity userEntity, Long hubId, Long userId) {
if (userId != null) {
return assignedApplicationsRepository.findApplicationIdsByUserIdAndIsDeletedFalse(userId);
} else if (validator.checkIsPreInstructor()) {
@@ -299,31 +302,31 @@ public class DashboardDao {
}
}
private void setAmendmentCounts(List<Long> applicationIds,AmendmentWidgetResponseBean responseBean, Long hubId) {
private void setAmendmentCounts(List<Long> applicationIds, AmendmentWidgetResponseBean responseBean, Long hubId) {
Long totalAmendment = applicationAmendmentRequestRepository.countAmendmentsByApplicationIds(applicationIds);
if (totalAmendment != null) {
responseBean.setTotalAmendments(totalAmendment);
}
Long totalAmendment = applicationAmendmentRequestRepository.countAmendmentsByApplicationIds(applicationIds);
if (totalAmendment != null) {
responseBean.setTotalAmendments(totalAmendment);
}
Long awaitingAmendments = applicationAmendmentRequestRepository.countAmendmentsByApplicationIdsAndStatus(
applicationIds, ApplicationAmendmentRequestEnum.AWAITING.getValue());
if (awaitingAmendments != null) {
responseBean.setWaitingForResponseAmendments(awaitingAmendments);
}
Long responseRecievedAmendments = applicationAmendmentRequestRepository.countAmendmentsByApplicationIdsAndStatus(
applicationIds, ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue());
if (responseRecievedAmendments != null) {
responseBean.setResponseReceivedAmendments(responseRecievedAmendments);
}
Long expiredAmendments = applicationAmendmentRequestRepository.countAmendmentsByApplicationIdsAndStatus(
applicationIds, ApplicationAmendmentRequestEnum.EXPIRED.getValue());
if (expiredAmendments != null) {
responseBean.setExpiredAmendments(expiredAmendments);
}
}
Long awaitingAmendments = applicationAmendmentRequestRepository.countAmendmentsByApplicationIdsAndStatus(
applicationIds, ApplicationAmendmentRequestEnum.AWAITING.getValue());
if (awaitingAmendments != null) {
responseBean.setWaitingForResponseAmendments(awaitingAmendments);
}
Long responseRecievedAmendments = applicationAmendmentRequestRepository.countAmendmentsByApplicationIdsAndStatus(
applicationIds, ApplicationAmendmentRequestEnum.RESPONSE_RECEIVED.getValue());
if (responseRecievedAmendments != null) {
responseBean.setResponseReceivedAmendments(responseRecievedAmendments);
}
Long expiredAmendments = applicationAmendmentRequestRepository.countAmendmentsByApplicationIdsAndStatus(
applicationIds, ApplicationAmendmentRequestEnum.EXPIRED.getValue());
if (expiredAmendments != null) {
responseBean.setExpiredAmendments(expiredAmendments);
}
}
private void calculateExpiringRequestsIn48Hours(List<Long> applicationIds ,AmendmentWidgetResponseBean responseBean, Long hubId) {
private void calculateExpiringRequestsIn48Hours(List<Long> applicationIds, AmendmentWidgetResponseBean responseBean, Long hubId) {
// Define the statuses to filter
List<String> statuses = List.of(
@@ -345,7 +348,7 @@ public class DashboardDao {
}
}
private void calculateAverageResponseDays(List<Long> applicationIds ,AmendmentWidgetResponseBean responseBean, Long hubId) {
private void calculateAverageResponseDays(List<Long> applicationIds, AmendmentWidgetResponseBean responseBean, Long hubId) {
if (!applicationIds.isEmpty()) {
BigDecimal averageResponseDays = applicationAmendmentRequestRepository
@@ -359,15 +362,16 @@ public class DashboardDao {
responseBean.setAverageResponseDays(BigDecimal.ZERO);
}
}
public AssignedApplicationWidgetResponseBean getApplicationDetailsForEvaluation(UserEntity userEntity) {
Long userId = userEntity.getId();
Long hubId = userEntity.getHub().getId();
public AssignedApplicationWidgetResponseBean getApplicationDetailsForEvaluation(UserEntity userEntity) {
Long userId = userEntity.getId();
Long hubId = userEntity.getHub().getId();
Object[] results;
List<Long> applicationIds;
if (validator.checkIsPreInstructor()) {
results = assignedApplicationsRepository.countAssignedApplicationsWithStatus(userId, hubId);
applicationIds = assignedApplicationsRepository.findApplicationIdsByUserIdAndHubIdAndIsDeletedFalse(userId,hubId);
applicationIds = assignedApplicationsRepository.findApplicationIdsByUserIdAndHubIdAndIsDeletedFalse(userId, hubId);
} else {
results = assignedApplicationsRepository.countAssignedApplicationsForHub(hubId);
applicationIds = assignedApplicationsRepository.findApplicationIdsByHubId(hubId);
@@ -389,9 +393,9 @@ public AssignedApplicationWidgetResponseBean getApplicationDetailsForEvaluation(
LocalDate today = LocalDate.now();
LocalDate twoDaysLater = today.plusDays(2);
List<String> statusList =Arrays.asList( ApplicationEvaluationStatusTypeEnum.OPEN.getValue(), ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
List<String> statusList = Arrays.asList(ApplicationEvaluationStatusTypeEnum.OPEN.getValue(), ApplicationEvaluationStatusTypeEnum.SOCCORSO.getValue());
Long dueApplications = applicationEvaluationRepository.countDueApplicationsBetween(
applicationIds, today, twoDaysLater,statusList
applicationIds, today, twoDaysLater, statusList
);
response.setNumberOfApplicationExpiringIn48Hours(dueApplications != null ? dueApplications : 0L);
}
@@ -409,7 +413,109 @@ public AssignedApplicationWidgetResponseBean getApplicationDetailsForEvaluation(
return response;
}
public static List<String> getStatusList() {
return List.of(
ApplicationStatusTypeEnum.SUBMIT.getValue(),
ApplicationStatusTypeEnum.EVALUATION.getValue(),
ApplicationStatusTypeEnum.APPROVED.getValue(),
ApplicationStatusTypeEnum.REJECTED.getValue(),
ApplicationStatusTypeEnum.SOCCORSO.getValue(),
ApplicationStatusTypeEnum.APPOINTMENT.getValue(),
ApplicationStatusTypeEnum.NDG.getValue(),
ApplicationStatusTypeEnum.ADMISSIBLE.getValue()
);
}
public BeneficiaryStatisticsResponseBean getStatisticsPageForBeneficiary(UserEntity userEntity, CompanyEntity company) {
BeneficiaryStatisticsResponseBean widgetResponseBean = initializeBeneficiaryStatisticsBean();
UserWithCompanyEntity userWithCompanyEntity = companyService.getUserWithCompany(userEntity.getId(), company.getId());
Long hubId = userEntity.getHub().getId();
List<String> statusList = getStatusList();
Long submittedApplication = applicationRepository.countSubmittedApplicationsByHubIdAndUserId(hubId, userEntity.getId(), userWithCompanyEntity.getId(), statusList);
Long approvedApplication = getApplicationCountByStatus(hubId, userEntity.getId(), userWithCompanyEntity.getId(), ApplicationStatusTypeEnum.APPROVED);
BigDecimal successRate = getSuccessRate(hubId, userEntity.getId(), userWithCompanyEntity.getId());
BigDecimal totalAmountRequested = applicationRepository.sumAmountRequestedByHubIdAndUserId(hubId, userEntity.getId(), userWithCompanyEntity.getId());
updateApplicationWidget(widgetResponseBean.getApplicationWidget(), submittedApplication, approvedApplication, successRate, totalAmountRequested);
Map<String, Object> widgetBars = getApplicationStatistics(userEntity, userWithCompanyEntity.getId());
widgetResponseBean.setApplicationWidgetBars(widgetBars);
return widgetResponseBean;
}
private BeneficiaryStatisticsResponseBean initializeBeneficiaryStatisticsBean() {
return BeneficiaryStatisticsResponseBean.builder()
.applicationWidget(ApplicationWidget.builder()
.submittedApplication(0L)
.approvedApplication(0L)
.successRate(BigDecimal.ZERO)
.totalAmountFinanced(BigDecimal.ZERO)
.build())
.build();
}
private Long getApplicationCountByStatus(Long hubId, Long userId, Long userWithCompanyId, ApplicationStatusTypeEnum status) {
return applicationRepository.countSubmittedApplicationsByHubIdAndUserIdAndStatus(hubId, userId, userWithCompanyId, status.getValue());
}
private BigDecimal getSuccessRate(Long hubId, Long userId, Long userWithCompanyId) {
return applicationRepository.findSuccessRateByHubIdAndUserIdAndUserWithCompanyId(hubId, userId, userWithCompanyId);
}
private void updateApplicationWidget(ApplicationWidget applicationWidget, Long submittedApplication, Long approvedApplication, BigDecimal successRate, BigDecimal totalAmountRequested) {
applicationWidget.setSubmittedApplication(submittedApplication != null ? submittedApplication : 0L);
applicationWidget.setApprovedApplication(approvedApplication != null ? approvedApplication : 0L);
applicationWidget.setSuccessRate(successRate != null ? successRate : BigDecimal.ZERO);
applicationWidget.setTotalAmountFinanced(totalAmountRequested != null ? totalAmountRequested : BigDecimal.ZERO);
}
public Map<String, Object> getApplicationStatistics(UserEntity requestedUser, Long userWithCompanyId) {
Map<String, Object> stats = new HashMap<>();
Map<String, Long> statusData = new HashMap<>();
for (ApplicationStatusTypeEnum status : ApplicationStatusTypeEnum.values()) {
statusData.put(status.name(), 0L);
}
// Get applications per status
List<Object[]> applicationsByStatus = applicationRepository.findApplicationsByStatusAndUserIdAndUserWithCompanyId(
requestedUser.getHub().getId(),
requestedUser.getId(),
userWithCompanyId
);
applicationsByStatus.forEach(result -> {
String status = (String) result[0];
Long count = (Long) result[1];
statusData.put(status, count);
});
List<Map<String, Object>> statusList = statusData.entrySet().stream().map(entry -> {
Map<String, Object> statusMap = new HashMap<>();
statusMap.put(GepafinConstant.STATUS, entry.getKey());
statusMap.put(GepafinConstant.NUMBER_OF_APPLICATION, entry.getValue());
return statusMap;
}).collect(Collectors.toList());
stats.put(GepafinConstant.APPLICATION_PER_STATUS, statusList);
// Requested VS Approved Amounts
List<Object[]> requestedVsApprovedAmounts = applicationRepository.findRequestedVsApprovedAmountsPerMonth(
requestedUser.getHub().getId(),
requestedUser.getId(),
userWithCompanyId
);
stats.put(GepafinConstant.REQUESTED_VS_APPROVED_AMOUNTS, requestedVsApprovedAmounts.stream().map(result -> {
Map<String, Object> data = new HashMap<>();
data.put(GepafinConstant.MONTH, result[0]);
data.put(GepafinConstant.TOTAL_REQUESTED, result[1]!= null ? result[1] : 0L);
data.put(GepafinConstant.TOTAL_APPROVED, result[2] != null ? result[2] : 0L);
return data;
}).toList());
return stats;
}
private PreInstructorWidgetResponseBean initializeDashboardPreInstructorResponseBean() {
return PreInstructorWidgetResponseBean.builder()
.assignedApplication(ApplicationToConsider.builder()

View File

@@ -94,19 +94,7 @@ public class EmailNotificationDao {
subjectPlaceholders.put("{{company_name}}", company.getCompanyName());
// bodyPlaceholders.put("{{legal_mail}}", legalMail);
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body;
if ("t7jh5wfg9QXylNaTZkPoE".equals(hubEntity.getUniqueUuid()) && templateType.equals(SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.DOCUMENTATION_INTEGRATION_REQUEST)) {
bodyPlaceholders.put("{{email_signature}}", hubEntity.getEmailSignature());
bodyPlaceholders.put("{{platform_link}}",hubEntity.getDomainName());
body = Utils.replacePlaceholders(GepafinConstant.DOCUMENTATION_INTEGRATION_REQUEST_SVILUPPUMBRIA, bodyPlaceholders);
}
else if ("t7jh5wfg9QXylNaTZkPoE".equals(hubEntity.getUniqueUuid()) && templateType.equals(SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum.INADMISSIBILITY_TEMPLATE)) {
bodyPlaceholders.put("{{email_signature}}", hubEntity.getEmailSignature());
body = Utils.replacePlaceholders(GepafinConstant.APPLICATION_REJECTED_SVILUPPUMBRIA, bodyPlaceholders);
}
else {
body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
}
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
return new EmailContentResponse(subject, body, systemEmailTemplateResponse);
}

View File

@@ -33,10 +33,10 @@ public class SystemEmailTemplatesDao {
public SystemEmailTemplateResponse retrieveTemplate(SystemEmailTemplatesEntityTypeEnum type, HubEntity hub, Locale language) {
SystemEmailTemplatesEntity dbSystemEmailTemplatesEntity = null;
if(hub != null){
// dbSystemEmailTemplatesEntity = systemEmailTemplatesRespository
// .findByTypeAndCallId(type.getValue(), call.getId());
dbSystemEmailTemplatesEntity = systemEmailTemplatesRespository
.findByTypeAndHubEntityId(type.getValue(), hub.getId());
}
if(dbSystemEmailTemplatesEntity == null) {
if(dbSystemEmailTemplatesEntity == null){
dbSystemEmailTemplatesEntity = systemEmailTemplatesRespository
.findByType(type.getValue());
}

View File

@@ -20,6 +20,7 @@ import net.gepafin.tendermanagement.util.LoggingUtil;
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.ForbiddenAccessException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -597,5 +598,58 @@ public class UserDao {
return userResponseBeans;
}
public UserResponseBean updateUserDetails(HttpServletRequest request , Long userId, UpdateUserReqForBeneficiary userReq){
log.info("Updating user by beneficiary with ID: {}", userId);
UserEntity userEntity = validator.validateUserId(request, userId);
UserEntity oldUserEntity = Utils.getClonedEntityForData(userEntity);
log.info("Current user details: {}", userEntity);
log.info("New user details: {}", userReq);
HubEntity hubEntity = hubService.valdateHub(userEntity.getHub().getId());
String beneficiaryRoleType = RoleStatusEnum.ROLE_BENEFICIARY.getValue();
if (validator.checkIsBeneficiary()) {
// Validate if the new email already exists for another beneficiary in the same hub
boolean emailExistsForBeneficiary = userRepository.existsByEmailIgnoreCaseForBeneficiaries(
userReq.getEmail(), hubEntity.getUniqueUuid(), beneficiaryRoleType);
if (emailExistsForBeneficiary) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
}
setIfUpdated(userEntity::getEmail,userEntity::setEmail,userReq.getEmail()); // Only update email if role is beneficiary
}
BeneficiaryEntity oldBeneficiaryEntity = null;
if(userEntity.getBeneficiary()!=null) {
oldBeneficiaryEntity = Utils.getClonedEntityForData(userEntity.getBeneficiary());
setIfUpdated(userEntity.getBeneficiary()::getFirstName, userEntity.getBeneficiary()::setFirstName, userReq.getFirstName());
setIfUpdated(userEntity.getBeneficiary()::getLastName, userEntity.getBeneficiary()::setLastName, userReq.getLastName());
setIfUpdated(userEntity.getBeneficiary()::getOrganization, userEntity.getBeneficiary()::setOrganization, userReq.getOrganization());
setIfUpdated(userEntity.getBeneficiary()::getAddress, userEntity.getBeneficiary()::setAddress, userReq.getAddress());
setIfUpdated(userEntity.getBeneficiary()::getPhoneNumber, userEntity.getBeneficiary()::setPhoneNumber, userReq.getPhoneNumber());
setIfUpdated(userEntity.getBeneficiary()::getDateOfBirth, userEntity.getBeneficiary()::setDateOfBirth, userReq.getDateOfBirth());
setIfUpdated(userEntity.getBeneficiary()::getCity, userEntity.getBeneficiary()::setCity, userReq.getCity());
setIfUpdated(userEntity.getBeneficiary()::getCountry, userEntity.getBeneficiary()::setCountry, userReq.getCountry());
/** This code is responsible for adding a version history log for the "Update beneficiary details " operation **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(oldBeneficiaryEntity).newData(userEntity.getBeneficiary()).build());
}
userEntity = userRepository.save(userEntity);
/** This code is responsible for adding a version history log for the "Update user details by beneficiary" operation **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.INSERT).oldData(oldUserEntity).newData(userEntity).build());
return convertUserEntityToUserResponse(userEntity);
}
}

View File

@@ -91,5 +91,11 @@ public class CallEntity extends BaseEntity {
@Column(name = "evaluationVersion")
private String evaluationVersion;
@Column(name = "NUMBER_OF_CHECK")
private Long numberOfCheck;
@Column(name = "PRODUCT_ID")
private Long productId;
}

View File

@@ -38,7 +38,12 @@ public class SystemEmailTemplatesEntity extends BaseEntity {
@Column(name = "email_scenario")
private String emailScenario;
@ManyToOne
@JoinColumn(name = "HUB_ID")
private HubEntity hubEntity;
public enum SystemEmailTemplatesEntityTypeEnum {
APPLICATION_SUBMISSION_TO_USER_AND_COMPANY("APPLICATION_SUBMISSION_TO_USER_AND_COMPANY"),

View File

@@ -149,6 +149,7 @@ public enum UserActionContextEnum {
GET_AMENDMENT_DETAILS("GET_AMENDMENT_DETAILS"),
GET_DASHBOARD_WIDGET_FOR_PRE_INSTRUCTOR("GET_DASHBOARD_WIDGET_FOR_PRE_INSTRUCTOR"),
GET_APPLICATION_DETAILS_FOR_EVALUATION("GET_APPLICATION_DETAILS_FOR_EVALUATION"),
GET_STATISTICS_PAGE_FOR_BENEFICIARY("GET_STATISTICS_PAGE_FOR_BENEFICIARY"),
/** Evaluation criteria action context **/
GET_EVALUATION_CRITERIA("GET_EVALUATION_CRITERIA"),

View File

@@ -10,5 +10,7 @@ public class ApplicationPageableRequestBean {
private GlobalFilters globalFilters;
private Integer daysRange;
private List<ApplicationStatusTypeEnum> status;
}

View File

@@ -24,6 +24,10 @@ public class CreateCallRequestStep1 {
private BigDecimal amountMax;
private Long numberOfCheck;
private Long productId;
private List<LookUpDataReq> aimedTo;
private String documentationRequested;

View File

@@ -41,6 +41,10 @@ public class UpdateCallRequestStep1 {
private List<FaqReq> faq;
private Long numberOfCheck;
private Long productId;
private EvaluationVersionEnum evaluationVersion;
}

View File

@@ -0,0 +1,18 @@
package net.gepafin.tendermanagement.model.request;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class UpdateUserReqForBeneficiary {
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private String organization;
private String address;
private String city;
private String country;
private LocalDateTime dateOfBirth;
}

View File

@@ -44,5 +44,7 @@ public class ApplicationEvaluationFormResponse {
private LocalDateTime dateAccepted;
private LocalDateTime dateRejected;
private EvaluationVersionEnum evaluationVersion;
private BigDecimal numberOfCheck;
private BigDecimal productId;
}

View File

@@ -44,6 +44,8 @@ public class ApplicationEvaluationResponse {
private BigDecimal amountAccepted;
private LocalDateTime dateAccepted;
private LocalDateTime dateRejected;
private Long numberOfCheck;
private Long productId;
private EvaluationVersionEnum evaluationVersion;
}

View File

@@ -0,0 +1,19 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Builder;
import lombok.Data;
import java.math.BigDecimal;
@Data
@Builder
public class ApplicationWidget {
private Long submittedApplication;
private BigDecimal successRate;
private Long approvedApplication;
private BigDecimal totalAmountFinanced;
}

View File

@@ -5,6 +5,7 @@ import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
import net.gepafin.tendermanagement.enums.EvaluationVersionEnum;
import net.gepafin.tendermanagement.model.BaseBean;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@@ -23,6 +24,8 @@ public class AssignedApplicationsResponse extends BaseBean {
private LocalDateTime callEndDate;
private String companyName;
private LocalDateTime evaluationEndDate;
private Long numberOfCheck;
private Long productId;
private EvaluationVersionEnum evaluationVersion;
}

View File

@@ -0,0 +1,17 @@
package net.gepafin.tendermanagement.model.response;
import lombok.Builder;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Map;
@Data
@Builder
public class BeneficiaryStatisticsResponseBean {
private ApplicationWidget applicationWidget;
private Map<String, Object> applicationWidgetBars;
}

View File

@@ -57,5 +57,9 @@ public class CallDetailsResponseBean {
private Long preferredCallId;
private Long numberOfCheck;
private Long productId;
private EvaluationVersionEnum evaluationVersion;
}

View File

@@ -50,6 +50,10 @@ public class CallResponse {
private String phoneNumber;
private Long numberOfCheck;
private Long productId;
@JsonSerialize(using = DynamicLocalTimeSerializer.class)
private LocalTime startTime;

View File

@@ -94,5 +94,72 @@ public interface ApplicationRepository extends JpaRepository<ApplicationEntity,
@Query("SELECT a.id FROM ApplicationEntity a WHERE a.hubId = :hubId AND a.isDeleted = false")
List<Long> findApplicationIdsByHubId(@Param("hubId") Long hubId);
@Query("SELECT CASE WHEN COUNT(CASE WHEN a.submissionDate IS NOT NULL THEN 1 ELSE NULL END) > 0 THEN " +
"CAST((SUM(CASE WHEN a.status = 'APPROVED' THEN 1 ELSE 0 END) * 100.0) / " +
"COUNT(CASE WHEN a.submissionDate IS NOT NULL THEN 1 ELSE NULL END) AS BigDecimal) " +
"ELSE CAST(0 AS BigDecimal) END " +
"FROM ApplicationEntity a " +
"WHERE a.hubId = :hubId AND a.userId = :userId AND a.userWithCompany.id = :userWithCompanyId " +
"AND a.isDeleted = false")
BigDecimal findSuccessRateByHubIdAndUserIdAndUserWithCompanyId(
@Param("hubId") Long hubId,
@Param("userId") Long userId,
@Param("userWithCompanyId") Long userWithCompanyId);
@Query("SELECT a.status, COUNT(a.id) FROM ApplicationEntity a WHERE a.isDeleted = false AND a.userId = :userId AND a.userWithCompany.id = :userWithCompanyId AND a.call.hub.id = :hubId GROUP BY a.status")
List<Object[]> findApplicationsByStatusAndUserIdAndUserWithCompanyId(@Param("hubId") Long hubId,
@Param("userId") Long userId,
@Param("userWithCompanyId") Long userWithCompanyId);
@Query("""
SELECT TO_CHAR(a.submissionDate, 'Mon') AS month,
SUM(a.amountRequested) AS totalRequested,
SUM(a.amountAccepted) AS totalApproved
FROM ApplicationEntity a
WHERE a.isDeleted = false
AND a.status = 'APPROVED'
AND a.call.hub.id = :hubId
AND a.userId = :userId
AND a.userWithCompany.id = :userWithCompanyId
GROUP BY TO_CHAR(a.submissionDate, 'Mon'), EXTRACT(YEAR FROM a.submissionDate), EXTRACT(MONTH FROM a.submissionDate)
ORDER BY EXTRACT(YEAR FROM a.submissionDate), EXTRACT(MONTH FROM a.submissionDate)
""")
List<Object[]> findRequestedVsApprovedAmountsPerMonth(
@Param("hubId") Long hubId,
@Param("userId") Long userId,
@Param("userWithCompanyId") Long userWithCompanyId
);
@Query("SELECT COUNT(a) FROM ApplicationEntity a " +
"WHERE a.hubId = :hubId " +
"AND a.userId = :userId " +
"AND a.userWithCompany.id = :userWithCompanyId " +
"AND a.isDeleted = false " +
"AND a.status IN :statusList " +
"AND a.submissionDate IS NOT NULL")
Long countSubmittedApplicationsByHubIdAndUserId(
@Param("hubId") Long hubId,
@Param("userId") Long userId,
@Param("userWithCompanyId") Long userWithCompanyId,
@Param("statusList") List<String> statusList
);
@Query("SELECT COUNT(a) FROM ApplicationEntity a " +
"WHERE a.hubId = :hubId " +
"AND a.userId = :userId " +
"AND a.userWithCompany.id = :userWithCompanyId " +
"AND a.status = :status " +
"AND a.isDeleted = false")
Long countSubmittedApplicationsByHubIdAndUserIdAndStatus(
@Param("hubId") Long hubId,
@Param("userId") Long userId,
@Param("userWithCompanyId") Long userWithCompanyId,
@Param("status") String status);
@Query("SELECT SUM(a.amountAccepted) FROM ApplicationEntity a WHERE a.hubId = :hubId AND a.userId = :userId AND a.status = 'APPROVED' AND a.userWithCompany.id = :userWithCompanyId AND a.isDeleted = false")
BigDecimal sumAmountRequestedByHubIdAndUserId(@Param("hubId") Long hubId, @Param("userId") Long userId, @Param("userWithCompanyId") Long userWithCompanyId);
List<ApplicationEntity> findByUserIdAndUserWithCompany_IdAndCall_IdAndIsDeletedFalseAndStatusNot(
Long userId, Long userWithCompanyId, Long callId, String status
);
}

View File

@@ -13,5 +13,8 @@ public interface SystemEmailTemplatesRespository extends JpaRepository<SystemEma
@Query("select s from SystemEmailTemplatesEntity s where s.type=:type and s.isDeleted =false and s.system = true")
SystemEmailTemplatesEntity findByType(@Param("type") String type);
@Query("select s from SystemEmailTemplatesEntity s where s.type=:type and s.hubEntity.id=:hubId and s.isDeleted =false and s.system = false")
SystemEmailTemplatesEntity findByTypeAndHubEntityId(@Param("type") String type, @Param("hubId") Long hubId);
}

View File

@@ -18,4 +18,6 @@ public interface DashboardService {
public PreInstructorWidgetResponseBean getDashboardWidgetForPreInstructor(HttpServletRequest request,Long userId);
public AssignedApplicationWidgetResponseBean getApplicationDetailsForEvaluation(HttpServletRequest request);
public BeneficiaryStatisticsResponseBean getStatisticsPageForBeneficiary(HttpServletRequest request,Long companyId);
}

View File

@@ -47,4 +47,6 @@ public interface UserService {
public UserEntity getUserEntityById(Long userId);
List<UserResponseBean> getAllUsers(HttpServletRequest request, List<Long> roleIds);
UserResponseBean updateUserDetails(HttpServletRequest request, Long userId, UpdateUserReqForBeneficiary userReq);
}

View File

@@ -57,4 +57,11 @@ public class DashboardServiceImpl implements DashboardService {
UserEntity userEntity = validator.validateUser(request);
return dashboardDao.getApplicationDetailsForEvaluation(userEntity);
}
@Override
public BeneficiaryStatisticsResponseBean getStatisticsPageForBeneficiary(HttpServletRequest request, Long companyId) {
UserEntity userEntity = validator.validateUser(request);
CompanyEntity company = validator.validateUserWithCompany(request, companyId);
return dashboardDao.getStatisticsPageForBeneficiary(userEntity,company);
}
}

View File

@@ -130,4 +130,10 @@ public class UserServiceImpl implements UserService {
UserEntity user=validator.validateUser(request);
return userDao.getAllUsers(user, roleIds);
}
@Override
@Transactional(rollbackFor = Exception.class)
public UserResponseBean updateUserDetails(HttpServletRequest request, Long userId, UpdateUserReqForBeneficiary userReq) {
return userDao.updateUserDetails(request , userId, userReq);
}
}

View File

@@ -2,6 +2,10 @@ package net.gepafin.tendermanagement.util;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -9,12 +13,18 @@ import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.FormDao;
import net.gepafin.tendermanagement.dao.VatCheckDao;
import net.gepafin.tendermanagement.entities.ApplicationFormEntity;
import net.gepafin.tendermanagement.entities.ApplicationFormFieldEntity;
import net.gepafin.tendermanagement.model.request.ApplicationFormFieldRequestBean;
import net.gepafin.tendermanagement.model.request.ContentRequestBean;
import net.gepafin.tendermanagement.model.response.ContentResponseBean;
import net.gepafin.tendermanagement.model.response.SettingResponseBean;
import net.gepafin.tendermanagement.repositories.ApplicationFormFieldRepository;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import net.gepafin.tendermanagement.web.rest.api.errors.ValidationException;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
@@ -163,11 +173,6 @@ public class FieldValidator {
throw new RuntimeException(e);
}
break;
default:
// If the custom rule is unknown, just log or add an error (optional)
errors.add(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_FIELD_CUSTOM), fieldId, customRule));
break;
}
return this;
@@ -219,31 +224,47 @@ public class FieldValidator {
return;
}
for (int rowIndex = 0; rowIndex < fieldValueList.size(); rowIndex++) {
Map<String, Object> field = fieldValueList.get(rowIndex);
// for (int rowIndex = 0; rowIndex < fieldValueList.size(); rowIndex++) {
// Map<String, Object> field = fieldValueList.get(rowIndex);
//
// boolean hasSingleNonNullPredefinedFalse = false;
//
// for (Map.Entry<String, Boolean> entry : stateFieldMap.entrySet()) {
// String stateKey = entry.getKey();
// Boolean isPredefinedFalse = Boolean.FALSE.equals(entry.getValue());
//
// if (isPredefinedFalse) {
// Object fieldValue = field.get(stateKey);
// if (fieldValue != null && !StringUtils.isEmpty(fieldValue.toString())) {
// hasSingleNonNullPredefinedFalse = true;
// break;
// }
// }
// }
//
// if (!hasSingleNonNullPredefinedFalse) {
// errors.add(MessageFormat.format(
// Translator.toLocale(GepafinConstant.VALIDATION_IN_TABLE),
// fieldId));
// break;
// }
//
// }
boolean hasSingleNonNullPredefinedFalse = false;
for (Map.Entry<String, Boolean> entry : stateFieldMap.entrySet()) {
String stateKey = entry.getKey();
Boolean isPredefinedFalse = Boolean.FALSE.equals(entry.getValue());
if (isPredefinedFalse) {
Object fieldValue = field.get(stateKey);
if (fieldValue != null && !StringUtils.isEmpty(fieldValue.toString())) {
hasSingleNonNullPredefinedFalse = true;
break;
}
}
}
if (!hasSingleNonNullPredefinedFalse) {
errors.add(MessageFormat.format(
Translator.toLocale(GepafinConstant.VALIDATION_IN_TABLE),
fieldId));
break;
}
boolean hasAtLeastOneNonEmptyPredefinedFalse = fieldValueList.stream()
.anyMatch(field -> stateFieldMap.entrySet().stream()
.filter(entry -> Boolean.FALSE.equals(entry.getValue())) // Check only predefined: false fields
.anyMatch(entry -> {
Object fieldValue = field.get(entry.getKey());
return fieldValue != null && !StringUtils.isEmpty(fieldValue.toString());
})
);
if (!hasAtLeastOneNonEmptyPredefinedFalse) {
errors.add(MessageFormat.format(
Translator.toLocale(GepafinConstant.VALIDATION_IN_TABLE),
fieldId));
}
} catch (Exception e) {
@@ -272,5 +293,17 @@ public class FieldValidator {
// Now contentRequestBean is populated with the data from the JSON
return contentRequestBean;
}
public FieldValidator formulaValidation(Object fieldValue, double finalValue, String label) {
if (fieldValue != null) {
try {
double fieldValueAsDouble = Double.parseDouble(fieldValue.toString()); // Convert fieldValue to double
if (Double.compare(finalValue, fieldValueAsDouble) != 0) { // Compare doubles safely
errors.add(MessageFormat.format(Translator.toLocale(GepafinConstant.FORMULA_AMOUNT_NOT_MATCHED), label));
}
} catch (NumberFormatException e) {
throw new CustomValidationException(Status.BAD_REQUEST, "Invalid field value: " + fieldValue);
}
}
return this;
}
}

View File

@@ -11,6 +11,7 @@ import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -27,6 +28,8 @@ import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.model.request.GlobalFilters;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -54,6 +57,9 @@ import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import static org.apache.commons.lang3.StringUtils.isEmpty;
@@ -753,6 +759,25 @@ public class Utils {
private static Map<String, Object> defaultErrorResponse() {
return Collections.singletonMap("message", Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
}
public static List<String> extractValues(String input) {
List<String> extractedValues = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{(.*?)\\}"); // Regex to match {value}
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
extractedValues.add(matcher.group(1)); // Extract value inside {}
}
return extractedValues;
}
public static double evaluateExpression(String expression) {
try {
Expression exp = new ExpressionBuilder(expression).build();
return exp.evaluate();
} catch (Exception e) {
e.printStackTrace();
return Double.NaN; // Return NaN if the expression is invalid
}
}
public static boolean isNumeric(String input) {
if (input == null || input.trim().isEmpty()) {
return false;

View File

@@ -94,7 +94,25 @@ public interface DashboardApi {
produces = { "application/json" })
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN') || hasRole('ROLE_INSTRUCTOR_MANAGER')|| hasRole('ROLE_PRE_INSTRUCTOR')")
ResponseEntity<Response<AssignedApplicationWidgetResponseBean>> getApplicationDetailsForEvaluation(HttpServletRequest request);
@Operation(summary = "Api to get Statistics page for beneficiary",
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 = "/beneficiary/statistic/company/{companyId}",
produces = { "application/json" })
ResponseEntity<Response<BeneficiaryStatisticsResponseBean>> getStatisticsPageForBeneficiary(HttpServletRequest request,
@Parameter(description = "The company id", required = true) @PathVariable(value = "companyId", required = true) Long companyId);
@Operation(summary = "Api to get dashboard widget for pre instructor",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@@ -104,11 +122,8 @@ public interface DashboardApi {
@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 = "/instructor/amendment",
@GetMapping(value = "/instructor/amendment",
produces = { "application/json" })
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN') || hasRole('ROLE_INSTRUCTOR_MANAGER')|| hasRole('ROLE_PRE_INSTRUCTOR')")
ResponseEntity<Response<PreInstructorWidgetResponseBean>> getDashboardWidgetForPreInstructor(HttpServletRequest request, @Parameter(description = "The User ID", required = false) @RequestParam(value = "userId",required = false) Long userId);
}

View File

@@ -47,7 +47,7 @@ public interface UserApi {
return new ResponseEntity<Response<JWTToken>>(HttpStatus.NOT_IMPLEMENTED);
}
@Operation(summary = "Api to update user",
@Operation(summary = "Api to update user (Only for super admin)",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@@ -243,6 +243,24 @@ public interface UserApi {
@RequestMapping("favicon.ico")
@ResponseBody
void returnNoFavicon();
@Operation(summary = "Api to update user",
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)}))})
@RequestMapping(value = "/{userId}/update-details",
produces = {"application/json"},
method = RequestMethod.PUT)
default ResponseEntity<Response<UserResponseBean>> updateUserDetails(HttpServletRequest request,
@Parameter(description = "The user id", required = true) @PathVariable("userId") Long userId,
@Parameter(description = "User request object", required = true) @Valid @RequestBody UpdateUserReqForBeneficiary userReq) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}

View File

@@ -93,6 +93,15 @@ public class DashboardApiController implements DashboardApi {
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(widgetResponseBean, Status.SUCCESS, Translator.toLocale(GepafinConstant.DASHBOARD_WIDGET_FETCHED_SUCCESSFULLY)));
}
@Override
public ResponseEntity<Response<BeneficiaryStatisticsResponseBean>> getStatisticsPageForBeneficiary(HttpServletRequest request, Long companyId) {
/** This code is responsible for creating user action logs for the "Get statistics page for beneficiary" operation. **/
loggingUtil.logUserAction(UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.VIEW).actionContext(UserActionContextEnum.GET_STATISTICS_PAGE_FOR_BENEFICIARY).build());
BeneficiaryStatisticsResponseBean widgetResponseBean= dashboardService.getStatisticsPageForBeneficiary(request, companyId);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(widgetResponseBean, Status.SUCCESS, Translator.toLocale(GepafinConstant.DASHBOARD_WIDGET_FETCHED_SUCCESSFULLY)));
}
}

View File

@@ -247,5 +247,21 @@ public class UserApiController implements UserApi {
public void returnNoFavicon() {
// Do nothing
}
@Override
public ResponseEntity<Response<UserResponseBean>> updateUserDetails(HttpServletRequest request,
@PathVariable("userId") Long userId,
@Valid @RequestBody UpdateUserReqForBeneficiary userReq) {
log.info("Update User for Beneficiary- User ID: {}, Request Body: {}", userId, userReq);
/** This code is responsible for "Updating user details by beneficiary" operation. **/
loggingUtil.logUserAction(UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.UPDATE)
.actionContext(UserActionContextEnum.UPDATE_USER_DETAILS).build());
UserResponseBean updatedUser = userService.updateUserDetails(request, userId, userReq);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(updatedUser, Status.SUCCESS, Translator.toLocale(GepafinConstant.USER_UPDATED_SUCCESS_MSG)));
}
}