Resolved conflicts

This commit is contained in:
harish
2024-10-14 15:51:52 +05:30
46 changed files with 1945 additions and 44 deletions

View File

@@ -3,6 +3,8 @@ package net.gepafin.tendermanagement.dao;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum;
import net.gepafin.tendermanagement.enums.ApplicationSignedDocumentStatusEnum;
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
@@ -12,24 +14,31 @@ import net.gepafin.tendermanagement.model.request.ApplicationRequest;
import net.gepafin.tendermanagement.model.request.ApplicationRequestBean;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.*;
import net.gepafin.tendermanagement.service.AmazonS3Service;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.DocumentService;
import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.MailUtil;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import jakarta.persistence.criteria.Predicate;
import jakarta.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.time.LocalDateTime;
@@ -71,17 +80,45 @@ public class ApplicationDao {
@Autowired
private FlowDataRepository flowDataRepository;
@Autowired
private UserWithCompanyRepository userWithCompanyRepository;
@Autowired
private UserCompanyDelegationRepository userCompanyDelegationRepository;
@Autowired
private Validator validator;
@Autowired
private CompanyService companyService;
@Autowired
private ProtocolRepository protocolRepository;
@Autowired
private SystemEmailTemplatesService systemEmailTemplatesService;
@Autowired
private MailUtil mailUtil;
@Value("${default_System_Receiver_Email}")
private String defaultSystemReceiverEmail;
@Value("${gepafin_email}")
private String gepafinEmail;
@Value("${rinaldo_email}")
private String rinaldoEmail;
@Value("${carlo_email}")
private String carloEmail;
@Autowired
private AmazonS3Service amazonS3Service;
@Autowired
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
@Value("${aws.s3.url.folder.signed.document}")
private String signedDocumentS3Folder;
public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId, Long applicationId) {
@@ -523,21 +560,21 @@ public class ApplicationDao {
ApplicationRequest applicationRequest, Long callId, UserEntity userEntity) {
CallEntity call = callService.validateCall(callId);
// call = callService.validatePublishedCall(call.getId());
checkIfApplicationExists(call, companyEntity);
checkIfApplicationExists(call, companyEntity, userEntity);
ApplicationEntity applicationEntity = createApplicationEntity(userEntity, call, companyEntity);
applicationEntity.setComments(applicationRequest.getComments());
applicationEntity = saveApplicationEntity(applicationEntity);
ApplicationResponse applicationResponse = getApplicationResponse(applicationEntity);
return applicationResponse;
}
public void checkIfApplicationExists(CallEntity call, CompanyEntity companyEntity){
Optional<ApplicationEntity> applicationEntity=applicationRepository.findByCompanyIdAndCallIdAndIsDeletedFalse(companyEntity.getId(),call.getId());
public void checkIfApplicationExists(CallEntity call, CompanyEntity companyEntity, UserEntity userEntity){
Optional<ApplicationEntity> applicationEntity=applicationRepository.findByUserIdAndCompanyIdAndCallIdAndIsDeletedFalse(userEntity.getId(), companyEntity.getId(),call.getId());
if(applicationEntity.isPresent()){
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_EXISTS));
}
}
public ApplicationResponse updateApplicationStatus(Long applicationId, ApplicationStatusTypeEnum status) {
public ApplicationResponse updateApplicationStatus(UserEntity userEntity, Long applicationId, ApplicationStatusTypeEnum status) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE));
@@ -566,11 +603,13 @@ public class ApplicationDao {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
}
Integer maxProtocolNumber=protocolRepository.findMaxProtocolNumber();
Integer protocolNumber = (maxProtocolNumber != null) ? maxProtocolNumber + 1 : 10000;
Integer protocolNumber = (maxProtocolNumber != null) ? maxProtocolNumber + 1 : 1;
ProtocolEntity protocolEntity=createProtocolEntity(applicationEntity,protocolNumber);
applicationEntity.setProtocol(protocolEntity);
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
sendMailToUserAndCompany(userEntity, applicationEntity);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
} else {
applicationEntity.setStatus(status.getValue());
}
@@ -579,7 +618,7 @@ public class ApplicationDao {
return getApplicationResponse(applicationEntity);
}
public Integer calculateProgress(Long totalSteps, Long completedSteps) {
public Integer calculateProgress(Long totalSteps, Long completedSteps) {
if (FieldValidator.isNullOrZero(totalSteps)) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.TOTAL_STEPS_NOT_BE_ZERO));
}
@@ -663,4 +702,143 @@ public class ApplicationDao {
protocolRepository.save(protocolEntity);
return protocolEntity;
}
private void sendMailToUserAndCompany(UserEntity userEntity, ApplicationEntity applicationEntity) {
CallEntity call =applicationEntity.getCall();
CompanyEntity company = applicationEntity.getCompany();
ProtocolEntity protocol = applicationEntity.getProtocol();
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_TO_USER_AND_COMPANY,
call, null);
// Create the map for subject placeholders
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
subjectPlaceholders.put("{{company_name}}", company.getCompanyName());
// Create the map for body placeholders
Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{call_name}}", call.getName());
bodyPlaceholders.put("{{protocol_number}}", protocol.getProtocolNumber().toString());
bodyPlaceholders.put("{{date}}", DateTimeUtil.formatLocalDateTime(protocol.getCreatedDate(), GepafinConstant.DD_MM_YYYY));
bodyPlaceholders.put("{{time}}", DateTimeUtil.parseLocalTimeToString(protocol.getTime(), GepafinConstant.HH_MM_SS));
// Replace placeholders in the subject and body
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
String email = userEntity.getEmail();
if (userEntity.getBeneficiary() != null) {
email = userEntity.getBeneficiary().getEmail();
}
mailUtil.sendByMailGun(subject, body, List.of(email), null);
mailUtil.sendByMailGun(subject, body, List.of(applicationEntity.getCompany().getEmail()), null);
}
private void sendMailTodefaultSystemAndGepafin(UserEntity userEntity, ApplicationEntity applicationEntity) {
CallEntity call = applicationEntity.getCall();
CompanyEntity company = applicationEntity.getCompany();
ProtocolEntity protocol = applicationEntity.getProtocol();
SystemEmailTemplateResponse systemEmailTemplateResponse = systemEmailTemplatesService
.retrieveTemplateByTypeAndCall(SystemEmailTemplatesEntityTypeEnum.APPLICATION_SUBMISSION_TO_GEPAFIN,
call, null);
// Create the map for subject placeholders
Map<String, String> subjectPlaceholders = new HashMap<>();
subjectPlaceholders.put("{{call_name}}", call.getName());
subjectPlaceholders.put("{{company_name}}", company.getCompanyName());
// Create the map for body placeholders
Map<String, String> bodyPlaceholders = new HashMap<>();
bodyPlaceholders.put("{{call_name}}", call.getName());
bodyPlaceholders.put("{{protocol_number}}", protocol.getProtocolNumber().toString());
bodyPlaceholders.put("{{date}}", DateTimeUtil.formatLocalDateTime(protocol.getCreatedDate(), GepafinConstant.DD_MM_YYYY));
bodyPlaceholders.put("{{time}}", DateTimeUtil.parseLocalTimeToString(protocol.getTime(), GepafinConstant.HH_MM_SS));
// Replace placeholders in the subject and body
String subject = Utils.replacePlaceholders(systemEmailTemplateResponse.getSubject(), subjectPlaceholders);
String body = Utils.replacePlaceholders(systemEmailTemplateResponse.getHtmlContent(), bodyPlaceholders);
mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
}
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId,
MultipartFile file) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
validateFileType(file);
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if (applicationSignedDocument != null) {
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
}
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = amazonS3Service.uploadFileOnAmazonS3(signedDocumentS3Folder,
file);
applicationSignedDocument = new ApplicationSignedDocumentEntity();
applicationSignedDocument.setApplication(applicationEntity);
applicationSignedDocument.setFileName(uploadFileOnAmazonS3.getFileName());
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
private ApplicationSignedDocumentResponse convertApplicationSignedDocumentToApplicationSignedDocumentResponse(
ApplicationSignedDocumentEntity applicationSignedDocument) {
ApplicationSignedDocumentResponse applicationSignedDocumentResponse = new ApplicationSignedDocumentResponse();
applicationSignedDocumentResponse.setId(applicationSignedDocument.getId());
applicationSignedDocumentResponse.setApplicationId(applicationSignedDocument.getApplication().getId());
applicationSignedDocumentResponse.setFileName(applicationSignedDocument.getFileName());
applicationSignedDocumentResponse.setFilePath(applicationSignedDocument.getFilePath());
applicationSignedDocumentResponse
.setStatus(ApplicationSignedDocumentStatusEnum.valueOf(applicationSignedDocument.getStatus()));
applicationSignedDocumentResponse.setCreatedDate(applicationSignedDocument.getCreatedDate());
applicationSignedDocumentResponse.setUpdatedDate(applicationSignedDocument.getUpdatedDate());
return applicationSignedDocumentResponse;
}
private void validateFileType(MultipartFile file) {
if (file.isEmpty()) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_EMPTY));
}
String filename = file.getOriginalFilename();
if (filename == null || !filename.endsWith(".p7m")) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_INVALIDTYPE));
}
}
public ApplicationSignedDocumentResponse getSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_SIGNED_DOCUMENT_NOT_FOUND));
}
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
public void deleteSignedDocument(HttpServletRequest request, Long applicationId) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_SIGNED_DOCUMENT_NOT_FOUND));
}
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
}
}

