Search in sources :

Example 36 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class InvoiceServices method createCommissionInvoices.

// Service for creating commission invoices
public static Map<String, Object> createCommissionInvoices(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds"));
    List<Map<String, String>> invoicesCreated = new LinkedList<>();
    Map<String, List<Map<String, Object>>> commissionParties = new HashMap<>();
    for (String salesInvoiceId : salesInvoiceIds) {
        List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds"));
        BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId);
        if (amountTotal.signum() == 0) {
            Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal + "], so no commission invoice will be created", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionZeroInvoiceAmount", locale));
        }
        BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING);
        GenericValue invoice = null;
        boolean isReturn = false;
        List<String> billFromVendorInvoiceRoles;
        List<GenericValue> invoiceItems;
        try {
            List<EntityExpr> invoiceRoleConds = UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR"));
            EntityQuery roleQuery = EntityQuery.use(delegator).select("partyId").from("InvoiceRole").where(invoiceRoleConds);
            billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(roleQuery.queryList(), "partyId", true);
            invoiceRoleConds = UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SALES_REP"));
            // if the receiving parties is empty then we will create commission invoices for all sales agent associated to sales invoice.
            if (UtilValidate.isEmpty(salesRepPartyIds)) {
                salesRepPartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isEmpty(salesRepPartyIds)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "No party found with role sales representative for sales invoice " + salesInvoiceId, locale));
                }
            } else {
                List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) {
                    salesRepPartyIds = UtilGenerics.checkList(CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds));
                }
            }
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", salesInvoiceId).queryOne();
            String invoiceTypeId = invoice.getString("invoiceTypeId");
            if ("CUST_RTN_INVOICE".equals(invoiceTypeId)) {
                isReturn = true;
            } else if (!"SALES_INVOICE".equals(invoiceTypeId)) {
                Debug.logWarning("This type of invoice has no commission; returning success", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionInvalid", locale));
            }
            invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", salesInvoiceId).queryList();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        // Determine commissions for various parties.
        for (GenericValue invoiceItem : invoiceItems) {
            BigDecimal amount = BigDecimal.ZERO;
            BigDecimal quantity = invoiceItem.getBigDecimal("quantity");
            amount = invoiceItem.getBigDecimal("amount");
            amount = isReturn ? amount.negate() : amount;
            String productId = invoiceItem.getString("productId");
            String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId");
            String invoiceId = invoiceItem.getString("invoiceId");
            // Determine commission parties for this invoiceItem
            if (UtilValidate.isNotEmpty(productId)) {
                Map<String, Object> resultMap = null;
                try {
                    resultMap = dispatcher.runSync("getCommissionForProduct", UtilMisc.<String, Object>toMap("productId", productId, "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId, "invoiceItemTypeId", invoiceItem.getString("invoiceItemTypeId"), "amount", amount, "quantity", quantity, "userLogin", userLogin));
                    if (ServiceUtil.isError(resultMap)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resultMap));
                    }
                } catch (GenericServiceException e) {
                    return ServiceUtil.returnError(e.getMessage());
                }
                // build a Map of partyIds (both to and from) in a commission and the amounts
                // Note that getCommissionForProduct returns a List of Maps with a lot values.  See services.xml definition for reference.
                List<Map<String, Object>> itemCommissions = UtilGenerics.checkList(resultMap.get("commissions"));
                if (UtilValidate.isNotEmpty(itemCommissions)) {
                    for (Map<String, Object> commissionMap : itemCommissions) {
                        commissionMap.put("invoice", invoice);
                        commissionMap.put("appliedFraction", appliedFraction);
                        if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom")) || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) {
                            continue;
                        }
                        String partyIdFromTo = (String) commissionMap.get("partyIdFrom") + (String) commissionMap.get("partyIdTo");
                        if (!commissionParties.containsKey(partyIdFromTo)) {
                            commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap));
                        } else {
                            (commissionParties.get(partyIdFromTo)).add(commissionMap);
                        }
                    }
                }
            }
        }
    }
    Timestamp now = UtilDateTime.nowTimestamp();
    // Create invoice for each commission receiving party
    for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) {
        List<GenericValue> toStore = new LinkedList<>();
        List<Map<String, Object>> commList = commissionParty.getValue();
        // get the billing parties
        if (UtilValidate.isEmpty(commList)) {
            continue;
        }
        // From and To are reversed between commission and invoice
        String partyIdBillTo = (String) (commList.get(0)).get("partyIdFrom");
        String partyIdBillFrom = (String) (commList.get(0)).get("partyIdTo");
        GenericValue invoice = (GenericValue) (commList.get(0)).get("invoice");
        BigDecimal appliedFraction = (BigDecimal) (commList.get(0)).get("appliedFraction");
        Long days = (Long) (commList.get(0)).get("days");
        // create the invoice record
        // To and From are in commission's sense, opposite for invoice
        Map<String, Object> createInvoiceMap = new HashMap<>();
        createInvoiceMap.put("partyId", partyIdBillTo);
        createInvoiceMap.put("partyIdFrom", partyIdBillFrom);
        createInvoiceMap.put("invoiceDate", now);
        // if there were days associated with the commission agreement, then set a dueDate for the invoice.
        if (days != null) {
            createInvoiceMap.put("dueDate", UtilDateTime.getDayEnd(now, days));
        }
        createInvoiceMap.put("invoiceTypeId", "COMMISSION_INVOICE");
        // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...)
        createInvoiceMap.put("statusId", "INVOICE_IN_PROCESS");
        createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId"));
        createInvoiceMap.put("userLogin", userLogin);
        // store the invoice first
        Map<String, Object> createInvoiceResult;
        try {
            createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap);
            if (ServiceUtil.isError(createInvoiceResult)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null, null);
            }
        } catch (GenericServiceException e) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null, null);
        }
        String invoiceId = (String) createInvoiceResult.get("invoiceId");
        // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store
        GenericValue partyContactMechPurpose = null;
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose").where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "BILLING_LOCATION").queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "BILLING_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose").where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "PAYMENT_LOCATION").queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech", UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId", "PAYMENT_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        // create the item records
        for (Map<String, Object> commissionMap : commList) {
            BigDecimal elemAmount = ((BigDecimal) commissionMap.get("commission")).multiply(appliedFraction);
            BigDecimal quantity = (BigDecimal) commissionMap.get("quantity");
            String invoiceIdFrom = (String) commissionMap.get("invoiceId");
            String invoiceItemSeqIdFrom = (String) commissionMap.get("invoiceItemSeqId");
            elemAmount = elemAmount.setScale(DECIMALS, ROUNDING);
            Map<String, Object> resMap = null;
            try {
                resMap = dispatcher.runSync("createInvoiceItem", UtilMisc.toMap("invoiceId", invoiceId, "productId", commissionMap.get("productId"), "invoiceItemTypeId", "COMM_INV_ITEM", "quantity", quantity, "amount", elemAmount, "userLogin", userLogin));
                if (ServiceUtil.isError(resMap)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionErrorItem", locale), null, null, resMap);
                }
                resMap = dispatcher.runSync("createInvoiceItemAssoc", UtilMisc.toMap("invoiceIdFrom", invoiceIdFrom, "invoiceItemSeqIdFrom", invoiceItemSeqIdFrom, "invoiceIdTo", invoiceId, "invoiceItemSeqIdTo", resMap.get("invoiceItemSeqId"), "invoiceItemAssocTypeId", "COMMISSION_INVOICE", "partyIdFrom", partyIdBillFrom, "partyIdTo", partyIdBillTo, "quantity", quantity, "amount", elemAmount, "userLogin", userLogin));
                if (ServiceUtil.isError(resMap)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resMap));
                }
            } catch (GenericServiceException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
        }
        // store value objects
        try {
            delegator.storeAll(toStore);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Entity/data problem creating commission invoice: " + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingInvoiceCommissionEntityDataProblem", UtilMisc.toMap("reason", e.toString()), locale));
        }
        invoicesCreated.add(UtilMisc.<String, String>toMap("commissionInvoiceId", invoiceId, "salesRepresentative ", partyIdBillFrom));
    }
    String invCreated = Integer.toString(invoicesCreated.size());
    Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "AccountingCommissionInvoicesCreated", UtilMisc.toMap("invoicesCreated", invCreated), locale));
    Debug.logInfo("Created Commission invoices for each commission receiving parties " + invCreated, module);
    result.put("invoicesCreated", invoicesCreated);
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) LinkedList(java.util.LinkedList) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 37 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class InvoiceWorker method getInvoiceApplied.

