Resolved Conflicts

This commit is contained in:
Piyush
2025-05-28 13:01:49 +05:30
107 changed files with 3355 additions and 434 deletions

View File

@@ -1,10 +1,15 @@
package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.*;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
@@ -23,15 +28,14 @@ import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.LoggingUtil;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.util.*;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.lang3.StringUtils;
import org.h2.util.IOUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -49,17 +53,17 @@ import jakarta.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -69,7 +73,6 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.hibernate.validator.internal.engine.messageinterpolation.el.RootResolver.FORMATTER;
@Component
public class ApplicationDao {
@@ -133,6 +136,9 @@ public class ApplicationDao {
@Value("${call.id}")
private String callId;
@Value("${sviluppumbriaUuid}")
private String sviluppumbriaUuid;
@Autowired
private AmazonS3Service amazonS3Service;
@@ -196,6 +202,16 @@ public class ApplicationDao {
@Autowired
private ApplicationViewRepository applicationViewRepository;
@Autowired
private ApplicationFormViewRepository applicationFormViewRepository;
@Autowired
private FormRepository formRepository;
@Autowired
private ApplicationEvaluationDao applicationEvaluationDao;
public final Random random = new Random();
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
log.info("Starting createApplication: formId={}, applicationId={}", formId, applicationId);
@@ -952,16 +968,20 @@ public class ApplicationDao {
}
}
public String generateRandomFiveDigitNumber() {
int number = 10000 + random.nextInt(90000); // Generates a number from 10000 to 99999
return String.valueOf(number);
}
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
log.info("Updating status for Application id : " + applicationId);
ApplicationEntity applicationEntity = validateApplication(applicationId);
checkCallEndDate(applicationEntity.getCall());
log.info("Call end date verified successfully | callId: {}", applicationEntity.getCall().getId());
//cloned entity for old application data
ApplicationEntity oldApplicationEntity = Utils.getClonedEntityForData(applicationEntity);
HubEntity hub=hubService.valdateHub(applicationEntity.getHubId());
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
@@ -973,11 +993,25 @@ public class ApplicationDao {
log.warn("Requested status is the same as current status | applicationId: {}, status: {}", applicationId, status);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_IN_PREVIOUS_STATUS));
}
if (status.equals(ApplicationStatusTypeEnum.APPOINTMENT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.NDG.getValue()))){
String appointmentId = generateRandomFiveDigitNumber();
applicationEntity.setAppointmentId(appointmentId);
applicationEntity.setStatus(ApplicationStatusTypeEnum.APPOINTMENT.getValue());
}
if (status.equals(ApplicationStatusTypeEnum.SUBMIT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
// callService.validatePublishedCall(applicationEntity.getCall().getId(), userEntity.getHub().getId());
checkCallEndDate(applicationEntity.getCall());
Long protocolNumber = protocolDao.getProtocolNumber(userEntity.getHub());
ProtocolEntity protocolEntity = protocolDao.createProtocolEntity(applicationEntity, protocolNumber, userEntity.getHub().getId(),true);
protocolDao.saveProtocolEntity(protocolEntity);
applicationEntity.setProtocol(protocolEntity);
if(Boolean.TRUE.equals(hub.getUniqueUuid().equals(sviluppumbriaUuid))) {
protocolEntity = protocolDao.createExternalProtocol(applicationEntity, company, protocolEntity);
}
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(protocolEntity.getCreatedDate());
applicationEntity = applicationRepository.save(applicationEntity);
@@ -988,16 +1022,18 @@ public class ApplicationDao {
loggingUtil.addVersionHistory(
VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplicationEntity).newData(applicationEntity).build());
sendMailToUserAndCompany(userEntity, applicationEntity);
sendMailToUserAndCompany(userEntity, applicationEntity,company);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
applicationEntity.setStatus(status.getValue());
log.info("Status updated to SUBMIT for applicationId: " + applicationId);
}
if (status.equals(ApplicationStatusTypeEnum.DRAFT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.AWAITING.getValue()))) {
checkCallEndDate(applicationEntity.getCall());
applicationEntity.setStatus(status.getValue());
log.info("Status updated to DRAFT for applicationId: " + applicationId);
}
if (status.equals(ApplicationStatusTypeEnum.AWAITING) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
checkCallEndDate(applicationEntity.getCall());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository.findByApplicationIdAndStatus(applicationId,
ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
deleteSignedDocumentFromS3(applicationSignedDocument);
@@ -1099,10 +1135,9 @@ public class ApplicationDao {
}
}
private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity) {
private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity,CompanyEntity company) {
log.info("Preparing to send submission email | applicationId: {}, userId: {}", applicationEntity.getId(), userEntity.getId());
CallEntity call =applicationEntity.getCall();
CompanyEntity company=companyService.validateCompany(applicationEntity.getCompanyId());
UserWithCompanyEntity userWithCompany=companyService.getUserWithCompany(userEntity.getId(),company.getId());
ProtocolEntity protocol= applicationEntity.getProtocol();
HubEntity hub = hubService.valdateHub(applicationEntity.getHubId());
@@ -1130,7 +1165,7 @@ public class ApplicationDao {
if (userEntity.getBeneficiary() != null) {
emailLogRequest.setRecipientType(RecipientTypeEnum.BENEFICIARY);
email = userEntity.getBeneficiary().getEmail();
emailLogRequest.setUserId(userEntity.getBeneficiary().getId());
emailLogRequest.setRecipientId(userEntity.getBeneficiary().getId());
}
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(email),emailLogRequest);
List<String> recipientEmails = new ArrayList<>();
@@ -1179,24 +1214,6 @@ public class ApplicationDao {
EmailLogRequest emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,userEntity.getEmail(),userEntity.getId(),applicationEntity.getId(),null,applicationEntity.getCall().getId());
// 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(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())
@@ -1225,6 +1242,12 @@ public class ApplicationDao {
log.info("Existing active signed document found and will be deleted | applicationId: {}, fileName: {}", applicationId, applicationSignedDocument.getFileName());
deleteSignedDocumentFromS3(applicationSignedDocument);
}
String hash ="";
try {
hash = FileHashUtil.calculateSHA256(file.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = uploadFileOnAmazonS3ForUserSignedDocument(file, applicationEntity.getCall().getId(), applicationId);
log.info("File uploaded to S3 successfully | applicationId: {}", applicationId);
applicationSignedDocument = new ApplicationSignedDocumentEntity();
@@ -1232,6 +1255,7 @@ public class ApplicationDao {
applicationSignedDocument.setFileName(uploadFileOnAmazonS3.getFileName());
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
applicationSignedDocument.setFileHash(hash);
applicationSignedDocument = applicationSignedDocumentRepository.save(applicationSignedDocument);
/** This code is responsible for adding a version history log for the "assign application document" operation. **/
@@ -1307,6 +1331,7 @@ public class ApplicationDao {
.setStatus(ApplicationSignedDocumentStatusEnum.valueOf(applicationSignedDocument.getStatus()));
applicationSignedDocumentResponse.setCreatedDate(applicationSignedDocument.getCreatedDate());
applicationSignedDocumentResponse.setUpdatedDate(applicationSignedDocument.getUpdatedDate());
applicationSignedDocumentResponse.setFileHash(applicationSignedDocument.getFileHash());
return applicationSignedDocumentResponse;
}
@@ -1885,4 +1910,429 @@ public class ApplicationDao {
responseBean.setDateRejected(applicationView.getDateRejected());
return responseBean;
}
public List<ApplicationFormView> getApplicationFormData(Long callId) {
List<ApplicationFormView> applicationFormViews=new ArrayList<>();
applicationFormViews= applicationFormViewRepository.findByCallId(callId);
return applicationFormViews;
}
private List<Method> getStaticGetterMethods() {
List<String> excluded = Arrays.asList(
GepafinConstant.GET_FIELD_TYPE,GepafinConstant.GET_APPLICATION_FORM_ID,GepafinConstant.GET_ID,GepafinConstant.GET_CLASS,GepafinConstant.GET_FORM_ID,GepafinConstant.GET_FIELD_ID,GepafinConstant.GET_FIELD_LABEL,GepafinConstant.GET_FIELD_VALUE,GepafinConstant.GET_REPORT_HEADER,GepafinConstant.GET_REPORT_ENABLE
);
Method applicationIdMethod = null;
List<Method> methods = new ArrayList<>();
for (Method m : ApplicationFormView.class.getMethods()) {
if (m.getName().equals(GepafinConstant.GET_APPLICATION_ID)) {
applicationIdMethod = m;
} else if (m.getName().startsWith(GepafinConstant.GET) && m.getParameterCount() == 0 && !excluded.contains(m.getName())) {
methods.add(m);
}
}
methods.sort(Comparator.comparing(Method::getName)); // Sort remaining
if (applicationIdMethod != null) {
methods.add(0, applicationIdMethod); // Add it to the beginning
}
return methods;
}
private String methodToHeader(Method method) {
String name = method.getName().substring(3); // strip "get"
return Arrays.stream(name.split("(?=[A-Z])"))
.map(String::toLowerCase)
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));
}
private String invokeGetter(ApplicationFormView view, Method method) {
try {
Object value = method.invoke(view);
if (value == null) return "";
String stringValue;
if (value instanceof LocalDate) {
stringValue = ((LocalDate) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} else if (value instanceof LocalDateTime) {
stringValue = ((LocalDateTime) value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} else if (value instanceof Date) {
stringValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
} else {
stringValue = value.toString();
}
// Wrap it in ="..." to make Excel treat it as a literal string
return "=\"" + stringValue.replace("\"", "\"\"") + "\"";
} catch (Exception e) {
return "";
}
}
public byte[] exportCsv(Long callId) {
List<ApplicationFormView> results = getApplicationFormData(callId);
Map<Long, ApplicationFormView> appInfo = new HashMap<>();
Map<Long, Map<String, String>> appFieldValues = new LinkedHashMap<>();
Set<String> tableFieldIds = new HashSet<>();
Map<String, String> fieldIdToLabel = new LinkedHashMap<>();
for (ApplicationFormView row : results) {
appInfo.putIfAbsent(row.getApplicationId(), row);
String label=row.getReportHeader();
if(Boolean.TRUE.equals(StringUtils.isEmpty(label))){
label=row.getFieldLabel();
}
fieldIdToLabel.putIfAbsent(row.getFieldId(), label);
if (GepafinConstant.TABLE.equalsIgnoreCase(row.getFieldType())) {
tableFieldIds.add(row.getFieldId());
continue;
}
String value = Optional.ofNullable(row.getFieldValue())
.map(v -> v.startsWith("\"") && v.endsWith("\"") ? v.substring(1, v.length() - 1) : v)
.orElse("");
appFieldValues
.computeIfAbsent(row.getApplicationId(), k -> new LinkedHashMap<>())
.merge(row.getFieldId(), value, (v1, v2) -> v1.equals(v2) ? v1 : String.join(", ", v1, v2));
}
Map<String, List<String>> tableHeadersByFieldId = new LinkedHashMap<>();
Map<Long, Map<String, String>> tableDataByApp = new HashMap<>();
prepareTableFieldData(results, tableFieldIds, tableHeadersByFieldId, tableDataByApp);
// Final header construction
List<Method> staticMethods = getStaticGetterMethods();
List<String> staticHeaders = staticMethods.stream().map(this::methodToHeader).toList();
List<String> dynamicHeaders = new ArrayList<>();
for (String fieldId : fieldIdToLabel.keySet()) {
if (tableHeadersByFieldId.containsKey(fieldId)) {
dynamicHeaders.addAll(tableHeadersByFieldId.get(fieldId));
} else {
dynamicHeaders.add(fieldIdToLabel.get(fieldId));
}
}
List<String> allHeaders = new ArrayList<>(staticHeaders);
allHeaders.addAll(dynamicHeaders);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (CSVPrinter printer = new CSVPrinter(new OutputStreamWriter(out), CSVFormat.DEFAULT.withHeader(allHeaders.toArray(new String[0])))) {
for (Long appId : appFieldValues.keySet()) {
ApplicationFormView appRow = appInfo.get(appId);
Map<String, String> flatFieldVals = appFieldValues.get(appId);
Map<String, String> tableVals = tableDataByApp.getOrDefault(appId, Collections.emptyMap());
List<String> row = new ArrayList<>();
for (Method method : staticMethods) {
row.add(invokeGetter(appRow, method));
}
for (String fieldId : fieldIdToLabel.keySet()) {
if (tableHeadersByFieldId.containsKey(fieldId)) {
for (String header : tableHeadersByFieldId.get(fieldId)) {
row.add(tableVals.getOrDefault(header, ""));
}
} else {
row.add(flatFieldVals.getOrDefault(fieldId, ""));
}
}
printer.printRecord(row);
}
} catch (IOException e) {
throw new RuntimeException("CSV generation failed", e);
}
return out.toByteArray();
}
private Map<String, String> extractTableData(String fieldType,
ContentResponseBean content, String fieldValue) {
if (content == null) return Map.of();
Map<String, String> result = new LinkedHashMap<>();
List<Map<String, Object>> rows = null;
try {
rows = GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(fieldType)
? Utils.convertJsonToListMap(String.valueOf(PdfUtils.extractRows(fieldValue)))
: Utils.convertJsonToListMap(fieldValue);
} catch (Exception e) {
throw new RuntimeException(e);
}
Map<String, String> fieldLabelMap = new LinkedHashMap<>();
Set<String> predefinedIds = new LinkedHashSet<>();
Set<String> dynamicIds = new LinkedHashSet<>();
Set<String> numericFormulaIds = new LinkedHashSet<>();
for (SettingResponseBean setting : content.getSettings()) {
String settingName = setting.getName();
if(settingName.equals(GepafinConstant.REPORT_ENABLE)){
Boolean enable= (Boolean) setting.getValue();
if(Boolean.FALSE.equals(enable)){
return null;
}
}
if (Boolean.TRUE.equals(GepafinConstant.TABLE_COLUMNS.equals(settingName)) || Boolean.TRUE.equals(GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(settingName))) {
Map<String, Object> valueMap = (Map<String, Object>) setting.getValue();
if (valueMap == null) continue;
List<Map<String, Object>> columns = (List<Map<String, Object>>) valueMap.get(GepafinConstant.STATE_FIELD_DATA);
if (columns != null) {
for (Map<String, Object> col : columns) {
String id = String.valueOf(col.get(GepafinConstant.NAME));
if (Boolean.FALSE.equals(col.get(GepafinConstant.PREDEFINED))) {
if (GepafinConstant.NUMERIC.equals(col.get(GepafinConstant.FIELD_TYPE)) && Boolean.TRUE.equals(col.get(GepafinConstant.ENABLE_FORMULA))) {
numericFormulaIds.add(id);
}
}
}
}
}
if (Boolean.TRUE.equals(GepafinConstant.REPORT_COLUMNS.equals(settingName))) {
List<Map<String, Object>> reportColumns = (List<Map<String, Object>>) setting.getValue();
if (reportColumns != null) {
for (Map<String, Object> col : reportColumns) {
Boolean enableCsv = (Boolean) col.get(GepafinConstant.EBABLE_CSV);
if (Boolean.TRUE.equals(enableCsv)) {
String id = String.valueOf(col.get(GepafinConstant.NAME));
String fieldCsvLabel = col.get(GepafinConstant.LABEL_CSV) != null
? String.valueOf(col.get(GepafinConstant.LABEL_CSV))
: String.valueOf(col.get(GepafinConstant.LABEL));
fieldLabelMap.put(id, fieldCsvLabel);
if (Boolean.TRUE.equals(col.get(GepafinConstant.PREDEFINED))) {
predefinedIds.add(id);
} else {
dynamicIds.add(id);
}
}
}
}
}
}
if (predefinedIds.isEmpty()) {
return null;
}
for (Map<String, Object> row : rows) {
String prefix = predefinedIds.stream()
.map(id -> String.valueOf(row.getOrDefault(id, "")))
.filter(s -> !s.isBlank())
.findFirst().orElse("");
for (String dynId : dynamicIds) {
String dynLabel = fieldLabelMap.get(dynId);
for (String preId : predefinedIds.isEmpty() ? List.of("") : predefinedIds) {
String preLabel = fieldLabelMap.get(preId);
String key = dynLabel + " " + (preLabel != null ? preLabel + " " : "") + prefix;
result.put(key, String.valueOf(row.getOrDefault(dynId, "")));
}
}
}
// Add totals for numeric formula-enabled columns
for (String dynId : numericFormulaIds) {
double sum = rows.stream()
.mapToDouble(r -> {
try {
return Double.parseDouble(String.valueOf(r.getOrDefault(dynId, "0")));
} catch (NumberFormatException e) {
return 0.0;
}
}).sum();
String dynLabel = fieldLabelMap.get(dynId);
result.put("TOTAL " + dynLabel, String.valueOf(sum));
}
return result;
}
private void prepareTableFieldData(
List<ApplicationFormView> results,
Set<String> tableFieldIds,
Map<String, List<String>> tableHeadersByFieldId,
Map<Long, Map<String, String>> tableDataByApp) {
if (tableFieldIds.isEmpty()) return;
Map<Long, List<ApplicationFormView>> groupedByApp = results.stream()
.filter(r -> tableFieldIds.contains(r.getFieldId()))
.collect(Collectors.groupingBy(ApplicationFormView::getApplicationId));
for (Map.Entry<Long, List<ApplicationFormView>> entry : groupedByApp.entrySet()) {
Long appId = entry.getKey();
Map<String, String> flattenedAll = new LinkedHashMap<>();
for (ApplicationFormView row : entry.getValue()) {
formRepository.findById(row.getFormId()).ifPresent(form -> {
List<ContentResponseBean> contentList = Utils.convertJsonStringToList(form.getContent(), ContentResponseBean.class);
ContentResponseBean content = contentList.stream()
.filter(c -> c.getId().equals(row.getFieldId()))
.findFirst()
.orElse(null);
if (content == null) return;
content.getSettings().stream()
.filter(setting -> GepafinConstant.TABLE_COLUMNS.equals(setting.getName())
|| GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(setting.getName()))
.findFirst()
.ifPresent(setting -> {
Map<String, String> flattened = extractTableData(
row.getFieldType(),
content,
row.getFieldValue()
);
if (flattened != null) {
tableHeadersByFieldId.putIfAbsent(row.getFieldId(), new ArrayList<>(flattened.keySet()));
flattenedAll.putAll(flattened);
}
});
});
}
tableDataByApp.put(appId, flattenedAll);
}
}
public ApplicationResponse readmitApplication(HttpServletRequest request, Long applicationId) {
log.info("Re-admiting the Application with id : {}", applicationId);
ApplicationEntity applicationEntity = fetchRejectedApplication(applicationId);
if(applicationEntity == null){
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_NOT_FOUND_MSG));
}
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationEntity.getId())
.ifPresent(assignedApp -> processAssignedAppAndEvaluation(request, applicationEntity, assignedApp));
return getApplicationResponse(applicationEntity);
}
private ApplicationEntity fetchRejectedApplication(Long applicationId) {
return applicationRepository.findByIdAndStatusAndIsDeletedFalse(applicationId, ApplicationStatusTypeEnum.REJECTED.getValue());
}
private void processAssignedAppAndEvaluation(HttpServletRequest request, ApplicationEntity applicationEntity, AssignedApplicationsEntity assignedApp) {
applicationEvaluationRepository.findByAssignedApplicationsEntity_IdAndIsDeletedFalse(assignedApp.getId())
.ifPresent(eval -> reopenApplication(request, applicationEntity, assignedApp, eval));
}
private void reopenApplication(HttpServletRequest request, ApplicationEntity applicationEntity,
AssignedApplicationsEntity assignedApp, ApplicationEvaluationEntity evaluationEntity) {
ApplicationEntity oldApplication = Utils.getClonedEntityForData(applicationEntity);
AssignedApplicationsEntity oldAssignedApp = Utils.getClonedEntityForData(assignedApp);
ApplicationEvaluationEntity oldEvaluation = Utils.getClonedEntityForData(evaluationEntity);
updateApplicationStatus(applicationEntity);
updateAssignedApplicationStatus(assignedApp);
updateEvaluationEntity(applicationEntity.getHubId(), evaluationEntity);
saveEntities(applicationEntity, assignedApp, evaluationEntity);
/** This code is responsible for adding a version history log for the "Update Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldApplication).newData(applicationEntity).build());
/** This code is responsible for adding a version history log for the "Update Application Evaluation" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldEvaluation).newData(evaluationEntity).build());
/** This code is responsible for adding a version history log for the "Update Assigned Application" operation. **/
loggingUtil.addVersionHistory(VersionHistoryRequest.builder().request(request).actionType(VersionActionTypeEnum.UPDATE).oldData(oldAssignedApp).newData(assignedApp).build());
}
private void updateApplicationStatus(ApplicationEntity applicationEntity) {
applicationEntity.setStatus(ApplicationStatusTypeEnum.EVALUATION.getValue());
applicationEntity.setDateRejected(null);
}
private void updateAssignedApplicationStatus(AssignedApplicationsEntity assignedApp) {
assignedApp.setStatus(AssignedApplicationEnum.OPEN.getValue());
}
private void updateEvaluationEntity(Long hubId, ApplicationEvaluationEntity evaluationEntity) {
HubEntity hub = hubService.valdateHub(hubId);
Long evaluationDays = (hub != null) ? hub.getEvaluationExpirationDays() : 30L;
LocalDateTime now = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
evaluationEntity.setStatus(ApplicationEvaluationStatusTypeEnum.OPEN.getValue());
evaluationEntity.setClosingDate(null);
evaluationEntity.setActiveDays(null);
evaluationEntity.setEndDate(now.plusDays(evaluationDays));
evaluationEntity.setStartDate(now);
evaluationEntity.setRemainingDays(evaluationDays);
evaluationEntity.setSuspendedDays(0L);
evaluationEntity.setStopDateTime(null);
}
private void saveEntities(ApplicationEntity app, AssignedApplicationsEntity assignedApp, ApplicationEvaluationEntity eval) {
applicationRepository.save(app);
assignedApplicationsRepository.save(assignedApp);
applicationEvaluationRepository.save(eval);
}
public void sendApplicationSubmissionFailureEmail(EmailLogRequest emailLogRequest){
Long callId = emailLogRequest.getCallId();
CallEntity call = callService.validateCall(callId);
HubEntity hub = call.getHub();
Long userId = emailLogRequest.getUserId();
UserEntity user = userService.validateUser(userId);
Long applicationId = emailLogRequest.getApplicatioId();
ApplicationEntity applicationEntity = validateApplication(applicationId);
CompanyEntity company = companyService.validateCompany(applicationEntity.getCompanyId());
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_FAILURE_NOTIFICATION,
hub, null);
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{scenario}}",emailLogRequest.getEmailType().getValue());
bodyPlaceholders.put("{{call_name}}", call.getName());
bodyPlaceholders.put("{{application_id}}", applicationEntity.getId().toString());
bodyPlaceholders.put("{{company_name}}", company.getCompanyName());
bodyPlaceholders.put("{{protocol_number}}", applicationEntity.getProtocol().getProtocolNumber().toString());
bodyPlaceholders.put("{{user_action_id}}",emailLogRequest.getUserActionId().toString());
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
emailLogRequest=emailLogDao.createEmailLogRequest(systemEmailTemplateResponse.getEmailScenario(),RecipientTypeEnum.PROPERTIES,null,user.getEmail(),user.getId(),applicationEntity.getId(),null,callId);
emailLogRequest.setRecipientEmails(GepafinConstant.RINALDO_EMAIL);
emailNotificationDao.sendMail(hub.getId(), subject, body, List.of(GepafinConstant.RINALDO_EMAIL),emailLogRequest);
}
}