View File

@@ -18,6 +18,7 @@ import net.gepafin.tendermanagement.repositories.UserWithCompanyRepository;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -190,8 +191,8 @@ public class CompanyDao {
}
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
return userWithCompanyRepository.findByUserIdAndCompanyId(userId, companyId).orElseThrow(() -> new CustomValidationException(Status.UNAUTHORIZED,
Translator.toLocale(GepafinConstant.UNAUTHORIZED)));
return userWithCompanyRepository.findByUserIdAndCompanyId(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED)));
}
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {

View File

@@ -0,0 +1,640 @@
package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.text.*;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.model.request.CustomPageEvent;
import net.gepafin.tendermanagement.model.request.FieldLabelValuePairRequest;
import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Cell;
//import com.itextpdf.layout.element.
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class PdfDao {
@Autowired
private CallService callService;
@Autowired
private ApplicationDao applicationDao;
@Autowired
private Validator validator;
public byte[] generatePdf(HttpServletRequest request,Long applicationId) {
try {
UserEntity userEntity = validator.validateUser(request);
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
CallEntity call=callService.validateCall(applicationEntity.getCall().getId());
// Create a byte stream to hold the PDF
ByteArrayOutputStream out = new ByteArrayOutputStream();
float leftMargin = 50f; // Adjust this for the left margin
Document document = new Document(PageSize.A4, leftMargin, 36f, 50f, 35);
PdfWriter writer = PdfWriter.getInstance(document, out);
// CustomPageEvent pageEvent = new CustomPageEvent(call.getName(), 0);
// writer.setPageEvent(pageEvent);
document.open();
// pageEvent.setTotalPages(writer.getPageNumber());
addLogo(document, "https://mementoresources.s3.eu-west-1.amazonaws.com/gepafin/logo.jpg"); // Add your image path here
BaseColor customColor = new BaseColor(0, 128, 0); // Adjust RGB values as needed
// Define fonts and styles
BaseColor greenColor = new BaseColor(0, 128, 0); // Adjust RGB values as needed
BaseColor darkGreenColor = new BaseColor(1, 50, 32); // Adjust RGB values as needed
Font titleFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, customColor);
Font sectionFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,darkGreenColor);
Font labelFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,new BaseColor(113,121,126)); // Light grey);
Font smallFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8,new BaseColor(105, 105, 105));
Font valueFont=FontFactory.getFont(FontFactory.HELVETICA_BOLD,10,new BaseColor(178, 190, 181));
Paragraph title = new Paragraph(call.getName(), titleFont);
title.setAlignment(Element.ALIGN_LEFT);
document.add(title);
BaseColor greyColor=new BaseColor(178, 190, 181); // Very light grey color
addColoredLines(writer,document,greyColor);
document.add(new Paragraph(" "));
// Application ID section (Centered)
// pageEvent.setTotalPages(writer.getPageNumber());
String protocolNumber="XX00";
if(applicationEntity.getProtocol()!=null) {
protocolNumber= String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
}
Paragraph appId = new Paragraph("ID domanda :" +protocolNumber);
appId.setAlignment(Element.ALIGN_RIGHT);
document.add(appId);
document.add(new Paragraph(" "));
addColoredLines(writer,document,greenColor);
document.add(new Paragraph(" "));
document.add(new Paragraph("\n")); // Add line break
// String companyName= companyEntity.getCompanyName();
// String vatNumber=companyEntity.getVatNumber();
// String address=companyEntity.getAddress();
// // Section: Dati Anagrafici Azienda
// document.add(new Paragraph("Dati Anagrafici Azienda", sectionFont));
// addLabelValuePair(document, "Codice ATECO", "SEZIONE C “ATTIVITÀ MANUFATTURIERE”", regularFont);
// addLabelValuePair(document, "Ragione Sociale", companyName, regularFont);
// addLabelValuePair(document, "Partita IVA", vatNumber, regularFont);
// addLabelValuePair(document, "Indirizzo sede Legale", address, regularFont);
//
// document.add(new Paragraph("\n")); // Add line break
//
// // Section: Domanda presentata da
// document.add(new Paragraph("Domanda presentata da:", sectionFont));
// addLabelValuePair(document, "Nome e cognome", userEntity.getBeneficiary().getFirstName()+" "+userEntity.getBeneficiary().getLastName(), regularFont);
// addLabelValuePair(document, "Codice fiscale", userEntity.getBeneficiary().getCodiceFiscale(), regularFont);
// addLabelValuePair(document, "Telefono", userEntity.getBeneficiary().getPhoneNumber(), regularFont);
// addLabelValuePair(document, "Email", userEntity.getBeneficiary().getEmail(), regularFont);
// addLabelValuePair(document, "Con il titolo di", "Rappresentante legale", regularFont);
document.add(new Paragraph(" "));
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(applicationId,null, userEntity);
for(FormApplicationResponse formApplicationResponse: applicationGetResponseBean.getForm()) {
document.add(new Paragraph(formApplicationResponse.getLabel(),sectionFont));
document.add(new Paragraph(" ")); // Add line break
List<FieldLabelValuePairRequest> fieldLabelValuePairRequests = getFormFieldsToLabels(formApplicationResponse);
for (FieldLabelValuePairRequest pair : fieldLabelValuePairRequests) {
String label = pair.getLabel();
Object value = pair.getValue();
Integer pages=0;
pages=addLabelValuePair(writer,document, label, value, labelFont,valueFont,call.getName(),pages);
if(pages !=0 ){
// pageEvent.setTotalPages(writer.getPageNumber());
}
}
addColoredLines(writer,document,greenColor);
document.add(new Paragraph(" ")); // Add line break
}
document.add(new Paragraph("\n")); // Add line break
Font boldSmallFont = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD,new BaseColor(105, 105, 105));
// Adding the "Documenti Allegati" section title
document.add(new Paragraph(" "));
// pageEvent.setTotalPages(writer.getPageNumber());
document.newPage();
// pageEvent.setTotalPages(writer.getPageNumber());
document.add(new Paragraph("Documenti Allegati", sectionFont));
document.add(new Paragraph(" "));
// 1. Autocertificazione possesso Requisiti
Paragraph p1 = new Paragraph();
p1.add(new Chunk("1. ", boldSmallFont));
p1.add(new Chunk("Autocertificazione possesso Requisiti ", boldSmallFont));
p1.add(new Chunk("ai sensi degli artt. 46 e 47 del DPR 445/2000", smallFont));
document.add(p1);
document.add(new Paragraph(" "));
// 2. Informativa Privacy relativa al trattamento dei dati personali
Paragraph p2 = new Paragraph();
p2.add(new Chunk("2. ", boldSmallFont));
p2.add(new Chunk("Informativa Privacy relativa al trattamento dei dati personali", boldSmallFont));
document.add(p2);
document.add(new Paragraph(" "));
// 3. Dati richiesti per la valutazione delladeguatezza dei flussi finanziari
Paragraph p3 = new Paragraph();
p3.add(new Chunk("3. ", boldSmallFont));
p3.add(new Chunk("Dati richiesti per la valutazione delladeguatezza dei flussi finanziari prospettici come da tabella di cui allAppendice 9", boldSmallFont));
document.add(p3);
document.add(new Paragraph(" "));
// 4. Rilevazione Centrale dei Rischi
Paragraph p4 = new Paragraph();
p4.add(new Chunk("4. ", boldSmallFont));
p4.add(new Chunk("Rilevazione Centrale dei Rischi riferita agli ultimi 36 mesi disponibili alla data di presentazione della Domanda", boldSmallFont));
document.add(p4);
document.add(new Paragraph(" "));
// 5. Schema di presentazione dei dati di bilancio
Paragraph p5 = new Paragraph();
p5.add(new Chunk("5. ", boldSmallFont));
p5.add(new Chunk("Schema di presentazione dei dati di bilancio", boldSmallFont));
document.add(p5);
document.add(new Paragraph(" "));
// 6. Dettagli bilanci in forma abbreviata
Paragraph p6 = new Paragraph();
p6.add(new Chunk("6. ", boldSmallFont));
p6.add(new Chunk("Dettagli bilanci in forma abbreviata", boldSmallFont));
document.add(p6);
document.add(new Paragraph(" "));
// 7. Relazione aziendale illustrativa
Paragraph p7 = new Paragraph();
p7.add(new Chunk("7. ", boldSmallFont));
p7.add(new Chunk("Relazione aziendale illustrativa", boldSmallFont));
document.add(p7);
document.add(new Paragraph(" "));
addColoredLines(writer,document,greenColor);
// System.out.println(writer.getPageSize());
// System.out.println(document.getPageSize());
// System.out.println(document.getPageNumber());
// System.out.println(writer.getPageNumber());
// document.setPageCount(100);
// document.setPageCount(writer.getPageNumber());
// System.out.println(document.getPageNumber());
// Close the document
document.close();
// Convert to byte array for response
byte[] pdfBytes =PdfPageNumberInserter.addPageNumbers(out.toByteArray());
return pdfBytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private Integer addLabelValuePair(PdfWriter writer,Document document, String label, Object value, Font labelFont,Font valueFont,String title,Integer totalPages) throws DocumentException {
// Add label
Paragraph labelParagraph = new Paragraph(label, labelFont);
document.add(labelParagraph);
float leftMargin = 20f;
PdfContentByte canvas = writer.getDirectContent();
// Setting the color and width of the line
float lineWidth = 1.0f; // Thickness of the line
canvas.setLineWidth(lineWidth);
// Get the current vertical position in the document
float yPos = writer.getVerticalPosition(true) - 10f; // Adjust this to move line slightly below current content
// Define start and end points for the line (relative to the page size and margins)
if (yPos <= 140) {
// If xEnd is less than or equal to 200, generate a new page
totalPages++;
document.newPage();
} // Add a gap between the label and value
document.add(new Paragraph(" ")); // Adding an empty paragraph for spacing
// Create value cell with rounded corners
PdfPTable valueTable = new PdfPTable(1);
valueTable.setWidthPercentage(100);
if (value instanceof List<?>) {
// Further check if the list contains Strings
List<?> list = (List<?>) value;
if (!list.isEmpty() && list.get(0) instanceof String) {
// Cast to List<String>
List<String> values = (List<String>) value;
// Loop through the list of strings and create a cell for each string
for (String item : values) {
PdfPCell valueCell = new PdfPCell(new Phrase(item, valueFont));
valueCell.setPadding(5f); // Increase padding for better spacing
valueCell.setPaddingLeft(leftMargin); // Increase left margin for value
valueCell.setBorder(Rectangle.NO_BORDER); // Remove border for value cell
valueCell.setMinimumHeight(30f);
valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
valueCell.setCellEvent(new RoundedCorners()); // Apply rounded corners
// Add the cell to the table
valueTable.addCell(valueCell);
}
// Finally, add the table to the document
document.add(valueTable);
} else {
boolean containsThreeValues = false; // Variable to track if any map contains three keys
List<Map<String, Object>> dataList = (List<Map<String, Object>>) value; // Cast Object to List of Maps
for (Map<String, Object> entry : dataList) {
if (entry.size() == 3) { // Check if the current map has three keys
containsThreeValues = true; // If found, set the variable to true
break; // No need to check further, exit loop
}
}
List<Map<String, String>> extractedData = new ArrayList<>(); // To hold extracted data
for (Map<String, Object> entry : dataList) {
Map<String, String> extractedMap = new HashMap<>(); // To hold the current extracted row of data
List<String> keys = new ArrayList<>(entry.keySet()); // Get all keys in the current map
// Handle based on the number of keys in the map
if (Boolean.FALSE.equals(containsThreeValues) && keys.size() == 2) {
// Treat the first key as the "key" and second key as the "value"
String heading = (String) entry.get(keys.get(0)); // Get value of first key
String value1 = (String) entry.get(keys.get(1)); // Get value of second key
extractedMap.put(heading,value1); // Store the first key's value as "heading"
} if (Boolean.TRUE.equals(containsThreeValues) ) {
String amount="";
// Treat the first as number, second as description, third as amount
if(keys.size()==3){
amount = (String) entry.get(keys.get(2)); // Third key's value
}
String number = (String) entry.get(keys.get(0)); // First key's value
String description = (String) entry.get(keys.get(1)); // Second key's value
// Store the combined result as a value in the map, with a suitable key
String combinedValue = number + "; " + description + "; " + amount; // Concatenate them as a single value
extractedMap.put("combined", combinedValue); // Store as a single entry, key as "combined"
}
extractedData.add(extractedMap); // Add each extracted map to the list
}
document=createPdfTable(extractedData,document);
}
}
else {
PdfPCell valueCell = new PdfPCell(new Phrase(String.valueOf(value), valueFont));
valueCell.setPadding(5f); // Increase padding for better spacing
valueCell.setPaddingLeft(leftMargin); // Increase left margin for value
valueCell.setBorder(Rectangle.NO_BORDER); // Remove border for value cell
valueCell.setMinimumHeight(30f);
valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
valueCell.setCellEvent(new RoundedCorners()); // Apply rounded corners
valueTable.addCell(valueCell);
document.add(valueTable);
}
document.add(new Paragraph("\n")); // Add line break after each value
return totalPages;
}
private Document createPdfTable(List<Map<String, String>> extractedData,Document document) throws DocumentException {
// Create a PdfPTable with 2 columns
PdfPTable table = new PdfPTable(2); // Initial assumption for 2 columns
table.setWidthPercentage(100); // Set table width to 100%
table.setTableEvent(new RoundedBorderEvent());
Font textFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new BaseColor(105, 105, 105)); // Gray text
boolean combinedHeaderAdded = false; // Flag to track if headers for combined have been added
float rowHeight = 50f; // Example row height, adjust as necessary
float maxTableHeight = 700f; // Maximum height of the table before a page break
float[] columnWidths = {0.7f, 0.3f};
table.setWidths(columnWidths);
// Add table header
// Populate the table with extracted data and style rows
for (Map<String, String> row : extractedData) {
for (Map.Entry<String, String> entry : row.entrySet()) {
String key = entry.getKey(); // This will give you the key
String value = entry.getValue(); // This will give you the value
// Check if the current entry is for the combined section
if ("combined".equals(key)) {
// Ensure the combined header is added only once
if (!combinedHeaderAdded) {
// Create a new table for combined entries
table = new PdfPTable(3); // 3 columns for combined entries
PdfPCell headerCell1 = new PdfPCell(new Phrase("Number"));
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell1);
PdfPCell headerCell2 = new PdfPCell(new Phrase("Details"));
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell2);
PdfPCell headerCell3 = new PdfPCell(new Phrase("Amount"));
headerCell3.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell3.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell3);
combinedHeaderAdded = true; // Mark header as added
}
// Split the value for "combined" into separate parts
String[] combinedValues = value.split("; ");
// Check if we have 3 parts (number, description, amount)
String number = combinedValues[0]; // 1st part (number)
String description = combinedValues[1]; // 2nd part (description)
String amount = "";
if (combinedValues.length == 3) {
amount = combinedValues[2]; // 3rd part (amount)
}
// Create PDF cells using the split values
PdfPCell cellNumber = new PdfPCell(new Phrase(number, textFont)); // Cell for number
PdfPCell cellDescription = new PdfPCell(new Phrase(description, textFont)); // Cell for description
PdfPCell cellAmount = new PdfPCell(new Phrase(amount, textFont)); // Cell for amount
// Set row background color for combined values
cellNumber.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for combined rows
cellDescription.setBackgroundColor(new BaseColor(239, 243, 248));
cellAmount.setBackgroundColor(new BaseColor(239, 243, 248));
// Set cell height and add rounded borders
// cellNumber.setFixedHeight(rowHeight);
// cellDescription.setFixedHeight(rowHeight);
// cellAmount.setFixedHeight(rowHeight);
cellNumber.setMinimumHeight(20f); // Set minimum height for better appearance
cellDescription.setMinimumHeight(20f); // Set minimum height for better appearance
cellAmount.setMinimumHeight(20f); // Set minimum height for better appearance
cellNumber.setPadding(7f);
cellDescription.setPadding(7f);
cellAmount.setPadding(7f);
// Add the cells to the table only once
table.addCell(cellNumber);
table.addCell(cellDescription);
table.addCell(cellAmount);
} else {
if (!combinedHeaderAdded) {
// Create a new table for combined entries
table= new PdfPTable(2); // 3 columns for combined entries
table.setWidthPercentage(100);
PdfPCell headerCell1 = new PdfPCell(new Phrase("Details"));
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell1);
PdfPCell headerCell2 = new PdfPCell(new Phrase("Amount"));
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
table.addCell(headerCell2);
combinedHeaderAdded=true;
}
// Add cells for regular key-value pairs without headers
PdfPCell cellKey = new PdfPCell(new Phrase(key, textFont));
PdfPCell cellValue = new PdfPCell(new Phrase(value, textFont));
// Set background color for both cells
cellKey.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for other rows
cellValue.setBackgroundColor(new BaseColor(239, 243, 248));
cellKey.setPadding(7f);
cellValue.setPadding(7f);
// Set cell height and add rounded borders
cellKey.setFixedHeight(rowHeight);
cellValue.setFixedHeight(rowHeight);
// Add the cells to the table
table.addCell(cellKey);
table.addCell(cellValue);
}
if (table.getTotalHeight() + rowHeight > maxTableHeight) {
// Start a new page if needed
document.add(table);
table = new PdfPTable(2); // Reset table for new page
table.setWidthPercentage(100); // Reset width percentage
combinedHeaderAdded = false; // Reset header flag
}
}
}
document.add(table); // Add the last table before returning
// Check if adding a new row would exceed the maximum height
// Return the populated table
return document;
}
public static class RoundedBorderEvent implements PdfPTableEvent {
@Override
public void tableLayout(PdfPTable table, float[][] widths, float[] heights,
int headerRows, int rowStart, PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.BASECANVAS];
// Get the table boundaries
float left = widths[0][0];
float right = widths[0][widths[0].length - 1];
float top = heights[0];
float bottom = heights[heights.length - 1];
// Define the corner radius
float radius = 20f;
// Draw a rounded rectangle around the table
canvas.roundRectangle(left, bottom, right - left, top - bottom, radius);
canvas.stroke();
}
}
public List<FieldLabelValuePairRequest> getFormFieldsToLabels(FormApplicationResponse responseBean) {
List<FieldLabelValuePairRequest> labelValuePairs = new ArrayList<>();
// Iterate through each form in the application response
List<ApplicationFormFieldResponseBean> formFields = responseBean.getFormFields();
List<ContentResponseBean> contents = responseBean.getContent();
// Iterate through each formField in the current form
for (ApplicationFormFieldResponseBean formField : formFields) {
String fieldId = formField.getFieldId();
Object fieldValue = formField.getFieldValue();
// Find the content in the form that matches the fieldId
Optional<ContentResponseBean> matchingContent = contents.stream()
.filter(content -> content.getId().equals(fieldId))
.findFirst();
// If the content with the matching fieldId is found, create a label-value pair
if (matchingContent.isPresent()) {
String name = matchingContent.get().getName();
if (name.equals("fileupload")) {
// Step 1: Check if fieldValue is an instance of List<DocumentResponseBean>
if (fieldValue instanceof List<?> && ((List<?>) fieldValue).stream().allMatch(item -> item instanceof DocumentResponseBean)) {
// Step 2: Safely cast to List<DocumentResponseBean>
List<DocumentResponseBean> documentList = (List<DocumentResponseBean>) fieldValue;
// Step 3: Extract names from the document list
List<String> names = documentList.stream()
.map(DocumentResponseBean::getName) // Extract the name from each DocumentResponseBean
.collect(Collectors.toList());
fieldValue=names;
}
}
if(name.equals("checkboxes")) {
List<String> check = (List<String>) fieldValue;
List<SettingResponseBean> settingResponseBeans = matchingContent.get().getSettings();
for (SettingResponseBean settingResponseBean : settingResponseBeans) {
// Initialize a list to hold matched labels for each SettingResponseBean
List<String> matchedLabels = new ArrayList<>();
if (settingResponseBean.getValue() instanceof List<?>) {
List<?> valueList = (List<?>) settingResponseBean.getValue();
if (!valueList.isEmpty() && valueList.get(0) instanceof Map<?, ?>) {
// Cast to List<Map<String, String>>
List<Map<String, String>> options = (List<Map<String, String>>) valueList;
for (Map<String, String> field : options) {
for (String val : check) {
String name1=field.get("name");
if (val.equals(name1)) { // Check if the key exists in the current field map
String label = field.get("label"); // Extract the label
if (field != null) { // Check if the value is not null
matchedLabels.add(label); // Add the value to the matchedValues list
}
}
}
}
fieldValue = matchedLabels;
}
}
}
}
String label = matchingContent.get().getLabel();
// Add the label-value pair to the list
if (fieldValue != null && !fieldValue.toString().trim().isEmpty()) {
fieldValue = findLabelInOptions(matchingContent.get().getSettings(), fieldValue);
labelValuePairs.add(new FieldLabelValuePairRequest(label, fieldValue));
}
}
}
return labelValuePairs;
}
public static Object findLabelInOptions(List<SettingResponseBean> settings, Object valueToFind) {
ObjectMapper objectMapper = new ObjectMapper();
try {
if (valueToFind instanceof String) {
String searchValue = (String) valueToFind;
for (SettingResponseBean setting : settings) {
Object value = setting.getValue();
if (value instanceof List) {
List<?> options = (List<?>) value;
for (Object option : options) {
JsonNode optionNode = objectMapper.convertValue(option, JsonNode.class);
if (optionNode.get("name").asText().equals(searchValue)) {
return optionNode.get("label").asText();
}
}
}
}
}
} catch (Exception e) {
}
return valueToFind;
}
public void addLogo(Document document, String logoPath) throws Exception {
Image logo = Image.getInstance(logoPath);
logo.scaleToFit(document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(), // Fit to document width
document.getPageSize().getHeight() / 4); // Adjust the height as needed (1/4th of the page height)
logo.setAlignment(Image.ALIGN_CENTER); // Align logo to center
document.add(logo);
// Add some space after logo
document.add(new Paragraph("\n")); // Adding space after the logo
}
public void addColoredLines(PdfWriter writer, Document document, BaseColor color){
PdfContentByte canvas = writer.getDirectContent();
// Setting the color and width of the line
canvas.setColorStroke(color);
float lineWidth = 1.0f; // Thickness of the line
canvas.setLineWidth(lineWidth);
// Get the current vertical position in the document
float yPos = writer.getVerticalPosition(true) - 10f; // Adjust this to move line slightly below current content
// Define start and end points for the line (relative to the page size and margins)
float xStart = document.leftMargin(); // Start from the left margin
float xEnd = document.getPageSize().getWidth() - document.rightMargin(); // End at the right margin
// Draw the line at the current Y position
canvas.moveTo(xStart, yPos); // Move to the starting point
canvas.lineTo(xEnd, yPos); // Draw the line to the end point
canvas.stroke(); // Apply the stroke (line)
}
}