/**
 * Returns amount applied to invoice before an asOfDateTime, based on Payment.effectiveDate &lt;= asOfDateTime
 *
 * @param delegator the delegator
 * @param invoiceId the invoice id
 * @param asOfDateTime - a Timestamp
 * @return returns amount applied to invoice before an asOfDateTime
 */
public static BigDecimal getInvoiceApplied(Delegator delegator, String invoiceId, Timestamp asOfDateTime, Boolean actualCurrency) {
    if (delegator == null) {
        throw new IllegalArgumentException("Null delegator is not allowed in this method");
    }
    BigDecimal invoiceApplied = BigDecimal.ZERO;
    List<GenericValue> paymentApplications = null;
    // lookup payment applications which took place before the asOfDateTime for this invoice
    EntityConditionList<EntityExpr> dateCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("effectiveDate", EntityOperator.EQUALS, null), EntityCondition.makeCondition("effectiveDate", EntityOperator.LESS_THAN_EQUAL_TO, asOfDateTime)), EntityOperator.OR);
    EntityConditionList<EntityCondition> conditions = EntityCondition.makeCondition(UtilMisc.toList(dateCondition, EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, invoiceId)), EntityOperator.AND);
    try {
        paymentApplications = EntityQuery.use(delegator).from("PaymentAndApplication").where(conditions).orderBy("effectiveDate").queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e, "Trouble getting paymentApplicationlist", module);
    }
    if (paymentApplications != null) {
        for (GenericValue paymentApplication : paymentApplications) {
            invoiceApplied = invoiceApplied.add(paymentApplication.getBigDecimal("amountApplied")).setScale(decimals, rounding);
        }
    }
    if (UtilValidate.isNotEmpty(invoiceApplied) && !actualCurrency) {
        invoiceApplied = invoiceApplied.multiply(getInvoiceCurrencyConversionRate(delegator, invoiceId)).setScale(decimals, rounding);
    }
    return invoiceApplied;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) BigDecimal(java.math.BigDecimal) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 38 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class PaymentGatewayServices method releaseOrderPayments.

