Done ticket GEPADINBE-6144

This commit is contained in:
rajesh
2025-10-28 17:17:10 +05:30
parent 6a487eeda3
commit 2b63a4a89b
10 changed files with 123 additions and 50 deletions

View File

@@ -33,7 +33,9 @@ import net.gepafin.tendermanagement.service.feignClient.AppointmentApiService;
import net.gepafin.tendermanagement.service.impl.ApplicationEvaluationServiceImpl;
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.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
@@ -141,6 +143,12 @@ public class AppointmentDao {
@Autowired
private NdganagRepository ndganagRepository;
@Autowired
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
@Autowired
private Validator validator;
private final Map<Long, ScheduledExecutorService> executorMap = new ConcurrentHashMap<>();
@@ -1129,12 +1137,31 @@ public class AppointmentDao {
return appointmentCreationRequest;
}
public DocumentUploadResponse uploadDocumentToExternalSystem(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
public DocumentUploadResponse uploadDocumentToExternalSystem(Long documentId,Boolean isSignedDocument, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
log.info("Initiating upload to external system for documentId: {}", documentId);
// Check if the document is already being processed
DocumentEntity systemDoc = documentDao.validateDocument(documentId);
ApplicationEntity application = null;
DocumentEntity systemDoc =null;
ApplicationSignedDocumentEntity applicationSignedDocument =null;
if(isSignedDocument!=null && Boolean.TRUE.equals(isSignedDocument)) {
//all flow in incomplete and testing for document for that unique id
applicationSignedDocument = applicationSignedDocumentRepository
.findByIdAndStatus(documentId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if(applicationSignedDocument == null) {
log.warn("No active signed document found for id: {}", documentId);
throw new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.APPLICATION_SIGNED_DOCUMENT_NOT_FOUND));
}
application=applicationDao.validateApplication(applicationSignedDocument.getApplication().getId());
// if (Boolean.TRUE.equals(validator.isProductionProfileActivated()) && application.getCall().getId().equals(23l)) {
// TO UPLOAD SIGNED DOCUMENT TO COMPANY DOCUMENT FOR SPECIFIC CALL 23 IN GEPAFIN
//// MultipartFile file=amazonS3Service.getFileFromS3Path();
// }
}
else {
systemDoc = documentDao.validateDocument(documentId);
if (systemDoc != null) {
DocumentSourceTypeEnum sourceType = DocumentSourceTypeEnum.valueOf(systemDoc.getSource());
@@ -1160,6 +1187,7 @@ public class AppointmentDao {
break;
}
}
}
Claims claims = tokenProvider.getClaimsFromToken(tokenProvider.extractTokenFromRequest(request));
Long hubId = Utils.extractHubIdFromPayload(claims.getSubject());
@@ -1167,7 +1195,15 @@ public class AppointmentDao {
// Authenticate the hub before proceeding
HubEntity hub = hubRepository.findByHubId(hubId);
authenticateAndSaveToken(hub, application);
if (systemDoc != null && systemDoc.getDocumentAttachmentId() != null) {
String documentAttachmentId=null;
if (applicationSignedDocument!=null){
documentAttachmentId=applicationSignedDocument.getDocumentAttachmentId();
}
if(systemDoc!=null) {
documentAttachmentId=systemDoc.getDocumentAttachmentId();
}
if (documentAttachmentId!=null) {
// If the documentAttachmentId is already set, return the response
log.info("Document already uploaded with documentAttachmentId: {}", systemDoc.getDocumentAttachmentId());
DocumentUploadResponse response = new DocumentUploadResponse();
@@ -1192,7 +1228,7 @@ public class AppointmentDao {
threadLocalHubId.set(hubId);
try {
log.info("Starting async document upload for documentId: {}", documentId);
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest, finalApplication);
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest, finalApplication,isSignedDocument);
} catch (Exception e) {
log.error("Error in async document upload for documentId: {}", documentId, e);
} finally {
@@ -1208,10 +1244,21 @@ public class AppointmentDao {
return null;
}
private void uploadDocumentToExternalSystemSync(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest, ApplicationEntity application) {
private void uploadDocumentToExternalSystemSync(Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest, ApplicationEntity application,Boolean isSignedDocument) {
log.info("Starting sync document upload for documentId: {}", documentId);
// Synchronous upload logic
DocumentEntity systemDoc = documentDao.validateDocument(documentId);
ApplicationSignedDocumentEntity applicationSignedDocument=null;
DocumentEntity systemDoc=null;
String oldUrl = null;
if(Boolean.TRUE.equals(isSignedDocument)){
applicationSignedDocument = applicationSignedDocumentRepository
.findByIdAndStatus(documentId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
oldUrl=applicationSignedDocument.getFilePath();
}else {
systemDoc = documentDao.validateDocument(documentId);
oldUrl=systemDoc.getFilePath();
}
Long hubId = threadLocalHubId.get();
HubEntity hub = hubRepository.findByHubId(hubId);
@@ -1222,13 +1269,17 @@ public class AppointmentDao {
}
log.info("Got Document in system: {}", systemDoc);
String oldUrl = systemDoc.getFilePath();
String authorizationToken = getBearerToken(hub);
try {
File localFile = downloadFileFromS3(oldUrl);
MultipartFile multipartFile = convertFileToMultipartFile(localFile);
// delete temp file
if (!localFile.delete()) {
log.warn("Failed to delete temp file: {}", localFile.getAbsolutePath());
}
UploadDocToExternalSystemRequest externalSystemRequest = new UploadDocToExternalSystemRequest();
externalSystemRequest.setInput(getUploadDocumentInput(docToExternalSystemRequest));
@@ -1245,14 +1296,20 @@ public class AppointmentDao {
}
// Save the documentAttachmentId to the database
if(systemDoc!=null) {
systemDoc.setDocumentAttachmentId(parsedResponse.getDocumentAttachmentId());
documentRepository.save(systemDoc);
}
if(applicationSignedDocument!=null){
applicationSignedDocument.setDocumentAttachmentId(parsedResponse.getDocumentAttachmentId());
applicationSignedDocumentRepository.save(applicationSignedDocument);
}
log.info("Document uploaded successfully to external system: {}", parsedResponse);
} catch (FeignException.Forbidden forbiddenException) {
log.error("403 Forbidden from external system during upload for documentId: {}. Retrying with new token...", documentId);
regenerateTokenAndSave(hub, application);
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest, application);
uploadDocumentToExternalSystemSync(documentId, docToExternalSystemRequest, application,isSignedDocument);
} catch (Exception e) {
log.error("Exception during document upload: {}", e.getMessage(), e);
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.EXTERNAL_DOCUMENT_UPLOAD_FAILURE_MSG));
@@ -1282,13 +1339,21 @@ public class AppointmentDao {
}
private File downloadFileFromS3(String fileUrl) throws Exception {
String key = amazonS3Service.extractS3KeyFromUrl(fileUrl);
String fileName = extractFileName(key);
String folderPath = key.substring(0, key.lastIndexOf("/"));
File localFile = new File(GepafinConstant.TEMP_FILE_PATH + fileName);
// Use OS-independent temp folder
String tempFolder = System.getProperty("java.io.tmpdir");
try (InputStream s3Stream = amazonS3Service.getFile(folderPath, key); FileOutputStream outputStream = new FileOutputStream(localFile)) {
File tempDir = new File(tempFolder);
if (!tempDir.exists() && !tempDir.mkdirs()) {
throw new IOException("Failed to create temp folder: " + tempDir.getAbsolutePath());
}
File localFile = new File(tempDir, fileName);
try (InputStream s3Stream = amazonS3Service.getFile(folderPath, key);
FileOutputStream outputStream = new FileOutputStream(localFile)) {
s3Stream.transferTo(outputStream);
}
@@ -1296,6 +1361,7 @@ public class AppointmentDao {
return localFile;
}
private String extractFileName(String filePath) {
String[] parts = filePath.split("/");

View File

@@ -91,11 +91,10 @@ public class CompanyDocumentDao {
@Autowired
private AmazonS3 amazonS3;
public List<CompanyDocumentResponseBean> uploadFileForCompany(HttpServletRequest request, Long userId, List<MultipartFile> files, Long companyId, Long documentCategoryId, CompanyDocumentTypeEnum companyDocumentSourceTypeEnum, LocalDateTime expirationDate,String name){
public List<CompanyDocumentResponseBean> uploadFileForCompany(Long userId, List<MultipartFile> files, Long companyId, Long documentCategoryId, CompanyDocumentTypeEnum companyDocumentSourceTypeEnum, LocalDateTime expirationDate,String name){
log.info("Uploading files for company. userId={}, companyId={}, documentCategoryId={}", userId, companyId, documentCategoryId);
DocumentCategoryEntity categoryEntity = categoryDao.validateCategory(documentCategoryId);
validator.validateUserWithCompany(request,companyId);
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userId,companyId);
LocalDateTime currentDate = LocalDateTime.now();

View File

@@ -29,4 +29,7 @@ public class ApplicationSignedDocumentEntity extends BaseEntity {
@Column(name="FILE_HASH")
private String fileHash;
@Column(name="DOCUMENT_ATTACHMENT_ID")
private String documentAttachmentId;
}

View File

@@ -1,4 +1,5 @@
package net.gepafin.tendermanagement.service;
import com.amazonaws.services.s3.AmazonS3;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

View File

@@ -12,7 +12,7 @@ public interface AppointmentService {
AppointmentCreationResponse createAppointmentForApplication(HttpServletRequest request, Long applicationId, CreateAppointmentRequest createAppointmentRequest);
DocumentUploadResponse uploadDocToExternalSystem(HttpServletRequest request, Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest);
DocumentUploadResponse uploadDocToExternalSystem(HttpServletRequest request, Long documentId,Boolean isSignedDocument,UploadDocToExternalSystemRequest docToExternalSystemRequest);
NdgResponse getNdgByVatNumber(HttpServletRequest request,String vatNumber);

View File

@@ -24,6 +24,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -141,7 +142,12 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
String originalFileName = org.springframework.util.StringUtils.cleanPath(file.getOriginalFilename());
String firstNameContain = originalFileName.substring(0, originalFileName.lastIndexOf('.'));
firstNameContain = Utils.replaceSpacesWithUnderscores(firstNameContain);
if(extension.equals("p7m")){
firstNameContain =Utils.randomKey(7)+"_"+firstNameContain;
}else {
firstNameContain += "_" + Utils.randomKey(7);
}
String fileName = (firstNameContain + "." + extension);
try {
String filepath = upload(fileName, s3Folder, file);

View File

@@ -35,9 +35,9 @@ public class AppointmentServiceImpl implements AppointmentService {
}
@Override
public DocumentUploadResponse uploadDocToExternalSystem(HttpServletRequest request, Long documentId, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
public DocumentUploadResponse uploadDocToExternalSystem(HttpServletRequest request, Long documentId,Boolean isSignedDocument, UploadDocToExternalSystemRequest docToExternalSystemRequest) {
return appointmentDao.uploadDocumentToExternalSystem(documentId, docToExternalSystemRequest);
return appointmentDao.uploadDocumentToExternalSystem(documentId,isSignedDocument, docToExternalSystemRequest);
}
@Override

View File

@@ -33,7 +33,8 @@ public class CompanyDocumentServiceImpl implements CompanyDocumentService {
Map<String, Object> userInfo = validator.getUserInfoFromToken(request);
Long userId = validator.getUserId(userInfo);
files.forEach(Utils::validateFileType);
return companyDocumentDao.uploadFileForCompany(request,userId,files,companyId,documentCategoryId,documentSourceTypeEnum,expirationDate,name);
validator.validateUserWithCompany(request,companyId);
return companyDocumentDao.uploadFileForCompany(userId,files,companyId,documentCategoryId,documentSourceTypeEnum,expirationDate,name);
}
@Override

View File

@@ -15,10 +15,7 @@ import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.*;
public interface AppointmentApi {
@@ -54,7 +51,7 @@ public interface AppointmentApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@PostMapping(value = "/document/{documentId}", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Response<DocumentUploadResponse>> uploadDocumentToExternalSystem(HttpServletRequest request,
@Parameter(description = "The document id", required = true) @PathVariable(value = "documentId", required = true) Long documentId,
@Parameter(description = "The document id", required = true) @PathVariable(value = "documentId", required = true) Long documentId,@RequestParam(value = "isSignedDocument", required = false) Boolean isSignedDocument,
@RequestBody UploadDocToExternalSystemRequest docToExternalSystemRequest);
@Operation(summary = "API to get ndg by vatNumber", responses = { @ApiResponse(responseCode = "200", description = "OK"),

View File

@@ -65,14 +65,14 @@ public class AppointmentController implements AppointmentApi {
}
@Override
public ResponseEntity<Response<DocumentUploadResponse>> uploadDocumentToExternalSystem(HttpServletRequest request, Long documentId,
public ResponseEntity<Response<DocumentUploadResponse>> uploadDocumentToExternalSystem(HttpServletRequest request, Long documentId,Boolean isSignedDocument,
UploadDocToExternalSystemRequest docToExternalSystemRequest) {
/** This code is responsible for creating user action logs for the "Upload document to external system" operation. **/
loggingUtil.logUserAction(
UserActionRequest.builder().request(request).actionType(UserActionLogsEnum.UPLOAD).actionContext(UserActionContextEnum.UPLOAD_DOCUMENT_TO_EXTERNAL_SYSTEM).build());
DocumentUploadResponse documentUploadResponse = appointmentService.uploadDocToExternalSystem(request, documentId, docToExternalSystemRequest);
DocumentUploadResponse documentUploadResponse = appointmentService.uploadDocToExternalSystem(request, documentId,isSignedDocument ,docToExternalSystemRequest);
String message = GepafinConstant.DOCUMENT_UPLOADED_SUCCESSFULLY_TO_EXTERNAL_SYSTEM;
if(documentUploadResponse == null) {