View File

@@ -0,0 +1,45 @@
package net.gepafin.tendermanagement.dao;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfContentByte;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class PdfPageNumberInserter {
public static byte[] addPageNumbers(byte[] pdfData) throws IOException, DocumentException {
PdfReader reader = new PdfReader(pdfData); // Read the generated PDF
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BaseColor darkGreenColor = new BaseColor(1, 50, 32); // Adjust RGB values as needed
Font baseFont = FontFactory.getFont(FontFactory.HELVETICA, 4,darkGreenColor);
BaseFont font = baseFont.getBaseFont();
// PdfStamper allows us to modify the existing PDF
PdfStamper stamper = new PdfStamper(reader, outputStream);
int totalPages = reader.getNumberOfPages();
// Set the font for page numbers
for (int i = 1; i <= totalPages; i++) {
// Get the content of the current page
PdfContentByte over = stamper.getOverContent(i);
over.beginText();
over.setFontAndSize(font, 12);
// Add the page number at the bottom center of the page
over.showTextAligned(PdfContentByte.ALIGN_CENTER, "Page " + i + " of " + totalPages, 300, 30, 0);
over.endText();
}
stamper.close();
reader.close();
return outputStream.toByteArray(); // Return the modified PDF with page numbers
}
}

View File

@@ -0,0 +1,45 @@
package net.gepafin.tendermanagement.dao;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPCellEvent;
import com.itextpdf.text.pdf.PdfPTable;
public class RoundedCorners implements PdfPCellEvent {
@Override
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvas) {
// Retrieve the canvas for drawing the background and border
PdfContentByte cbBackground = canvas[PdfPTable.BACKGROUNDCANVAS];
PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
cbBackground.saveState();
cb.saveState();
// Define the rounded rectangle radius and padding
float radius = 10f;
float padding = 2f; // Small padding to avoid overlap
// Get position values with adjusted height and width
float x = position.getLeft() + padding;
float y = position.getBottom() + padding;
float width = position.getWidth() - 2 * padding;
float height = position.getHeight() - 2 * padding;
// Fill the rounded rectangle with lighter grey
cbBackground.setColorFill(new BaseColor(239, 243, 248)); // Very light grey color
cbBackground.roundRectangle(x, y, width, height, radius);
cbBackground.fill(); // Fill the background
// Set the border stroke to thin and draw the rounded rectangle with dark grey color
cb.setLineWidth(0.5f); // Thin border width
cb.setColorStroke(new BaseColor(105, 105, 105)); // Dark grey border
cb.roundRectangle(x, y, width, height, radius);
cb.stroke(); // Draw the border
// Restore the canvas states
cbBackground.restoreState();
cb.restoreState();
}
}

