use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class FinAccountServices method refundFinAccount.
public static Map<String, Object> refundFinAccount(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
GenericValue userLogin = (GenericValue) context.get("userLogin");
String finAccountId = (String) context.get("finAccountId");
Map<String, Object> result = null;
GenericValue finAccount;
try {
finAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
if (finAccount != null) {
// check to make sure the account is refundable
if (!"Y".equals(finAccount.getString("isRefundable"))) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountIsNotRefundable", locale));
}
// get the actual and available balance
BigDecimal availableBalance = finAccount.getBigDecimal("availableBalance");
BigDecimal actualBalance = finAccount.getBigDecimal("actualBalance");
// be settled first
if (actualBalance.compareTo(availableBalance) != 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeRefunded", locale));
}
// now we make sure there is something to refund
if (actualBalance.compareTo(BigDecimal.ZERO) > 0) {
BigDecimal remainingBalance = new BigDecimal(actualBalance.toString());
BigDecimal refundAmount = BigDecimal.ZERO;
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("finAccountTransTypeId", EntityOperator.EQUALS, "DEPOSIT"), EntityCondition.makeCondition("finAccountId", EntityOperator.EQUALS, finAccountId));
EntityCondition condition = EntityCondition.makeCondition(exprs, EntityOperator.AND);
try (EntityListIterator eli = EntityQuery.use(delegator).from("FinAccountTrans").where(condition).orderBy("-transactionDate").queryIterator()) {
GenericValue trans;
while (remainingBalance.compareTo(FinAccountHelper.ZERO) < 0 && (trans = eli.next()) != null) {
String orderId = trans.getString("orderId");
String orderItemSeqId = trans.getString("orderItemSeqId");
// make sure there is an order available to refund
if (orderId != null && orderItemSeqId != null) {
GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
GenericValue productStore = orderHeader.getRelatedOne("ProductStore", false);
GenericValue orderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryOne();
if (!"ITEM_CANCELLED".equals(orderItem.getString("statusId"))) {
// make sure the item hasn't already been returned
List<GenericValue> returnItems = orderItem.getRelated("ReturnItem", null, null, false);
if (UtilValidate.isEmpty(returnItems)) {
BigDecimal txAmt = trans.getBigDecimal("amount");
BigDecimal refAmt = txAmt;
if (remainingBalance.compareTo(txAmt) == -1) {
refAmt = remainingBalance;
}
remainingBalance = remainingBalance.subtract(refAmt);
refundAmount = refundAmount.add(refAmt);
// create the return header
Map<String, Object> rhCtx = UtilMisc.toMap("returnHeaderTypeId", "CUSTOMER_RETURN", "fromPartyId", finAccount.getString("ownerPartyId"), "toPartyId", productStore.getString("payToPartyId"), "userLogin", userLogin);
Map<String, Object> rhResp = dispatcher.runSync("createReturnHeader", rhCtx);
if (ServiceUtil.isError(rhResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(rhResp));
}
String returnId = (String) rhResp.get("returnId");
// create the return item
Map<String, Object> returnItemCtx = new HashMap<>();
returnItemCtx.put("returnId", returnId);
returnItemCtx.put("orderId", orderId);
returnItemCtx.put("description", orderItem.getString("itemDescription"));
returnItemCtx.put("orderItemSeqId", orderItemSeqId);
returnItemCtx.put("returnQuantity", BigDecimal.ONE);
returnItemCtx.put("receivedQuantity", BigDecimal.ONE);
returnItemCtx.put("returnPrice", refAmt);
returnItemCtx.put("returnReasonId", "RTN_NOT_WANT");
// refund return
returnItemCtx.put("returnTypeId", "RTN_REFUND");
returnItemCtx.put("returnItemTypeId", "RET_NPROD_ITEM");
returnItemCtx.put("userLogin", userLogin);
Map<String, Object> retItResp = dispatcher.runSync("createReturnItem", returnItemCtx);
if (ServiceUtil.isError(retItResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(retItResp));
}
String returnItemSeqId = (String) retItResp.get("returnItemSeqId");
// approve the return
Map<String, Object> appRet = UtilMisc.toMap("statusId", "RETURN_ACCEPTED", "returnId", returnId, "userLogin", userLogin);
Map<String, Object> appResp = dispatcher.runSync("updateReturnHeader", appRet);
if (ServiceUtil.isError(appResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(appResp));
}
// "receive" the return - should trigger the refund
Map<String, Object> recRet = UtilMisc.toMap("statusId", "RETURN_RECEIVED", "returnId", returnId, "userLogin", userLogin);
Map<String, Object> recResp = dispatcher.runSync("updateReturnHeader", recRet);
if (ServiceUtil.isError(recResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(recResp));
}
// get the return item
GenericValue returnItem = EntityQuery.use(delegator).from("ReturnItem").where("returnId", returnId, "returnItemSeqId", returnItemSeqId).queryOne();
GenericValue response = returnItem.getRelatedOne("ReturnItemResponse", false);
if (response == null) {
throw new GeneralException("No return response found for: " + returnItem.getPrimaryKey());
}
String paymentId = response.getString("paymentId");
// create the adjustment transaction
Map<String, Object> txCtx = new HashMap<>();
txCtx.put("finAccountTransTypeId", "ADJUSTMENT");
txCtx.put("finAccountId", finAccountId);
txCtx.put("orderId", orderId);
txCtx.put("orderItemSeqId", orderItemSeqId);
txCtx.put("paymentId", paymentId);
txCtx.put("amount", refAmt.negate());
txCtx.put("partyId", finAccount.getString("ownerPartyId"));
txCtx.put("userLogin", userLogin);
Map<String, Object> txResp = dispatcher.runSync("createFinAccountTrans", txCtx);
if (ServiceUtil.isError(txResp)) {
throw new GeneralException(ServiceUtil.getErrorMessage(txResp));
}
}
}
}
}
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// check to make sure we balanced out
if (remainingBalance.compareTo(FinAccountHelper.ZERO) == 1) {
result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resourceError, "AccountingFinAccountPartiallyRefunded", locale));
}
}
}
if (result == null) {
result = ServiceUtil.returnSuccess();
}
return result;
}
use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class PaymentGatewayServices method retryFailedAuthNsfs.
public static Map<String, Object> retryFailedAuthNsfs(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
// get the date/time for one week before now since we'll only retry once a week for NSFs
Calendar calcCal = Calendar.getInstance();
calcCal.setTimeInMillis(System.currentTimeMillis());
calcCal.add(Calendar.WEEK_OF_YEAR, -1);
Timestamp oneWeekAgo = new Timestamp(calcCal.getTimeInMillis());
EntityQuery eq = EntityQuery.use(delegator).from("OrderPaymentPreference").where(EntityCondition.makeCondition("needsNsfRetry", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition(ModelEntity.STAMP_FIELD, EntityOperator.LESS_THAN_EQUAL_TO, oneWeekAgo)).orderBy("orderId");
try (EntityListIterator eli = eq.queryIterator()) {
List<String> processList = new LinkedList<>();
if (eli != null) {
Debug.logInfo("Processing failed order re-auth(s)", module);
GenericValue value = null;
while (((value = eli.next()) != null)) {
String orderId = value.getString("orderId");
if (!processList.contains(orderId)) {
// just try each order once
try {
// each re-try is independent of each other; if one fails it should not effect the others
dispatcher.runAsync("retryFailedOrderAuth", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
processList.add(orderId);
} catch (GenericServiceException e) {
Debug.logError(e, module);
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class EntityDataServices method unwrapByteWrappers.
public static Map<String, Object> unwrapByteWrappers(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
String entityName = (String) context.get("entityName");
String fieldName = (String) context.get("fieldName");
Locale locale = (Locale) context.get("locale");
try (EntityListIterator eli = EntityQuery.use(delegator).from(entityName).queryIterator()) {
GenericValue currentValue;
while ((currentValue = eli.next()) != null) {
byte[] bytes = currentValue.getBytes(fieldName);
if (bytes != null) {
currentValue.setBytes(fieldName, bytes);
currentValue.store();
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Error unwrapping ByteWrapper records: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorUnwrappingRecords", UtilMisc.toMap("errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class EntitySyncContext method assembleValuesToStore.
public ArrayList<GenericValue> assembleValuesToStore() throws SyncDataErrorException {
// simulate two ordered lists and merge them on-the-fly for faster combined sorting
// make it an ArrayList to easily merge in sorted lists
ArrayList<GenericValue> valuesToStore = new ArrayList<GenericValue>();
if (this.nextUpdateTxTime != null && (this.nextUpdateTxTime.equals(currentRunEndTime) || this.nextUpdateTxTime.after(currentRunEndTime))) {
// this means that for all entities in this pack we found on the last pass that there would be nothing for this one, so just return nothing...
return valuesToStore;
}
// Debug.logInfo("Getting values to store; currentRunStartTime=" + currentRunStartTime + ", currentRunEndTime=" + currentRunEndTime, module);
int entitiesSkippedForKnownNext = 0;
// iterate through entities, get all records with tx stamp in the current time range, put all in a single list
for (ModelEntity modelEntity : entityModelToUseList) {
int insertBefore = 0;
// first test to see if we know that there are no records for this entity in this time period...
Timestamp knownNextUpdateTime = this.nextEntityUpdateTxTime.get(modelEntity.getEntityName());
if (knownNextUpdateTime != null && (knownNextUpdateTime.equals(currentRunEndTime) || knownNextUpdateTime.after(currentRunEndTime))) {
entitiesSkippedForKnownNext++;
continue;
}
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin(7200);
} catch (GenericTransactionException e) {
throw new SyncDataErrorException("Unable to begin JTA transaction", e);
}
try {
// get all values that were updated, but NOT created in the current time range; if no info on created stamp, that's okay we'll include it here because it won't have been included in the valuesToCreate list
EntityCondition createdBeforeStartCond = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunStartTime));
EntityCondition findValCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunStartTime), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime), createdBeforeStartCond);
EntityListIterator eli = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findValCondition).orderBy(ModelEntity.STAMP_TX_FIELD, ModelEntity.STAMP_FIELD).queryIterator();
GenericValue nextValue = null;
long valuesPerEntity = 0;
while ((nextValue = eli.next()) != null) {
// find first value in valuesToStore list, starting with the current insertBefore value, that has a STAMP_TX_FIELD after the nextValue.STAMP_TX_FIELD, then do the same with STAMP_FIELD
while (insertBefore < valuesToStore.size() && valuesToStore.get(insertBefore).getTimestamp(ModelEntity.STAMP_TX_FIELD).before(nextValue.getTimestamp(ModelEntity.STAMP_TX_FIELD))) {
insertBefore++;
}
while (insertBefore < valuesToStore.size() && valuesToStore.get(insertBefore).getTimestamp(ModelEntity.STAMP_FIELD).before(nextValue.getTimestamp(ModelEntity.STAMP_FIELD))) {
insertBefore++;
}
valuesToStore.add(insertBefore, nextValue);
valuesPerEntity++;
}
eli.close();
// if we didn't find anything for this entity, find the next value's Timestamp and keep track of it
if (valuesPerEntity == 0) {
Timestamp startCheckStamp = new Timestamp(System.currentTimeMillis() - syncEndBufferMillis);
EntityCondition findNextCondition = EntityCondition.makeCondition(EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.GREATER_THAN_EQUAL_TO, currentRunEndTime), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition(ModelEntity.CREATE_STAMP_TX_FIELD, EntityOperator.LESS_THAN, currentRunEndTime));
EntityListIterator eliNext = EntityQuery.use(delegator).from(modelEntity.getEntityName()).where(findNextCondition).orderBy(ModelEntity.STAMP_TX_FIELD).queryIterator();
// get the first element and it's tx time value...
GenericValue firstVal = eliNext.next();
eliNext.close();
Timestamp nextTxTime;
if (firstVal != null) {
nextTxTime = firstVal.getTimestamp(ModelEntity.CREATE_STAMP_TX_FIELD);
} else {
// no results? well, then it's safe to say that up to the pre-querytime (minus the buffer, as usual) we are okay
nextTxTime = startCheckStamp;
}
if (this.nextUpdateTxTime == null || nextTxTime.before(this.nextUpdateTxTime)) {
this.nextUpdateTxTime = nextTxTime;
Debug.logInfo("EntitySync: Set nextUpdateTxTime to [" + nextTxTime + "]", module);
}
Timestamp curEntityNextTxTime = this.nextEntityUpdateTxTime.get(modelEntity.getEntityName());
if (curEntityNextTxTime == null || nextTxTime.before(curEntityNextTxTime)) {
this.nextEntityUpdateTxTime.put(modelEntity.getEntityName(), nextTxTime);
Debug.logInfo("EntitySync: Set nextEntityUpdateTxTime to [" + nextTxTime + "] for the entity [" + modelEntity.getEntityName() + "]", module);
}
}
} catch (GenericEntityException e) {
try {
TransactionUtil.rollback(beganTransaction, "Entity Engine error in assembleValuesToStore", e);
} catch (GenericTransactionException e2) {
Debug.logWarning(e2, "Unable to call rollback()", module);
}
throw new SyncDataErrorException("Error getting values to store from the datasource", e);
} catch (Throwable t) {
try {
TransactionUtil.rollback(beganTransaction, "General error in assembleValuesToStore", t);
} catch (GenericTransactionException e2) {
Debug.logWarning(e2, "Unable to call rollback()", module);
}
throw new SyncDataErrorException("Caught runtime error while getting values to store", t);
}
try {
TransactionUtil.commit(beganTransaction);
} catch (GenericTransactionException e) {
throw new SyncDataErrorException("Commit transaction failed", e);
}
}
if (entitiesSkippedForKnownNext > 0) {
if (Debug.infoOn())
Debug.logInfo("In assembleValuesToStore skipped [" + entitiesSkippedForKnownNext + "/" + entityModelToUseList + "] entities for the time period ending at [" + currentRunEndTime + "] because of next known update times", module);
}
// TEST SECTION: leave false for normal use
boolean logValues = false;
if (logValues && valuesToStore.size() > 0) {
StringBuilder toStoreInfo = new StringBuilder();
for (GenericValue valueToStore : valuesToStore) {
toStoreInfo.append("\n-->[");
toStoreInfo.append(valueToStore.get(ModelEntity.STAMP_TX_FIELD));
toStoreInfo.append(":");
toStoreInfo.append(valueToStore.get(ModelEntity.STAMP_FIELD));
toStoreInfo.append("] ");
toStoreInfo.append(valueToStore.getPrimaryKey());
}
Debug.logInfo(toStoreInfo.toString(), module);
}
// this calculation is false, so it needs to be nullified
if (valuesToStore.size() > 0) {
this.nextUpdateTxTime = null;
}
return valuesToStore;
}
use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.
the class Iterate method exec.
@Override
public boolean exec(MethodContext methodContext) throws MiniLangException {
if (listFma.isEmpty()) {
if (Debug.verboseOn()) {
Debug.logVerbose("Collection not found, doing nothing: " + this, module);
}
return true;
}
Object oldEntryValue = entryFma.get(methodContext.getEnvMap());
Object objList = listFma.get(methodContext.getEnvMap());
if (objList instanceof EntityListIterator) {
try (EntityListIterator eli = (EntityListIterator) objList) {
GenericValue theEntry;
while ((theEntry = eli.next()) != null) {
entryFma.put(methodContext.getEnvMap(), theEntry);
try {
for (MethodOperation methodOperation : subOps) {
if (!methodOperation.exec(methodContext)) {
return false;
}
}
} catch (MiniLangException e) {
if (e instanceof BreakElementException) {
break;
}
if (e instanceof ContinueElementException) {
continue;
}
throw e;
}
}
} catch (GenericEntityException e) {
throw new MiniLangRuntimeException("Error with entityListIterator: " + e.getMessage(), this);
}
} else if (objList instanceof Collection<?>) {
Collection<Object> theCollection = UtilGenerics.checkCollection(objList);
if (theCollection.size() == 0) {
if (Debug.verboseOn()) {
Debug.logVerbose("Collection has zero entries, doing nothing: " + this, module);
}
return true;
}
for (Object theEntry : theCollection) {
entryFma.put(methodContext.getEnvMap(), theEntry);
try {
for (MethodOperation methodOperation : subOps) {
if (!methodOperation.exec(methodContext)) {
return false;
}
}
} catch (MiniLangException e) {
if (e instanceof BreakElementException) {
break;
}
if (e instanceof ContinueElementException) {
continue;
}
throw e;
}
}
} else if (objList instanceof Iterator<?>) {
Iterator<Object> theIterator = UtilGenerics.cast(objList);
if (!theIterator.hasNext()) {
if (Debug.verboseOn()) {
Debug.logVerbose("Iterator has zero entries, doing nothing: " + this, module);
}
return true;
}
while (theIterator.hasNext()) {
Object theEntry = theIterator.next();
entryFma.put(methodContext.getEnvMap(), theEntry);
try {
for (MethodOperation methodOperation : subOps) {
if (!methodOperation.exec(methodContext)) {
return false;
}
}
} catch (MiniLangException e) {
if (e instanceof BreakElementException) {
break;
}
if (e instanceof ContinueElementException) {
continue;
}
throw e;
}
}
} else {
if (Debug.verboseOn()) {
Debug.logVerbose("Cannot iterate over a " + objList == null ? "null object" : objList.getClass().getName() + ", doing nothing: " + this, module);
}
return true;
}
entryFma.put(methodContext.getEnvMap(), oldEntryValue);
return true;
}
Aggregations