Skip to content

Commit

Permalink
merges issue-96 changes into reverted copy of main (#106)
Browse files Browse the repository at this point in the history
  • Loading branch information
fereira authored Aug 15, 2022
1 parent 7887697 commit 3e66473
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 44 deletions.
9 changes: 2 additions & 7 deletions src/main/java/org/olf/folio/order/MarcToJson.java
Original file line number Diff line number Diff line change
Expand Up @@ -597,13 +597,8 @@ public JSONArray validateEnvironment( ) {
if (StringUtils.isEmpty((String) this.getConfig().getProperty("tenant"))) {
JSONObject errMsg = new JSONObject();
errMsg.put("error", "api tenant environment variable not found");
errors.put(errMsg);
}
if (StringUtils.isEmpty((String) this.getConfig().getProperty("fiscalYearCode"))) {
JSONObject errMsg = new JSONObject();
errMsg.put("error", "fiscalYearCode environment variable not found");
errors.put(errMsg);
}
errors.put(errMsg);
}
if (StringUtils.isEmpty((String) this.getConfig().getProperty("billToDefault"))) {
JSONObject errMsg = new JSONObject();
errMsg.put("error", "billToDefault environment variable not found");
Expand Down
136 changes: 99 additions & 37 deletions src/main/java/org/olf/folio/order/OrderImport.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
Expand Down Expand Up @@ -47,6 +48,8 @@ public class OrderImport {
private HashMap<String, String> billingMap;
private String tenant;
private boolean rushPO = false;
private String baseOkapEndpoint;
private String token;

private ApiService apiService;
MarcUtils marcUtils = new MarcUtils();
Expand All @@ -60,7 +63,7 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept

//COLLECT VALUES FROM THE CONFIGURATION FILE
// TODO: Fix this typo everywhere... Should be baseOkapiEndpoint
String baseOkapEndpoint = (String) getMyContext().getAttribute("baseOkapEndpoint");
this.baseOkapEndpoint = (String) getMyContext().getAttribute("baseOkapEndpoint");
String apiUsername = (String) getMyContext().getAttribute("okapi_username");
String apiPassword = (String) getMyContext().getAttribute("okapi_password");
tenant = (String) getMyContext().getAttribute("tenant");
Expand All @@ -83,7 +86,7 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept
jsonObject.put("tenant",tenant);

this.apiService = new ApiService(tenant);
String token = this.apiService.callApiAuth( baseOkapEndpoint + "authn/login", jsonObject);
this.token = this.apiService.callApiAuth( baseOkapEndpoint + "authn/login", jsonObject);

//GET THE UPLOADED FILE
String filePath = (String) myContext.getAttribute("uploadFilePath");
Expand All @@ -105,19 +108,19 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept
// We don't want to continue if any of the marc records do not contain valid data
MarcReader reader = new MarcStreamReader(in);

JSONArray validateRequiredResult = validateRequiredValues(reader, token, baseOkapEndpoint);
JSONArray validateRequiredResult = validateRequiredValues(reader);
if (!validateRequiredResult.isEmpty()) return validateRequiredResult;

//SAVE REFERENCE TABLE VALUES (JUST LOOKUP THEM UP ONCE)
logger.debug("Get Lookup table");
if (myContext.getAttribute(Constants.LOOKUP_TABLE) == null) {
LookupUtil lookupUtil = new LookupUtil();
lookupUtil.setBaseOkapEndpoint(baseOkapEndpoint);
lookupUtil.setBaseOkapEndpoint(this.baseOkapEndpoint);
lookupUtil.setApiService(apiService);
lookupUtil.load();
this.lookupTable = lookupUtil.getReferenceValues(token);
String billingEndpoint = baseOkapEndpoint+"configurations/entries?query=(configName==tenant.addresses)";
this.billingMap = lookupUtil.getBillingAddresses(billingEndpoint, token);
this.lookupTable = lookupUtil.getReferenceValues(this.token);
String billingEndpoint = this.baseOkapEndpoint+"configurations/entries?query=(configName==tenant.addresses)";
this.billingMap = lookupUtil.getBillingAddresses(billingEndpoint, this.token);
myContext.setAttribute(Constants.LOOKUP_TABLE, lookupTable);
myContext.setAttribute(Constants.BILLINGMAP, billingMap);

Expand All @@ -143,7 +146,7 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept

//GET THE NEXT PO NUMBER
logger.trace("get next PO number");
String poNumber = this.apiService.callApiGet(baseOkapEndpoint + "orders/po-number", token);
String poNumber = this.apiService.callApiGet(baseOkapEndpoint + "orders/po-number", this.token);
JSONObject poNumberObj = new JSONObject(poNumber);
logger.trace("NEXT PO NUMBER: " + poNumberObj.get("poNumber"));
// does this have to be a UUID object?
Expand Down Expand Up @@ -204,7 +207,7 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept
String organizationEndpoint = baseOkapEndpoint
+ "organizations-storage/organizations?query=(code==" + encodedOrgCode + ")";
logger.debug("organizationEndpoint: " + organizationEndpoint);
String orgLookupResponse = apiService.callApiGet(organizationEndpoint, token);
String orgLookupResponse = apiService.callApiGet(organizationEndpoint, this.token);
JSONObject orgObject = new JSONObject(orgLookupResponse);
String vendorId = (String) orgObject.getJSONArray("organizations").getJSONObject(0).get("id");
order.put("vendor", vendorId);
Expand All @@ -230,6 +233,11 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept
JSONObject fundsObject = new JSONObject(fundResponse);
String fundId = (String) fundsObject.getJSONArray("funds").getJSONObject(0).get("id");

//LOOK UP THE Acquisiton method
//logger.debug("lookup acquisition method");
String acquistionMethodString = "Purchase";
String acquisitionMethodUUID = getAcquisitionMethodUUID(acquistionMethodString);

// CREATING THE PURCHASE ORDER


Expand Down Expand Up @@ -277,7 +285,8 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept
orderLine.put("cost", cost);
orderLine.put("locations", locations);
orderLine.put("titleOrPackage", title);
orderLine.put("acquisitionMethod", "df26d81b-9d63-4ff8-bf41-49bf75cfa70e");
//orderLine.put("acquisitionMethod", "Purchase");
orderLine.put("acquisitionMethod", acquisitionMethodUUID);

// get the "internal note", which apparently will be used as a description
String internalNotes = marcUtils.getInternalNotes(nineEighty);
Expand Down Expand Up @@ -411,12 +420,12 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept
logger.debug(order.toString(3));

//POST THE ORDER AND LINE:
String orderResponse = apiService.callApiPostWithUtf8(baseOkapEndpoint + "orders/composite-orders", order, token);
String orderResponse = apiService.callApiPostWithUtf8(this.baseOkapEndpoint + "orders/composite-orders", order, this.token);


//GET THE UPDATED PURCHASE ORDER FROM THE API AND PULL OUT THE ID FOR THE INSTANCE FOLIO CREATED:
logger.debug("getUpdatedPurchaseOrder");
String updatedPurchaseOrder = apiService.callApiGet(baseOkapEndpoint + "orders/composite-orders/" +orderUUID.toString() ,token);
String updatedPurchaseOrder = apiService.callApiGet(this.baseOkapEndpoint + "orders/composite-orders/" +orderUUID.toString() ,this.token);
JSONObject updatedPurchaseOrderJson = new JSONObject(updatedPurchaseOrder);
logger.info("updated purchase order...");
logger.info(updatedPurchaseOrderJson.toString(3));
Expand Down Expand Up @@ -483,7 +492,7 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept

// Get the Inventory Instance FOLIO created, so we can render the Instance HRID in the results
logger.debug("get InstanceResponse");
String instanceResponse = apiService.callApiGet(baseOkapEndpoint + "inventory/instances/" + instanceId, token);
String instanceResponse = apiService.callApiGet(this.baseOkapEndpoint + "inventory/instances/" + instanceId, this.token);
JSONObject instanceAsJson = new JSONObject(instanceResponse);
logger.debug(instanceAsJson.toString(3));
String hrid = instanceAsJson.getString("hrid");
Expand Down Expand Up @@ -530,7 +539,7 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept

// Overlay/Update Inventory Instance & Holding via mod-copycat
logger.debug("post copycatImportObject");
String copycatResponse = apiService.callApiPostWithUtf8(baseOkapEndpoint + "copycat/imports", copycatImportObject, token);
String copycatResponse = apiService.callApiPostWithUtf8(this.baseOkapEndpoint + "copycat/imports", copycatImportObject, this.token);
}

responseMessages.put(responseMessage);
Expand All @@ -557,7 +566,7 @@ public JSONArray upload(String fileName) throws IOException, InterruptedExcept

// this method validates required values and will return a JSONArray with error messages or an empty array if it passes

public JSONArray validateRequiredValues(MarcReader reader,String token, String baseOkapEndpoint ) {
public JSONArray validateRequiredValues(MarcReader reader) {

Record record = null;
JSONArray errorMessages = new JSONArray();
Expand Down Expand Up @@ -622,14 +631,14 @@ record = reader.next();

//VALIDATE THE ORGANIZATION, AND FUND
//STOP THE PROCESS IF AN ERRORS WERE FOUND
JSONObject orgValidationResult = validateOrganization(vendorCode, title, token, baseOkapEndpoint, recordCount);
JSONObject orgValidationResult = validateOrganization(vendorCode, title, recordCount);
if (orgValidationResult != null) {
logger.error("organization invalid: "+ vendorCode);
logger.error(record.toString());
errorMessages.put(orgValidationResult);
}

JSONObject fundValidationResult = validateFund(fundCode, title, token, baseOkapEndpoint);
JSONObject fundValidationResult = validateFund(fundCode, title);
if (fundValidationResult != null) {
//logger.error("fundCode invalid: "+ fundCode + " (price: "+ price +")");
logger.error(record.toString());
Expand Down Expand Up @@ -668,15 +677,19 @@ static String readFile(String path, Charset encoding) throws IOException {
//TODO
//THESE VALIDATION METHODS COULD
//USE IMPROVEMENT
public JSONObject validateFund(String fundCode, String title, String token, String baseOkapiEndpoint) throws IOException, InterruptedException, Exception {

//GET CURRENT FISCAL YEAR
String fiscalYearCode = (String) getMyContext().getAttribute("fiscalYearCode");
String fundEndpoint = baseOkapiEndpoint + "finance/funds?limit=30&offset=0&query=((code='" + fundCode + "'))";

public JSONObject validateFund(String fundCode, String title) throws IOException, InterruptedException, Exception {
JSONObject errorMessage = new JSONObject();
//GET CURRENT FISCAL YEAR
JSONObject fiscalYearJson = getCurrentFiscalYear();
if (fiscalYearJson == null) {
errorMessage.put("error", "Could not obtain current fiscal year form Folio");
return errorMessage;
}
String fiscalYearCode = fiscalYearJson.getString("code");
String fundEndpoint = this.baseOkapEndpoint + "finance/funds?limit=30&offset=0&query=((code='" + fundCode + "'))";


String fundResponse = apiService.callApiGet(fundEndpoint, token);
String fundResponse = apiService.callApiGet(fundEndpoint, this.token);
JSONObject fundsObject = new JSONObject(fundResponse);
//----------->VALIDATION #1: MAKE SURE THE FUND CODE EXISTS
if (fundsObject.getJSONArray("funds").length() < 1) {
Expand All @@ -688,8 +701,8 @@ public JSONObject validateFund(String fundCode, String title, String token, Stri
logger.debug("FUNDS: " + fundsObject.get("funds"));

//----------->VALIDATION #2: MAKE SURE THE FUND CODE FOR THE CURRENT FISCAL HAS ENOUGH MONEY
String fundBalanceQuery = baseOkapiEndpoint + "finance/budgets?query=(name==" + fundCode + "-" + fiscalYearCode + ")";
String fundBalanceResponse = apiService.callApiGet(fundBalanceQuery, token);
String fundBalanceQuery = this.baseOkapEndpoint + "finance/budgets?query=(name==" + fundCode + "-" + fiscalYearCode + ")";
String fundBalanceResponse = apiService.callApiGet(fundBalanceQuery, this.token);
JSONObject fundBalanceObject = new JSONObject(fundBalanceResponse);
if (fundBalanceObject.getJSONArray("budgets").length() < 1) {
errorMessage.put("error", "Fund code in file (" + fundCode + ") does not have a budget");
Expand All @@ -705,14 +718,12 @@ public JSONObject validateFund(String fundCode, String title, String token, Stri
/**
* @param orgCode
* @param title
* @param token
* @param baseOkapiEndpoint
* @return
* @throws IOException
* @throws InterruptedException
* @throws Exception
*/
public JSONObject validateOrganization(String orgCode, String title, String token, String baseOkapiEndpoint, Integer recordCount ) throws IOException, InterruptedException, Exception {
public JSONObject validateOrganization(String orgCode, String title, Integer recordCount ) throws IOException, InterruptedException, Exception {
JSONObject errorMessage = new JSONObject();

try {
Expand All @@ -721,9 +732,9 @@ public JSONObject validateOrganization(String orgCode, String title, String tok
logger.debug("encodedOrgCode: " + encodedOrgCode);

//LOOK UP THE ORGANIZATION
String organizationEndpoint = baseOkapiEndpoint + "organizations-storage/organizations?query=(code==" + encodedOrgCode + ")";
String organizationEndpoint = this.baseOkapEndpoint + "organizations-storage/organizations?query=(code==" + encodedOrgCode + ")";
logger.debug("organizationEndpoint: " + organizationEndpoint);
String orgLookupResponse = apiService.callApiGet(organizationEndpoint, token);
String orgLookupResponse = apiService.callApiGet(organizationEndpoint, this.token);
JSONObject orgObject = new JSONObject(orgLookupResponse);
//---------->VALIDATION: MAKE SURE THE ORGANIZATION CODE EXISTS
if (orgObject.getJSONArray("organizations").length() < 1) {
Expand Down Expand Up @@ -767,11 +778,6 @@ public JSONArray validateEnvironment( ) {
errMsg.put("error", "api tenant environment variable not found");
errors.put(errMsg);
}
if (StringUtils.isEmpty((String) getMyContext().getAttribute("fiscalYearCode"))) {
JSONObject errMsg = new JSONObject();
errMsg.put("error", "fiscalYearCode environment variable not found");
errors.put(errMsg);
}
if (StringUtils.isEmpty((String) getMyContext().getAttribute("billToDefault"))) {
JSONObject errMsg = new JSONObject();
errMsg.put("error", "billToDefault environment variable not found");
Expand All @@ -782,6 +788,62 @@ public JSONArray validateEnvironment( ) {
} else {
return errors;
}
}
}
public JSONObject getCurrentFiscalYear( ) {

String fiscalYearEndpoint = this.baseOkapEndpoint + "finance/fiscal-years";
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDate now = LocalDate.now();
try {
String fiscalYearResponse = this.apiService.callApiGet(this.baseOkapEndpoint + "finance/fiscal-years", this.token);

JSONObject fiscalYearsObject = new JSONObject(fiscalYearResponse);
JSONArray fiscalYearArray = fiscalYearsObject.getJSONArray("fiscalYears");
//System.out.println("date: "+ LocalDate.now());
for (int i = 0; i < fiscalYearArray.length(); i++) {
JSONObject thisFiscalYear = (JSONObject) fiscalYearArray.get(i);
// format: 2021-07-01T00:00:00.000+00:00
String periodStart = StringUtils.substringBefore(thisFiscalYear.getString("periodStart"), "T");
String periodEnd = StringUtils.substringBefore( thisFiscalYear.getString("periodEnd"), "T");
LocalDate beginDate = LocalDate.parse(periodStart, formatter);
LocalDate endDate = LocalDate.parse(periodEnd, formatter);

if (beginDate.compareTo(now)* now.compareTo(endDate) >= 0) {
return thisFiscalYear;
}
}
return null;
} catch (Exception e) {
logger.error(e.getMessage());
return null;
}
}

public String getAcquisitionMethodUUID(String value) {
//LOOK UP THE Acquisiton method
//logger.debug("lookup acquisition method");
String acquistionMethodString = "Purchase";
String acquisitionMethodEndpoint = baseOkapEndpoint + "orders/acquisition-methods?limit=3&offset=0&query=(value==" + value + ")";
String acquisitionMethodResponse;
try {
acquisitionMethodResponse = this.apiService.callApiGet(acquisitionMethodEndpoint, this.token);
JSONObject acquisitionMethodsObject = new JSONObject(acquisitionMethodResponse);

String acquisitionMethodUUID = (String) acquisitionMethodsObject.getJSONArray("acquisitionMethods").getJSONObject(0).get("id");
return acquisitionMethodUUID;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}

}
}

0 comments on commit 3e66473

Please sign in to comment.