View File

@@ -0,0 +1,116 @@
package net.gepafin.tendermanagement.dao;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity;
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum;
import net.gepafin.tendermanagement.model.response.SystemEmailTemplateResponse;
import net.gepafin.tendermanagement.repositories.SystemEmailTemplatesRespository;
import net.gepafin.tendermanagement.util.Utils;
@Component
public class SystemEmailTemplatesDao {
@Autowired
private SystemEmailTemplatesRespository systemEmailTemplatesRespository;
@Value("${fe.base.url}")
private String feBaseUrl;
public SystemEmailTemplateResponse retrieveTemplate(SystemEmailTemplatesEntityTypeEnum type, CallEntity call, Locale language) {
SystemEmailTemplatesEntity dbSystemEmailTemplatesEntity = null;
if(call != null){
// dbSystemEmailTemplatesEntity = systemEmailTemplatesRespository
// .findByTypeAndCallId(type.getValue(), call.getId());
}
if(dbSystemEmailTemplatesEntity == null){
dbSystemEmailTemplatesEntity = systemEmailTemplatesRespository
.findByType(type.getValue());
}
SystemEmailTemplateResponse systemEmailTemplateResponse = replaceHtmlContant(dbSystemEmailTemplatesEntity, call, language, Boolean.TRUE);
return systemEmailTemplateResponse;
}
private SystemEmailTemplateResponse replaceHtmlContant(SystemEmailTemplatesEntity dbSystemEmailTemplatesEntity,
CallEntity call, Locale language1, Boolean isDefaultReplace) {
String language = null;
String htmlContent = dbSystemEmailTemplatesEntity.getHtmlContent();
String subject = dbSystemEmailTemplatesEntity.getSubject();
if (language1 == null) {
// language = getLanguage(LocaleContextHolder.getLocale());
language="italian";
}else{
language="italian";
}
Map<String, String> languageMap = new HashMap<>();
String jsonContent = dbSystemEmailTemplatesEntity.getJson();
if (Boolean.FALSE.equals(StringUtils.isEmpty(jsonContent))) {
Map<String, Map<String, String>> jsonMap = Utils.parseJsonContent(jsonContent);
if (jsonMap != null && jsonMap.containsKey(language)) {
languageMap = jsonMap.get(language);
htmlContent = replacePlaceholders(htmlContent, languageMap);
subject = replaceSubjectPlaceholders(subject, languageMap);
}
}
if(Boolean.TRUE.equals(StringUtils.isEmpty(subject))){
subject = "";
}
htmlContent = replacePlatformLinkPlaceholder(call, htmlContent, languageMap);
SystemEmailTemplateResponse systemEmailTemplateResponse = new SystemEmailTemplateResponse();
systemEmailTemplateResponse.setHtmlContent(htmlContent);
systemEmailTemplateResponse.setSubject(subject);
systemEmailTemplateResponse.setJsonMap(languageMap);
return systemEmailTemplateResponse;
}
// private String getLanguage(Locale locale) {
// return switch (locale.getLanguage()) {
// case "en" -> "english";
// case "it" -> "italian";
// default -> "italian";
// };
// }
private String replacePlaceholders(String htmlContent, Map<String, String> languageMap) {
for (Map.Entry<String, String> entry : languageMap.entrySet()) {
htmlContent = htmlContent.replace("{{" + entry.getKey() + "}}", entry.getValue());
}
return htmlContent;
}
private String replaceSubjectPlaceholders(String subject, Map<String, String> languageMap) {
if(languageMap.containsKey("subject") && subject != null){
String value = languageMap.get("subject");
subject = subject.replace("{{subject}}", value);
return subject;
}
return "";
}
private String replacePlatformLinkPlaceholder(CallEntity call, String htmlContent,
Map<String, String> languageMap) {
String platformLink = feBaseUrl;
// if(hubEntity != null && Boolean.FALSE.equals(isEmpty(hubEntity.getDomainName()))){
// platformLink = hubEntity.getDomainName();
// }
htmlContent = htmlContent.replace("{{platform_link}}", platformLink);
return htmlContent;
}
}