Skip to content

Commit

Permalink
Merge pull request #105 from nimble-platform/staging
Browse files Browse the repository at this point in the history
Pull Request for Release 17.0.18
  • Loading branch information
dogukan10 authored Jun 30, 2021
2 parents 9f8f5ff + 8cf66af commit 45518de
Show file tree
Hide file tree
Showing 11 changed files with 617 additions and 98 deletions.
4 changes: 0 additions & 4 deletions Jenkinsfile
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,6 @@ node('nimble-jenkins-slave') {
sh 'ssh nimble "cd /data/deployment_setup/prod/ && sudo ./run-prod.sh restart-single business-process-service"'
}

stage('Deploy FMP') {
sh 'ssh fmp-prod "cd /srv/nimble-fmp/ && ./run-fmp-prod.sh restart-single business-process-service"'
}

stage('Deploy Efactory') {
sh 'ssh efac-prod "cd /srv/nimble-efac/ && ./run-efac-prod.sh restart-single business-process-service"'
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,20 @@ public boolean preHandle (HttpServletRequest request, HttpServletResponse respon
// save the time as an Http attribute
request.setAttribute("startTime", System.currentTimeMillis());

// add Company Admin role to execution context if the endpoint is among the excluded ones from authentication
if(excludedEndpoints.stream().anyMatch(endpoint -> request.getServletPath().matches(endpoint))) {
executionContext.setUserRoles(Collections.singletonList(NimbleRole.COMPANY_ADMIN.getName()));
return true;
}

String bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION);
String originalBearerToken = request.getHeader(ORIGINAL_AUTHORIZATION_HEADER);

Claims claims = null;
try {
claims = iValidationUtil.validateToken(bearerToken);
} catch (Exception e) {
// do not throw an exception if the endpoint is among the excluded ones from authentication
if(excludedEndpoints.stream().anyMatch(endpoint -> request.getServletPath().matches(endpoint))) {
executionContext.setUserRoles(Collections.singletonList(NimbleRole.COMPANY_ADMIN.getName()));
return true;
} else {
throw new NimbleException(NimbleExceptionMessageCode.UNAUTHORIZED_NO_USER_FOR_TOKEN.toString(), Arrays.asList(bearerToken),e);
}
throw new NimbleException(NimbleExceptionMessageCode.UNAUTHORIZED_NO_USER_FOR_TOKEN.toString(), Arrays.asList(bearerToken),e);
}

// set token to the execution context
Expand Down
37 changes: 34 additions & 3 deletions src/main/java/eu/nimble/service/bp/contract/ContractGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,14 @@ public class ContractGenerator {
public void generateContract(OrderType order,ZipOutputStream zos) throws Exception{
// get the order response
OrderResponseSimpleType orderResponse = DocumentPersistenceUtility.getOrderResponseDocumentByOrderId(order.getID());
List<XWPFDocument> orderTermsAndConditions = null;
// the list of terms and conditions files used in the order
List<DocumentReferenceType> termsAndConditionsFiles = ProcessDocumentMetadataDAOUtility.getTermsAndConditionsFiles(orderResponse);
// if there is no file for the terms and conditions, create the standard T&Cs document using the order
if(termsAndConditionsFiles.size() == 0){
orderTermsAndConditions = fillOrderTermsAndConditions(order);
}

List<XWPFDocument> orderTermsAndConditions = fillOrderTermsAndConditions(order);
List<XWPFDocument> purchaseDetails = fillPurchaseDetails(order,orderResponse);

getAndPopulateClauses(order,zos,purchaseDetails);
Expand All @@ -95,7 +101,6 @@ public void generateContract(OrderType order,ZipOutputStream zos) throws Excepti
// then, we create entry names by combining the product name and count,i.e.,Product Name,Product Name_1,Product Name_2 etc.
Map<String,Integer> productNamesCountMap = new HashMap<>();
for (int i = 0; i<orderLineSize;i++) {
XWPFDocument orderTermsAndCondition = orderTermsAndConditions.get(i);
XWPFDocument purchaseDetail = purchaseDetails.get(i);
String productName = order.getOrderLine().get(i).getLineItem().getItem().getName().get(0).getValue();
// update the map
Expand All @@ -104,7 +109,11 @@ public void generateContract(OrderType order,ZipOutputStream zos) throws Excepti
int count = productNamesCountMap.get(productName);
String entryName = count > 1 ? productName+"_"+count: productName;
// create entries
addDocxToZipFile(entryName+"/Standard Purchase Order Terms and Conditions.pdf",orderTermsAndCondition,zos);
if(orderTermsAndConditions != null){
addDocxToZipFile(entryName+"/Standard Purchase Order Terms and Conditions.pdf",orderTermsAndConditions.get(i),zos);
} else{
createTermsAndConditionsFiles(termsAndConditionsFiles,zos,entryName);
}
addDocxToZipFile(entryName+"/Company Purchase Details.pdf",purchaseDetail,zos);
}
}
Expand Down Expand Up @@ -290,6 +299,28 @@ else if(text != null && text.contains("$document_name")){
return documents;
}


/**
* Creates the entries for the given terms and conditions files.
* */
public void createTermsAndConditionsFiles(List<DocumentReferenceType> termsAndConditionsFiles,ZipOutputStream zos,String entryName) throws IOException {
try {
for(DocumentReferenceType documentReference : termsAndConditionsFiles){
byte[] bytes = binaryContentService.retrieveContent(documentReference.getAttachment().getEmbeddedDocumentBinaryObject().getUri()).getValue();
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
bos.write(bytes,0,bytes.length);

ZipEntry zipEntry2 = new ZipEntry(entryName+"/"+documentReference.getAttachment().getEmbeddedDocumentBinaryObject().getFileName());
zos.putNextEntry(zipEntry2);
bos.writeTo(zos);
}
}
catch (Exception e){
logger.error("Failed to create terms and conditions entry",e);
throw e;
}
}

private void setClauseContent(String sectionText, XWPFParagraph paragraph, List<TradingTermType> tradingTerms){
// get the identifiers of all trading terms
List<String> tradingTermIds = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ public enum NimbleExceptionMessageCode {
INTERNAL_SERVER_ERROR_GET_ALL_DIGITAL_AGREEMENTS_FOR_PARTIES_AND_PRODUCTS("INTERNAL_SERVER_ERROR.getAllDigitalAgreementsForPartiesAndProduct"),
INTERNAL_SERVER_ERROR_GET_ASSOCIATED_COLLABORATION_GROUP("INTERNAL_SERVER_ERROR.getAssociatedCollaborationGroup"),
INTERNAL_SERVER_ERROR_GET_AVERAGE_RESPONSE_TIME("INTERNAL_SERVER_ERROR.getAverageResponseTime"),
INTERNAL_SERVER_ERROR_GET_COLLABORATION_TIME_IN_MONTHS("INTERNAL_SERVER_ERROR.getCollaborationTimeInMonths"),
INTERNAL_SERVER_ERROR_GET_CATALOGUE_LINE_FOR_EPC("INTERNAL_SERVER_ERROR.getCatalogueLineForEPCCode"),
INTERNAL_SERVER_ERROR_GET_CLAUSES_FOR_PROCESS_INSTANCES("INTERNAL_SERVER_ERROR.getClausesOfContract"),
INTERNAL_SERVER_ERROR_GET_CLAUSE_DETAILS("INTERNAL_SERVER_ERROR.getClauseDetails"),
Expand All @@ -87,6 +88,7 @@ public enum NimbleExceptionMessageCode {
INTERNAL_SERVER_ERROR_GET_NON_ORDERED_PRODUCTS("INTERNAL_SERVER_ERROR.getNonOrderedProducts"),
INTERNAL_SERVER_ERROR_GET_ORDER_DOCUMENT("INTERNAL_SERVER_ERROR.getOrderDocument"),
INTERNAL_SERVER_ERROR_GET_PROCESS_COUNT("INTERNAL_SERVER_ERROR.getProcessCount"),
INTERNAL_SERVER_ERROR_GET_PROCESS_COUNT_BREAKDOWN_BY_ROLE("INTERNAL_SERVER_ERROR.getProcessCountBreakDownByRole"),
INTERNAL_SERVER_ERROR_GET_PROCESS_COUNT_BREAK_DOWN("INTERNAL_SERVER_ERROR.getProcessCountBreakDown"),
INTERNAL_SERVER_ERROR_GET_PROCESS_DOCUMENT_METADATA_SUMMARIES("INTERNAL_SERVER_ERROR.getProcessDocumentMetadataSummaries"),
INTERNAL_SERVER_ERROR_GET_PROCESS_INSTANCE_GROUP_FILTERS("INTERNAL_SERVER_ERROR.getProcessInstanceGroupFilters"),
Expand Down
91 changes: 88 additions & 3 deletions src/main/java/eu/nimble/service/bp/impl/StatisticsController.java
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ public ResponseEntity getAverageResponseTimeForMonths(@ApiParam(value = "Identif
@ApiParam(value = "The Bearer token provided by the identity service" ,required=true ) @RequestHeader(value="Authorization", required=true) String bearerToken,
@ApiParam(value = "" ,required=false ) @RequestHeader(value="federationId", required=false) String federationId) throws NimbleException {
// set request log of ExecutionContext
String requestLog = String.format("Getting average response time for the party with id: %s",partyId);
String requestLog = String.format("Getting average response time for months for the party with id: %s",partyId);
executionContext.setRequestLog(requestLog);

logger.info(requestLog);
Expand Down Expand Up @@ -396,7 +396,7 @@ public ResponseEntity getAverageResponseTimeForMonths(@ApiParam(value = "Identif
}
}

logger.info("Retrieved average response time for the party with id: {}",partyId);
logger.info("Retrieved average response time for months for the party with id: {}",partyId);
return ResponseEntity.ok(averageResponseTime);
}

Expand Down Expand Up @@ -430,12 +430,55 @@ public ResponseEntity getAverageCollaborationTime(@ApiParam(value = "Identifier
if (partyId != null) {
averageNegotiationTime = StatisticsPersistenceUtility.calculateAverageCollaborationTime(partyId,federationId,bearerToken,role);
}else{
averageNegotiationTime = StatisticsPersistenceUtility.calculateAverageCollaborationTimeForPlatform(bearerToken,role);
averageNegotiationTime = StatisticsPersistenceUtility.calculateAverageCollaborationTimeForPlatform(role);
}
logger.info("Retrieved average negotiation time for the party with id: {}",partyId);
return ResponseEntity.ok(averageNegotiationTime);
}

@ApiOperation(value = "Gets average collaboration time in months for the party in terms of days")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Retrieved average collaboration time for the party"),
@ApiResponse(code = 401, message = "Invalid token. No user was found for the provided token")
})
@RequestMapping(value = "/collaboration-time-months",
produces = {"application/json"},
method = RequestMethod.GET)
public ResponseEntity getAverageCollaborationTimeForMonths(@ApiParam(value = "Identifier of the party as specified by the identity service",required = false) @RequestParam(value = "partyId",required = false) String partyId,
@ApiParam(value = "Role of the party in the business process.<br>Possible values:<ul><li>SELLER</li><li>BUYER</li></ul>", defaultValue = "SELLER", required = false) @RequestParam(value = "role", required = false, defaultValue = "SELLER") String role,
@ApiParam(value = "The Bearer token provided by the identity service" ,required=true ) @RequestHeader(value="Authorization", required=true) String bearerToken,
@ApiParam(value = "" ,required=false ) @RequestHeader(value="federationId", required=false) String federationId) throws NimbleException {
// set request log of ExecutionContext
String requestLog = String.format("Getting average collaboration time in months for the party with id: %s",partyId);
executionContext.setRequestLog(requestLog);

logger.info(requestLog);

// validate federation id header
federationId = validateFederationIdHeader(federationId);

// validate role
if(!validationUtil.validateRole(bearerToken,executionContext.getUserRoles(), RoleConfig.REQUIRED_ROLES_PURCHASES_OR_SALES_READ)) {
throw new NimbleException(NimbleExceptionMessageCode.UNAUTHORIZED_INVALID_ROLE.toString());
}
Map<Integer,Double> averageNegotiationTime = null;

try {
if (partyId != null) {
averageNegotiationTime = StatisticsPersistenceUtility.calculateAverageCollaborationTimeInMonths(partyId,federationId,bearerToken,role);
}
else {
averageNegotiationTime = StatisticsPersistenceUtility.calculateAverageCollaborationTimeForPlatformInMonths(role);
}
}
catch (Exception e){
throw new NimbleException(NimbleExceptionMessageCode.INTERNAL_SERVER_ERROR_GET_COLLABORATION_TIME_IN_MONTHS.toString(),Arrays.asList(partyId),e);
}

logger.info("Retrieved average collaboration time in months for the party with id: {}",partyId);
return ResponseEntity.ok(averageNegotiationTime);
}

@ApiOperation(value = "Gets statistics (average collaboration time,average response time,trading volume and number of transactions) for the party")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Retrieved statistics for the party",response = OverallStatistics.class),
Expand Down Expand Up @@ -541,6 +584,48 @@ public ResponseEntity getProcessDocumentMetadataSummaries(@ApiParam(value = "The
}
}

@ApiOperation(value = "",notes = "Gets the total number of business processes for the companies. The number of business processes are broken down per company and its role in the business processes.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Retrieved the process breakdown by role successfully",response = int.class),
@ApiResponse(code = 400, message = "Invalid parameter"),
@ApiResponse(code = 401, message = "Invalid token. No user was found for the provided token"),
@ApiResponse(code = 500, message = "Unexpected error while getting the process breakdown by role")
})
@RequestMapping(value = "/total-number/business-process/break-down/role",
produces = {"application/json"},
method = RequestMethod.GET)
public ResponseEntity getProcessCountBreakDownByRole(@ApiParam(value = "Offset of the first result among the complete result set satisfying the given criteria", defaultValue = "0") @RequestParam(value = "offset", required = false, defaultValue = "0") Integer offset,
@ApiParam(value = "Number of results to be included in the result set", defaultValue = "10") @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
@ApiParam(value = "Start date (DD-MM-YYYY) of the process", required = false) @RequestParam(value = "startDate", required = false) String startDateStr,
@ApiParam(value = "End date (DD-MM-YYYY) of the process", required = false) @RequestParam(value = "endDate", required = false) String endDateStr,
@ApiParam(value = "The Bearer token provided by the identity service" ,required=true ) @RequestHeader(value="Authorization", required=true) String bearerToken
) throws NimbleException {
// set request log of ExecutionContext
String requestLog = String.format("Getting process breakdown by role");
executionContext.setRequestLog(requestLog);
try {
logger.info(requestLog);
// validate role
if(!validationUtil.validateRole(bearerToken,executionContext.getUserRoles(), RoleConfig.REQUIRED_ROLES_PURCHASES_OR_SALES_READ)) {
throw new NimbleException(NimbleExceptionMessageCode.UNAUTHORIZED_INVALID_ROLE.toString());
}

// check start date
InputValidatorUtil.checkDate(startDateStr, true);

// check end date
InputValidatorUtil.checkDate(endDateStr, true);

PlatformCompanyProcessCount companyProcessCounts = ProcessDocumentMetadataDAOUtility.getProcessCountBreakDownByRole(offset,limit,startDateStr,endDateStr);

logger.info("Retrieved process breakdown by role");
return ResponseEntity.ok().body(companyProcessCounts);

} catch (Exception e) {
throw new NimbleException(NimbleExceptionMessageCode.INTERNAL_SERVER_ERROR_GET_PROCESS_COUNT_BREAKDOWN_BY_ROLE.toString(),Arrays.asList(startDateStr, endDateStr, limit.toString(),offset.toString()),e);
}
}


private String validateFederationIdHeader(String federationIdHeader){
if(federationIdHeader == null){
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package eu.nimble.service.bp.model.statistics;

import java.math.BigInteger;

public class CompanyProcessCount {

private String partyId;
private String federationId;
private BigInteger purchasesCount;
private BigInteger salesCount;

public CompanyProcessCount() {
}

public CompanyProcessCount(String partyId, String federationId, BigInteger purchasesCount, BigInteger salesCount) {
this.partyId = partyId;
this.federationId = federationId;
this.purchasesCount = purchasesCount;
this.salesCount = salesCount;
}

public String getPartyId() {
return partyId;
}

public void setPartyId(String partyId) {
this.partyId = partyId;
}

public String getFederationId() {
return federationId;
}

public void setFederationId(String federationId) {
this.federationId = federationId;
}

public BigInteger getPurchasesCount() {
return purchasesCount;
}

public void setPurchasesCount(BigInteger purchasesCount) {
this.purchasesCount = purchasesCount;
}

public BigInteger getSalesCount() {
return salesCount;
}

public void setSalesCount(BigInteger salesCount) {
this.salesCount = salesCount;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package eu.nimble.service.bp.model.statistics;

import java.math.BigInteger;
import java.util.List;

public class PlatformCompanyProcessCount {

private BigInteger totalCompanyCount;
private List<CompanyProcessCount> companyProcessCounts;

public PlatformCompanyProcessCount() {
}

public PlatformCompanyProcessCount(BigInteger totalCompanyCount, List<CompanyProcessCount> companyProcessCounts) {
this.totalCompanyCount = totalCompanyCount;
this.companyProcessCounts = companyProcessCounts;
}

public BigInteger getTotalCompanyCount() {
return totalCompanyCount;
}

public void setTotalCompanyCount(BigInteger totalCompanyCount) {
this.totalCompanyCount = totalCompanyCount;
}

public List<CompanyProcessCount> getCompanyProcessCounts() {
return companyProcessCounts;
}

public void setCompanyProcessCounts(List<CompanyProcessCount> companyProcessCounts) {
this.companyProcessCounts = companyProcessCounts;
}
}
Loading

0 comments on commit 45518de

Please sign in to comment.