/**
 * Releases authorizations through service calls to the defined processing service for the ProductStore/PaymentMethodType
 * @return COMPLETE|FAILED|ERROR for complete processing of ALL payments.
 */
public static Map<String, Object> releaseOrderPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> result = ServiceUtil.returnSuccess();
    String orderId = "";
    // Get the OrderPaymentPreference
    GenericValue paymentPref = null;
    try {
        if (orderPaymentPreferenceId != null) {
            paymentPref = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceId).queryOne();
            orderId = paymentPref.getString("orderId");
        } else {
            orderId = (String) context.get("orderId");
        }
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
    }
    // get the payment preferences
    List<GenericValue> paymentPrefs = null;
    try {
        // get the valid payment prefs
        List<EntityExpr> othExpr = UtilMisc.toList(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EFT_ACCOUNT"));
        othExpr.add(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "GIFT_CARD"));
        othExpr.add(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "FIN_ACCOUNT"));
        EntityCondition con1 = EntityCondition.makeCondition(othExpr, EntityJoinOperator.OR);
        EntityCondition statExpr = EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_SETTLED");
        EntityCondition con2 = EntityCondition.makeCondition(UtilMisc.toList(con1, statExpr), EntityOperator.AND);
        EntityCondition authExpr = EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_AUTHORIZED");
        EntityCondition con3 = EntityCondition.makeCondition(UtilMisc.toList(con2, authExpr), EntityOperator.OR);
        EntityExpr orderExpr = EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId);
        EntityCondition con4 = EntityCondition.makeCondition(UtilMisc.toList(con3, orderExpr), EntityOperator.AND);
        paymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where(con4).queryList();
    } catch (GenericEntityException gee) {
        Debug.logError(gee, "Problems getting entity record(s), see stack trace", module);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, "ERROR: Could not get order information (" + gee.toString() + ").");
        return result;
    }
    // return complete if no payment prefs were found
    if (paymentPrefs.size() == 0) {
        Debug.logWarning("No OrderPaymentPreference records available for release", module);
        result.put("processResult", "COMPLETE");
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
        return result;
    }
    // iterate over the prefs and release each one
    List<GenericValue> finished = new LinkedList<>();
    for (GenericValue pPref : paymentPrefs) {
        Map<String, Object> releaseContext = UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", pPref.getString("orderPaymentPreferenceId"));
        Map<String, Object> releaseResult = null;
        try {
            releaseResult = dispatcher.runSync("releaseOrderPaymentPreference", releaseContext);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problem calling releaseOrderPaymentPreference service for orderPaymentPreferenceId" + paymentPref.getString("orderPaymentPreferenceId"), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale) + " " + paymentPref.getString("orderPaymentPreferenceId"));
        }
        if (ServiceUtil.isError(releaseResult)) {
            Debug.logError(ServiceUtil.getErrorMessage(releaseResult), module);
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResult));
        } else if (!ServiceUtil.isFailure(releaseResult)) {
            finished.add(paymentPref);
        }
    }
    result = ServiceUtil.returnSuccess();
    if (finished.size() == paymentPrefs.size()) {
        result.put("processResult", "COMPLETE");
    } else {
        result.put("processResult", "FAILED");
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 39 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class JobManager method poll.

/**
 * Scans the JobSandbox entity and returns a list of jobs that are due to run.
 * Returns an empty list if there are no jobs due to run.
 * This method is called by the {@link JobPoller} polling thread.
 */
protected List<Job> poll(int limit) {
    assertIsRunning();
    // The rest of this method logs exceptions and does not throw them.
    // The idea is to keep the JobPoller working even when a database
    // connection is not available (possible on a saturated server).
    DispatchContext dctx = getDispatcher().getDispatchContext();
    if (dctx == null) {
        Debug.logWarning("Unable to locate DispatchContext object; not running job!", module);
        return Collections.emptyList();
    }
    // basic query
    List<EntityExpr> expressions = UtilMisc.toList(EntityCondition.makeCondition("runTime", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("startDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
    // limit to just defined pools
    List<String> pools = null;
    try {
        pools = getRunPools();
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Unable to get run pools - not running job: ", module);
        return Collections.emptyList();
    }
    List<EntityExpr> poolsExpr = UtilMisc.toList(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, null));
    if (!pools.isEmpty()) {
        for (String poolName : pools) {
            poolsExpr.add(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, poolName));
        }
    }
    List<Job> poll = new ArrayList<>(limit);
    // make the conditions
    EntityCondition baseCondition = EntityCondition.makeCondition(expressions);
    EntityCondition poolCondition = EntityCondition.makeCondition(poolsExpr, EntityOperator.OR);
    EntityCondition mainCondition = EntityCondition.makeCondition(UtilMisc.toList(baseCondition, poolCondition));
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        if (!beganTransaction) {
            Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
            return poll;
        }
        try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("runTime").queryIterator()) {
            GenericValue jobValue = jobsIterator.next();
            while (jobValue != null) {
                // Claim ownership of this value. Using storeByCondition to avoid a race condition.
                List<EntityExpr> updateExpression = UtilMisc.toList(EntityCondition.makeCondition("jobId", EntityOperator.EQUALS, jobValue.get("jobId")), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
                int rowsUpdated = delegator.storeByCondition("JobSandbox", UtilMisc.toMap("runByInstanceId", instanceId), EntityCondition.makeCondition(updateExpression));
                if (rowsUpdated == 1) {
                    poll.add(new PersistedServiceJob(dctx, jobValue, null));
                    if (poll.size() == limit) {
                        break;
                    }
                }
                jobValue = jobsIterator.next();
            }
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
        }
        TransactionUtil.commit(beganTransaction);
    } catch (Throwable t) {
        String errMsg = "Exception thrown while polling JobSandbox: ";
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, t);
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
        }
        Debug.logWarning(t, errMsg, module);
        return Collections.emptyList();
    }
    if (poll.isEmpty()) {
        // No jobs to run, see if there are any jobs to purge
        Calendar cal = Calendar.getInstance();
        try {
            int daysToKeep = ServiceConfigUtil.getServiceEngine().getThreadPool().getPurgeJobDays();
            cal.add(Calendar.DAY_OF_YEAR, -daysToKeep);
        } catch (GenericConfigException e) {
            Debug.logWarning(e, "Unable to get purge job days: ", module);
            return Collections.emptyList();
        }
        Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
        List<EntityExpr> finExp = UtilMisc.toList(EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
        List<EntityExpr> canExp = UtilMisc.toList(EntityCondition.makeCondition("cancelDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
        EntityCondition doneCond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(canExp), EntityCondition.makeCondition(finExp)), EntityOperator.OR);
        mainCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runByInstanceId", instanceId), doneCond));
        beganTransaction = false;
        try {
            beganTransaction = TransactionUtil.begin();
            if (!beganTransaction) {
                Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
                return Collections.emptyList();
            }
            try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("jobId").queryIterator()) {
                GenericValue jobValue = jobsIterator.next();
                while (jobValue != null) {
                    poll.add(new PurgeJob(jobValue));
                    if (poll.size() == limit) {
                        break;
                    }
                    jobValue = jobsIterator.next();
                }
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
            TransactionUtil.commit(beganTransaction);
        } catch (Throwable t) {
            String errMsg = "Exception thrown while polling JobSandbox: ";
            try {
                TransactionUtil.rollback(beganTransaction, errMsg, t);
            } catch (GenericEntityException e) {
                Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
            }
            Debug.logWarning(t, errMsg, module);
            return Collections.emptyList();
        }
    }
    return poll;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) DispatchContext(org.apache.ofbiz.service.DispatchContext) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 40 with EntityExpr

use of org.apache.ofbiz.entity.condition.EntityExpr in project ofbiz-framework by apache.

the class CatalogUrlSeoTransform method forwardUri.

/**
 * Forward a uri according to forward pattern regular expressions.
 * @param request
 * @param response
 * @param delegator
 * @param controlServlet
 * @return boolean to indicate whether the uri is forwarded.
 * @throws ServletException
 * @throws IOException
 */
public static boolean forwardUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator, String controlServlet) throws ServletException, IOException {
    String pathInfo = request.getRequestURI();
    String contextPath = request.getContextPath();
    if (!isCategoryMapInitialed()) {
        initCategoryMap(request, delegator);
    }
    if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
        return false;
    }
    List<String> pathElements = StringUtil.split(pathInfo, "/");
    if (UtilValidate.isEmpty(pathElements)) {
        return false;
    }
    // remove context path
    pathInfo = SeoUrlUtil.removeContextPath(pathInfo, contextPath);
    // remove servlet path
    pathInfo = SeoUrlUtil.removeContextPath(pathInfo, request.getServletPath());
    if (pathInfo.startsWith("/" + CatalogUrlServlet.CATEGORY_REQUEST + "/")) {
        return forwardCategoryUri(request, response, delegator, controlServlet);
    }
    String lastPathElement = pathElements.get(pathElements.size() - 1);
    String categoryId = null;
    String productId = null;
    if (UtilValidate.isNotEmpty(lastPathElement)) {
        if (UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) {
            if (lastPathElement.endsWith(SeoConfigUtil.getCategoryUrlSuffix())) {
                lastPathElement = lastPathElement.substring(0, lastPathElement.length() - SeoConfigUtil.getCategoryUrlSuffix().length());
            } else {
                return false;
            }
        }
        if (SeoConfigUtil.isCategoryNameEnabled() || pathInfo.startsWith("/" + CatalogUrlServlet.CATEGORY_REQUEST + "/")) {
            for (Entry<String, String> entry : categoryNameIdMap.entrySet()) {
                String categoryName = entry.getKey();
                if (lastPathElement.startsWith(categoryName)) {
                    categoryId = entry.getValue();
                    if (!lastPathElement.equals(categoryName)) {
                        lastPathElement = lastPathElement.substring(categoryName.length() + URL_HYPHEN.length());
                    }
                    break;
                }
            }
            if (UtilValidate.isEmpty(categoryId)) {
                categoryId = lastPathElement;
            }
        }
        if (UtilValidate.isNotEmpty(lastPathElement)) {
            List<String> urlElements = StringUtil.split(lastPathElement, URL_HYPHEN);
            if (UtilValidate.isEmpty(urlElements)) {
                try {
                    if (EntityQuery.use(delegator).from("Product").where("productId", lastPathElement).cache().queryOne() != null) {
                        productId = lastPathElement;
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo + "]: " + e.toString(), module);
                }
            } else {
                int i = urlElements.size() - 1;
                String tempProductId = urlElements.get(i);
                while (i >= 0) {
                    try {
                        List<EntityExpr> exprs = new LinkedList<>();
                        exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, lastPathElement));
                        exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, tempProductId));
                        List<GenericValue> products = delegator.findList("Product", EntityCondition.makeCondition(exprs, EntityOperator.OR), UtilMisc.toSet("productId", "productName"), null, null, true);
                        if (products != null && products.size() > 0) {
                            if (products.size() == 1) {
                                productId = products.get(0).getString("productId");
                                break;
                            }
                            productId = tempProductId;
                            break;
                        } else if (i > 0) {
                            tempProductId = urlElements.get(i - 1) + URL_HYPHEN + tempProductId;
                        }
                    } catch (GenericEntityException e) {
                        Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo + "]: " + e.toString(), module);
                    }
                    i--;
                }
            }
        }
    }
    if (UtilValidate.isNotEmpty(productId) || UtilValidate.isNotEmpty(categoryId)) {
        if (categoryId != null) {
            request.setAttribute("productCategoryId", categoryId);
        }
        if (productId != null) {
            request.setAttribute("product_id", productId);
            request.setAttribute("productId", productId);
        }
        StringBuilder urlBuilder = new StringBuilder();
        if (UtilValidate.isNotEmpty(controlServlet)) {
            urlBuilder.append("/" + controlServlet);
        }
        urlBuilder.append("/" + (productId != null ? CatalogUrlServlet.PRODUCT_REQUEST : CatalogUrlServlet.CATEGORY_REQUEST));
        UrlServletHelper.setViewQueryParameters(request, urlBuilder);
        Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module);
        RequestDispatcher rd = request.getRequestDispatcher(urlBuilder.toString());
        rd.forward(request, response);
        return true;
    }
    return false;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr) LinkedList(java.util.LinkedList) RequestDispatcher(javax.servlet.RequestDispatcher)

Aggregations

EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)57 GenericValue (org.apache.ofbiz.entity.GenericValue)51 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)47 Delegator (org.apache.ofbiz.entity.Delegator)29 LinkedList (java.util.LinkedList)27 HashMap (java.util.HashMap)24 Locale (java.util.Locale)23 BigDecimal (java.math.BigDecimal)19 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)18 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)16 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)15 Timestamp (java.sql.Timestamp)13 ArrayList (java.util.ArrayList)11 GeneralException (org.apache.ofbiz.base.util.GeneralException)7 List (java.util.List)6 Map (java.util.Map)6 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)6 Calendar (com.ibm.icu.util.Calendar)4 LinkedHashSet (java.util.LinkedHashSet)4 EntityConditionList (org.apache.ofbiz.entity.condition.EntityConditionList)4