Example usage for java.sql Timestamp after

List of usage examples for java.sql Timestamp after

Introduction

In this page you can find the example usage for java.sql Timestamp after.

Prototype

public boolean after(Timestamp ts) 

Source Link

Document

Indicates whether this Timestamp object is later than the given Timestamp object.

Usage

From source file:org.kuali.kfs.module.tem.document.service.impl.TravelAuthorizationServiceImpl.java

private boolean matchReimbursements(List<TravelReimbursementDocument> travelReimbursementDocuments,
        Date tripBeginBufferDate, Date tripEndBufferDate) {
    Timestamp earliestTripBeginDate = null;
    Timestamp greatestTripEndDate = null;

    for (TravelReimbursementDocument document : travelReimbursementDocuments) {
        Timestamp tripBegin = document.getTripBegin();
        Timestamp tripEnd = document.getTripEnd();
        if (ObjectUtils.isNull(earliestTripBeginDate) && ObjectUtils.isNull(greatestTripEndDate)) {
            earliestTripBeginDate = tripBegin;
            greatestTripEndDate = tripEnd;
        } else {//from  w  w w  . j a  v a2  s .c  o  m
            earliestTripBeginDate = tripBegin.before(earliestTripBeginDate) ? tripBegin : earliestTripBeginDate;
            greatestTripEndDate = tripEnd.after(greatestTripEndDate) ? tripEnd : greatestTripEndDate;

        }
    }

    if (doesDatesOverlap(tripBeginBufferDate, tripEndBufferDate, convertToSqlDate(earliestTripBeginDate),
            convertToSqlDate(greatestTripEndDate))) {
        return true;
    }

    return false;
}

From source file:org.eevolution.form.VCRP.java

protected Timestamp[] getDayBorders(Timestamp dateTime, MMPCOrderNode node, MResourceType t) {

    Timestamp endDayTime = null;/* ww  w  .j  a v  a  2 s. c  o  m*/
    // The theoretical latest time on a day, where the work ends, dependent on
    // the resource type's time slot value
    if (t.isTimeSlot()) {

        endDayTime = DateTimeUtil.getDayBorder(dateTime, t.getTimeSlotEnd(), true);
    } else {

        endDayTime = DateTimeUtil.getDayBorder(dateTime, null, true);
    }

    // Initialize the end time to the present, if the work ends at this day. Otherwise
    // the earliest possible start time for a day is set.
    endDayTime = (endDayTime.before(node.getDateFinishSchedule())) ? endDayTime : node.getDateFinishSchedule();

    Timestamp startDayTime = null;
    // The theoretical earliest time on a day, where the work begins, dependent on
    // the resource type's time slot value
    if (t.isTimeSlot()) {

        startDayTime = DateTimeUtil.getDayBorder(dateTime, t.getTimeSlotStart(), false);
    } else {

        startDayTime = DateTimeUtil.getDayBorder(dateTime, null, false);
    }

    // Initialize the end time to the present, if the work begins at this day. Otherwise
    // the earliest possible start time for a day is set.
    startDayTime = (startDayTime.after(node.getDateStartSchedule())) ? startDayTime
            : node.getDateStartSchedule();

    return new Timestamp[] { startDayTime, endDayTime };
}

From source file:com.pari.ic.ICManager.java

/**
 * Validates if a given IC has sufficient licese for execution. In case of insufficient license, throws exception
 * with appropriate license expiry message.
 *
 * @param customer_id/*from  w w w  . j  a v a2s  . c  o m*/
 *            Customer ID
 * @param icIdentifier
 *            IC Identifier
 *
 * @param deviceCount
 *            the device count
 * @throws Exception
 *             Exception in case of insufficient license for IC execution
 */
public void validateLicense(int customer_id, String icIdentifier, int deviceCount) throws Exception {
    ICPackage icPackage = ICDDBHelper.getICPackageForIc(customer_id, icIdentifier);
    if (icPackage != null) {
        String licenseType = icPackage.getLicenseType();
        logger.info("Validating license " + licenseType + " for IC " + icIdentifier);
        if (ICPackageLicense.LicenseNeverExpires == ICPackageLicense.getEnum(licenseType)) {
            return;
        } else if (ICPackageLicense.PackageUsageCount == ICPackageLicense.getEnum(licenseType)) {
            int icUsageCount = ICDDBHelper.getIcUsageCount(customer_id, icIdentifier);
            int maxCount = icPackage.getLicenseExpiryCount();
            if ((icUsageCount + deviceCount) > maxCount) {
                logger.debug("IC Package " + icPackage.getPackageName() + " has max count " + maxCount
                        + " but current usage count of IC " + icIdentifier + " is " + icUsageCount);
                throw new Exception("Insufficient License counts - maximum limit is " + maxCount
                        + " , current usage count is " + icUsageCount + ", Required licenses - " + deviceCount);
            }
        } else if (ICPackageLicense.PackageExpiryDate == ICPackageLicense.getEnum(licenseType)) {
            Timestamp expiryDate = icPackage.getLicenseExpiryDate();
            try {
                Date now = new Date();
                if (!expiryDate.after(now)) {
                    String expiryDateStr = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm")
                            .format(expiryDate);
                    logger.debug("IC Package " + icPackage.getPackageName() + " has expiry date of "
                            + expiryDateStr + " which is is beyond current time. IC =  " + icIdentifier);
                    throw new Exception("License expired - IC Package expired on " + expiryDateStr);
                }
            } catch (Exception e) {
                throw new Exception("IC Package license not available - " + e.getLocalizedMessage());
            }
        } else {
            logger.error(
                    "Unknown license type " + licenseType + " for IC Package " + icPackage.getPackageName());
        }
    }
}

From source file:org.kuali.kra.irb.actions.ActionHelper.java

/**
 * Prepares all protocol actions for being filtered by setting their isInFilterView attribute.
 *//*w ww.j av a 2s  .c om*/
public void initFilterDatesView() {
    java.util.Date dayBeforeStartDate = null;
    java.util.Date dayAfterEndDate = null;

    if (filteredHistoryStartDate != null && filteredHistoryEndDate != null) {
        dayBeforeStartDate = DateUtils.addDays(filteredHistoryStartDate, -1);
        dayAfterEndDate = DateUtils.addDays(filteredHistoryEndDate, 1);
    }

    for (ProtocolActionBase protocolAction : getSortedProtocolActions()) {
        Timestamp actionDate = protocolAction.getActionDate();
        if (dayBeforeStartDate != null && dayAfterEndDate != null) {
            protocolAction.setIsInFilterView(
                    actionDate.after(dayBeforeStartDate) && actionDate.before(dayAfterEndDate));
        } else {
            protocolAction.setIsInFilterView(true);
        }
        if (protocolAction.getIsInFilterView()) {
            ((ProtocolAction) protocolAction).setQuestionnairePrintOptionFromHelper(this);
        }
    }
}

From source file:org.kuali.kra.protocol.actions.ActionHelperBase.java

/**
 * Prepares all protocol actions for being filtered by setting their isInFilterView attribute.
 *//* w  w w  . ja v  a2 s .  c  om*/
public void initFilterDatesView() {
    java.util.Date dayBeforeStartDate = null;
    java.util.Date dayAfterEndDate = null;

    if (filteredHistoryStartDate != null && filteredHistoryEndDate != null) {
        dayBeforeStartDate = DateUtils.addDays(filteredHistoryStartDate, -1);
        dayAfterEndDate = DateUtils.addDays(filteredHistoryEndDate, 1);
    }

    for (ProtocolActionBase protocolAction : getSortedProtocolActions()) {
        Timestamp actionDate = protocolAction.getActionDate();
        if (dayBeforeStartDate != null && dayAfterEndDate != null) {
            protocolAction.setIsInFilterView(
                    actionDate.after(dayBeforeStartDate) && actionDate.before(dayAfterEndDate));
        } else {
            protocolAction.setIsInFilterView(true);
        }
        if (protocolAction.getIsInFilterView()) {

        }
    }
}

From source file:org.etudes.component.app.melete.ModuleDB.java

private int getStudentNavSeqNo(String userId, String courseId, int currSeqNo, boolean prevFlag) {
    Connection dbConnection = null;
    List resList = new ArrayList();
    java.sql.Timestamp currentTimestamp = null;
    int navSeqNo = -1;
    String sql;//from w w  w .  j  a va2  s.  c  om

    try {
        dbConnection = SqlService.borrowConnection();
        ResultSet rs, accRs = null;
        //First get all sequence numbers after this one from course module table
        if (prevFlag) {
            sql = "select cm.seq_no from melete_course_module cm,melete_module_shdates msh where cm.course_id = ? and cm.delete_flag = 0 and cm.archv_flag = 0 and cm.seq_no < ? and cm.module_id = msh.module_id and ((msh.start_date is null or msh.start_date < ?) and (msh.end_date is null or msh.end_date > ?)) order by cm.seq_no desc";
        } else {
            sql = "select cm.seq_no from melete_course_module cm,melete_module_shdates msh where cm.course_id = ? and cm.delete_flag = 0 and cm.archv_flag = 0 and cm.seq_no > ? and cm.module_id = msh.module_id and ((msh.start_date is null or msh.start_date < ?) and (msh.end_date is null or msh.end_date > ?)) order by cm.seq_no";
        }
        PreparedStatement pstmt = dbConnection.prepareStatement(sql);
        pstmt.setString(1, courseId);
        pstmt.setInt(2, currSeqNo);
        currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTimeInMillis());
        pstmt.setTimestamp(3, currentTimestamp);
        pstmt.setTimestamp(4, currentTimestamp);
        rs = pstmt.executeQuery();
        if (rs != null) {
            //Add them to resList
            while (rs.next()) {
                resList.add(rs.getInt("seq_no"));
            }
        }
        //Get all access entries for user   
        if (prevFlag) {
            sql = "select cm.seq_no, sa.start_date, sa.end_date from melete_course_module cm,melete_special_access sa where cm.course_id = ? and cm.delete_flag = 0 and cm.archv_flag = 0 and cm.seq_no < ? and cm.module_id = sa.module_id and sa.users like ? order by cm.seq_no desc";
        } else {
            sql = "select cm.seq_no, sa.start_date, sa.end_date from melete_course_module cm,melete_special_access sa where cm.course_id = ? and cm.delete_flag = 0 and cm.archv_flag = 0 and cm.seq_no > ? and cm.module_id = sa.module_id and sa.users like ? order by cm.seq_no";
        }
        PreparedStatement accPstmt = dbConnection.prepareStatement(sql);
        accPstmt.setString(1, courseId);
        accPstmt.setInt(2, currSeqNo);
        accPstmt.setString(3, "%" + userId + "%");
        accRs = accPstmt.executeQuery();
        Map accMap = new HashMap();
        if (accRs != null) {
            //Add them to accMap  
            while (accRs.next()) {
                AccessDates ad = new AccessDates(accRs.getTimestamp("start_date"),
                        accRs.getTimestamp("end_date"));
                accMap.put(accRs.getInt("seq_no"), ad);
            }
        }
        accRs.close();
        accPstmt.close();
        //If there are no access entries, return the first entry in resList
        if ((accMap == null) || (accMap.size() == 0)) {
            if (resList.size() == 0)
                navSeqNo = -1;
            else
                navSeqNo = ((Integer) resList.get(0)).intValue();
        } else {
            List removeList = new ArrayList();
            Iterator it = accMap.entrySet().iterator();
            //Check to see if there are any blocked entries in accMap. If so, add them to removeList
            while (it.hasNext()) {
                Map.Entry pairs = (Map.Entry) it.next();
                Integer seq = (Integer) pairs.getKey();
                AccessDates ad = (AccessDates) pairs.getValue();
                currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTimeInMillis());
                java.sql.Timestamp startTimestamp = ad.getAccStartTimestamp();
                java.sql.Timestamp endTimestamp = ad.getAccEndTimestamp();
                if (((startTimestamp == null) || (startTimestamp.before(currentTimestamp)))
                        && ((endTimestamp == null) || (endTimestamp.after(currentTimestamp)))) {
                    continue;
                } else {
                    removeList.add(seq);
                }
            }
            //If there are blocked entries, remove them from both resList and accMap
            if (removeList.size() > 0) {
                for (Iterator itr = removeList.listIterator(); itr.hasNext();) {
                    Integer seq = (Integer) itr.next();
                    if (resList.size() > 0) {
                        if (resList.indexOf(seq) != -1)
                            resList.remove(seq);
                    }
                    accMap.remove(seq);
                }
            }
            //Return sequence number appropriately
            if ((resList.size() == 0) && (accMap.size() == 0)) {
                navSeqNo = -1;
            }
            if ((resList.size() == 0) && (accMap.size() > 0))
                navSeqNo = ((Integer) ((Map.Entry) accMap.entrySet().iterator().next()).getKey()).intValue();
            if ((resList.size() > 0) && (accMap.size() == 0))
                navSeqNo = ((Integer) resList.get(0)).intValue();
            if ((resList.size() > 0) && (accMap.size() > 0))
                navSeqNo = Math.max(
                        ((Integer) ((Map.Entry) accMap.entrySet().iterator().next()).getKey()).intValue(),
                        ((Integer) resList.get(0)).intValue());
        }
        rs.close();
        pstmt.close();
    } catch (Exception e) {
        if (logger.isErrorEnabled())
            logger.error(e.toString());
    } finally {
        try {
            if (dbConnection != null)
                SqlService.returnConnection(dbConnection);
        } catch (Exception e1) {
            if (logger.isErrorEnabled())
                logger.error(e1.toString());
        }
    }
    return navSeqNo;
}

From source file:org.kuali.kfs.module.tem.document.service.impl.TravelDocumentServiceImpl.java

@Override
public List<String> findMatchingTrips(TravelDocument travelDocument) {

    String travelDocumentIdentifier = travelDocument.getTravelDocumentIdentifier();
    Integer temProfileId = travelDocument.getTemProfileId();
    Timestamp earliestTripBeginDate = null;
    Timestamp greatestTripEndDate = null;

    List<TravelReimbursementDocument> documents = findReimbursementDocuments(travelDocumentIdentifier);
    for (TravelReimbursementDocument document : documents) {
        Timestamp tripBegin = document.getTripBegin();
        Timestamp tripEnd = document.getTripEnd();
        if (ObjectUtils.isNull(earliestTripBeginDate) && ObjectUtils.isNull(greatestTripEndDate)) {
            earliestTripBeginDate = tripBegin;
            greatestTripEndDate = tripEnd;
        } else {/*from   w  ww.  ja  v a  2  s. co  m*/
            earliestTripBeginDate = tripBegin.before(earliestTripBeginDate) ? tripBegin : earliestTripBeginDate;
            greatestTripEndDate = tripEnd.after(greatestTripEndDate) ? tripEnd : greatestTripEndDate;

        }
    }

    // TR with no TAs created from mainmenu
    if (documents.isEmpty() && ObjectUtils.isNotNull(travelDocument.getTripBegin())
            && ObjectUtils.isNotNull(travelDocument.getTripEnd())) {
        earliestTripBeginDate = getTripBeginDate(travelDocument.getTripBegin());
        greatestTripEndDate = getTripEndDate(travelDocument.getTripEnd());
    }

    List<TravelReimbursementDocument> matchDocs = (List<TravelReimbursementDocument>) travelDocumentDao
            .findMatchingTrips(temProfileId, earliestTripBeginDate, greatestTripEndDate);
    List<String> documentIds = new ArrayList<String>();
    for (TravelReimbursementDocument document : matchDocs) {
        if (!travelDocument.getDocumentNumber().equals(document.getDocumentNumber())) {
            documentIds.add(document.getDocumentNumber());
        }
    }
    return documentIds;
}

From source file:org.ofbiz.order.order.OrderServices.java

/** Service for editing a old order. Here we are assuming only orderItems and orderAdjustment only change for old orderId */
public static Map<String, Object> editOrder(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Security security = ctx.getSecurity();
    List<GenericValue> toBeStored = new LinkedList<GenericValue>();
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> successResult = ServiceUtil.returnSuccess();

    GenericValue userLogin = (GenericValue) context.get("userLogin");
    // get the order type
    String orderTypeId = (String) context.get("orderTypeId");
    String partyId = (String) context.get("partyId");
    String billFromVendorPartyId = (String) context.get("billFromVendorPartyId");
    // check security permissions for order:
    //  SALES ORDERS - if userLogin has ORDERMGR_SALES_CREATE or ORDERMGR_CREATE permission, or if it is same party as the partyId, or
    //                 if it is an AGENT (sales rep) creating an order for his customer
    //  PURCHASE ORDERS - if there is a PURCHASE_ORDER permission
    Map<String, Object> resultSecurity = new HashMap<String, Object>();
    boolean hasPermission = OrderServices.hasPermission(orderTypeId, partyId, userLogin, "CREATE", security);
    // final check - will pass if userLogin's partyId = partyId for order or if userLogin has ORDERMGR_CREATE permission
    // jacopoc: what is the meaning of this code block? FIXME
    if (!hasPermission) {
        partyId = ServiceUtil.getPartyIdCheckSecurity(userLogin, security, context, resultSecurity, "ORDERMGR",
                "_CREATE");
        if (resultSecurity.size() > 0) {
            return resultSecurity;
        }/*from   www  . ja v  a 2s .  c o m*/
    }

    // get the product store for the order, but it is required only for sales orders
    String productStoreId = (String) context.get("productStoreId");
    GenericValue productStore = null;
    if ((orderTypeId.equals("SALES_ORDER")) && (UtilValidate.isNotEmpty(productStoreId))) {
        try {
            productStore = delegator.findByPrimaryKeyCache("ProductStore",
                    UtilMisc.toMap("productStoreId", productStoreId));
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource_error, "OrderErrorCouldNotFindProductStoreWithID",
                            UtilMisc.toMap("productStoreId", productStoreId), locale) + e.toString());
        }
    }

    // figure out if the order is immediately fulfilled based on product store settings
    boolean isImmediatelyFulfilled = false;
    if (productStore != null) {
        isImmediatelyFulfilled = "Y".equals(productStore.getString("isImmediatelyFulfilled"));
    }

    successResult.put("orderTypeId", orderTypeId);

    // lookup the order type entity
    GenericValue orderType = null;
    try {
        orderType = delegator.findByPrimaryKeyCache("OrderType", UtilMisc.toMap("orderTypeId", orderTypeId));
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource_error, "OrderErrorOrderTypeLookupFailed", locale)
                        + e.toString());
    }

    // make sure we have a valid order type
    if (orderType == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderErrorInvalidOrderTypeWithID", UtilMisc.toMap("orderTypeId", orderTypeId), locale));
    }

    // check to make sure we have something to order
    List<GenericValue> orderItems = UtilGenerics.checkList(context.get("orderItems"));
    if (orderItems.size() < 1) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "items.none", locale));
    }

    // all this marketing pkg auto stuff is deprecated in favor of MARKETING_PKG_AUTO productTypeId and a BOM of MANUF_COMPONENT assocs
    // these need to be retrieved now because they might be needed for exploding MARKETING_PKG_AUTO
    List<GenericValue> orderAdjustments = UtilGenerics.checkList(context.get("orderAdjustments"));
    List<GenericValue> orderItemShipGroupInfo = UtilGenerics.checkList(context.get("orderItemShipGroupInfo"));
    List<GenericValue> orderItemPriceInfo = UtilGenerics.checkList(context.get("orderItemPriceInfos"));

    // check inventory and other things for each item
    List<String> errorMessages = FastList.newInstance();
    Map<String, BigDecimal> normalizedItemQuantities = FastMap.newInstance();
    Map<String, String> normalizedItemNames = FastMap.newInstance();
    Map<String, GenericValue> itemValuesBySeqId = FastMap.newInstance();
    Iterator<GenericValue> itemIter = orderItems.iterator();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();

    //
    // need to run through the items combining any cases where multiple lines refer to the
    // same product so the inventory check will work correctly
    // also count quantities ordered while going through the loop
    while (itemIter.hasNext()) {
        GenericValue orderItem = itemIter.next();

        // start by putting it in the itemValuesById Map
        itemValuesBySeqId.put(orderItem.getString("orderItemSeqId"), orderItem);

        String currentProductId = orderItem.getString("productId");
        if (currentProductId != null) {
            // only normalize items with a product associated (ignore non-product items)
            if (normalizedItemQuantities.get(currentProductId) == null) {
                normalizedItemQuantities.put(currentProductId, orderItem.getBigDecimal("quantity"));
                normalizedItemNames.put(currentProductId, orderItem.getString("itemDescription"));
            } else {
                BigDecimal currentQuantity = normalizedItemQuantities.get(currentProductId);
                normalizedItemQuantities.put(currentProductId,
                        currentQuantity.add(orderItem.getBigDecimal("quantity")));
            }

            /* try {
                 // count product ordered quantities
                 // run this synchronously so it will run in the same transaction
                 dispatcher.runSync("countProductQuantityOrdered", UtilMisc.<String, Object>toMap("productId", currentProductId, "quantity", orderItem.getBigDecimal("quantity"), "userLogin", userLogin));
             } catch (GenericServiceException e1) {
                 Debug.logError(e1, "Error calling countProductQuantityOrdered service", module);
                 return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                   "OrderErrorCallingCountProductQuantityOrderedService",locale) + e1.toString());
             }*/
        }
    }

    if (!"PURCHASE_ORDER".equals(orderTypeId) && productStoreId == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderErrorTheProductStoreIdCanOnlyBeNullForPurchaseOrders", locale));
    }

    Timestamp orderDate = (Timestamp) context.get("orderDate");

    Iterator<String> normalizedIter = normalizedItemQuantities.keySet().iterator();
    while (normalizedIter.hasNext()) {
        // lookup the product entity for each normalized item; error on products not found
        String currentProductId = normalizedIter.next();
        BigDecimal currentQuantity = normalizedItemQuantities.get(currentProductId);
        String itemName = normalizedItemNames.get(currentProductId);
        GenericValue product = null;

        try {
            product = delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", currentProductId));
        } catch (GenericEntityException e) {
            String errMsg = UtilProperties.getMessage(resource_error, "product.not_found",
                    new Object[] { currentProductId }, locale);
            Debug.logError(e, errMsg, module);
            errorMessages.add(errMsg);
            continue;
        }

        if (product == null) {
            String errMsg = UtilProperties.getMessage(resource_error, "product.not_found",
                    new Object[] { currentProductId }, locale);
            Debug.logError(errMsg, module);
            errorMessages.add(errMsg);
            continue;
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            // check to see if introductionDate hasn't passed yet
            if (product.get("introductionDate") != null
                    && nowTimestamp.before(product.getTimestamp("introductionDate"))) {
                String excMsg = UtilProperties.getMessage(resource_error, "product.not_yet_for_sale",
                        new Object[] { getProductName(product, itemName), product.getString("productId") },
                        locale);
                Debug.logWarning(excMsg, module);
                errorMessages.add(excMsg);
                continue;
            }
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            boolean salesDiscontinuationFlag = false;
            // When past orders are imported, they should be imported even if sales discontinuation date is in the past but if the order date was before it
            if (orderDate != null && product.get("salesDiscontinuationDate") != null) {
                salesDiscontinuationFlag = orderDate.after(product.getTimestamp("salesDiscontinuationDate"))
                        && nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"));
            } else if (product.get("salesDiscontinuationDate") != null) {
                salesDiscontinuationFlag = nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"));
            }
            // check to see if salesDiscontinuationDate has passed
            if (salesDiscontinuationFlag) {
                String excMsg = UtilProperties.getMessage(resource_error, "product.no_longer_for_sale",
                        new Object[] { getProductName(product, itemName), product.getString("productId") },
                        locale);
                Debug.logWarning(excMsg, module);
                errorMessages.add(excMsg);
                continue;
            }
        }

    }

    // the inital status for ALL order types
    String initialStatus = "ORDER_CREATED";
    successResult.put("statusId", initialStatus);

    // create the order object
    String orderId = (String) context.get("orderId");
    String orgPartyId = null;
    if (productStore != null) {
        orgPartyId = productStore.getString("payToPartyId");
    } else if (billFromVendorPartyId != null) {
        orgPartyId = billFromVendorPartyId;
    }

    if (UtilValidate.isNotEmpty(orgPartyId)) {
        Map<String, Object> getNextOrderIdContext = FastMap.newInstance();
        getNextOrderIdContext.putAll(context);
        getNextOrderIdContext.put("partyId", orgPartyId);
        getNextOrderIdContext.put("userLogin", userLogin);

        if ((orderTypeId.equals("SALES_ORDER")) || (productStoreId != null)) {
            getNextOrderIdContext.put("productStoreId", productStoreId);
        }
        if (UtilValidate.isEmpty(orderId)) {
            try {
                getNextOrderIdContext = ctx.makeValidContext("getNextOrderId", "IN", getNextOrderIdContext);
                Map<String, Object> getNextOrderIdResult = dispatcher.runSync("getNextOrderId",
                        getNextOrderIdContext);
                if (ServiceUtil.isError(getNextOrderIdResult)) {
                    String errMsg = UtilProperties.getMessage(resource_error,
                            "OrderErrorGettingNextOrderIdWhileCreatingOrder", locale);
                    return ServiceUtil.returnError(errMsg, null, null, getNextOrderIdResult);
                }
                orderId = (String) getNextOrderIdResult.get("orderId");
            } catch (GenericServiceException e) {
                String errMsg = UtilProperties.getMessage(resource_error,
                        "OrderCaughtGenericServiceExceptionWhileGettingOrderId", locale);
                Debug.logError(e, errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
        }
    }

    if (UtilValidate.isEmpty(orderId)) {
        // for purchase orders or when other orderId generation fails, a product store id should not be required to make an order
        orderId = delegator.getNextSeqId("OrderHeader");
    }

    String billingAccountId = (String) context.get("billingAccountId");
    if (orderDate == null) {
        orderDate = nowTimestamp;
    }

    Map<String, Object> orderHeaderMap = UtilMisc.<String, Object>toMap("orderId", orderId, "orderTypeId",
            orderTypeId, "orderDate", orderDate, "entryDate", nowTimestamp, "statusId", initialStatus,
            "billingAccountId", billingAccountId);
    orderHeaderMap.put("orderName", context.get("orderName"));
    orderHeaderMap.put("estimatedDeliveryDate", context.get("estimatedDeliveryDate"));
    orderHeaderMap.put("isEnableAcctg", context.get("isEnableAcctg"));
    if (isImmediatelyFulfilled) {
        // also flag this order as needing inventory issuance so that when it is set to complete it will be issued immediately (needsInventoryIssuance = Y)
        orderHeaderMap.put("needsInventoryIssuance", "Y");
    }
    GenericValue orderHeader = delegator.makeValue("OrderHeader", orderHeaderMap);
    //if Already there get that order only

    if (UtilValidate.isNotEmpty(orderId)) {
        try {
            orderHeader = delegator.findOne("OrderHeader", UtilMisc.toMap("orderId", orderId), false);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Problem while finding order", module);
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource_error, "OrderErrorCouldNotCreateOrderWriteError", locale)
                            + e.getMessage() + ").");
        }

    }

    if (context.get("grandTotal") != null) {
        orderHeader.set("grandTotal", context.get("grandTotal"));
    }

    if (UtilValidate.isNotEmpty(context.get("visitId"))) {
        orderHeader.set("visitId", context.get("visitId"));
    }

    if (userLogin != null && userLogin.get("userLoginId") != null) {
        orderHeader.set("createdBy", userLogin.getString("userLoginId"));
    }
    if (UtilValidate.isNotEmpty(context.get("orderName"))) {
        orderHeader.set("orderName", context.get("orderName"));
    }
    // first try to create the OrderHeader; if this does not fail, continue.
    try {
        delegator.createOrStore(orderHeader);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot create OrderHeader entity; problems with insert", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderOrderCreationFailedPleaseNotifyCustomerService", locale));
    }

    // before processing orderItems process orderItemGroups so that they'll be in place for the foreign keys and what not
    List<GenericValue> orderItemGroups = UtilGenerics.checkList(context.get("orderItemGroups"));
    if (UtilValidate.isNotEmpty(orderItemGroups)) {
        Iterator<GenericValue> orderItemGroupIter = orderItemGroups.iterator();
        while (orderItemGroupIter.hasNext()) {
            GenericValue orderItemGroup = orderItemGroupIter.next();
            orderItemGroup.set("orderId", orderId);
            toBeStored.add(orderItemGroup);
        }
    }

    // set the order items
    Iterator<GenericValue> oi = orderItems.iterator();
    while (oi.hasNext()) {
        GenericValue orderItem = oi.next();
        orderItem.set("orderId", orderId);
        toBeStored.add(orderItem);

        // create the item status record
        /* String itemStatusId = delegator.getNextSeqId("OrderStatus");
         GenericValue itemStatus = delegator.makeValue("OrderStatus", UtilMisc.toMap("orderStatusId", itemStatusId));
         itemStatus.put("statusId", orderItem.get("statusId"));
         itemStatus.put("orderId", orderId);
         itemStatus.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
         itemStatus.put("statusDatetime", nowTimestamp);
         itemStatus.set("statusUserLogin", userLogin.getString("userLoginId"));
         toBeStored.add(itemStatus);*/
    }

    /* // set the order attributes
     List<GenericValue> orderAttributes = UtilGenerics.checkList(context.get("orderAttributes"));
     if (UtilValidate.isNotEmpty(orderAttributes)) {
         Iterator<GenericValue> oattr = orderAttributes.iterator();
         while (oattr.hasNext()) {
       GenericValue oatt = oattr.next();
       oatt.set("orderId", orderId);
       toBeStored.add(oatt);
         }
     }*/

    // set the order item attributes
    /* List<GenericValue> orderItemAttributes = UtilGenerics.checkList(context.get("orderItemAttributes"));
     if (UtilValidate.isNotEmpty(orderItemAttributes)) {
         Iterator<GenericValue> oiattr = orderItemAttributes.iterator();
         while (oiattr.hasNext()) {
       GenericValue oiatt = oiattr.next();
       oiatt.set("orderId", orderId);
       toBeStored.add(oiatt);
         }
     }*/

    //Here it is edit order always remove old adjustments
    try {
        List<GenericValue> oldOrderAdjustments = delegator.findList("OrderAdjustment",
                EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId), null, null, null,
                false);
        //Debug.log("==oldOrderAdjustments===Before=Deletion========="+oldOrderAdjustments);
        delegator.removeAll(oldOrderAdjustments);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem with order storage or reservations", module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource_error, "OrderErrorCouldNotCreateOrderWriteError", locale)
                        + e.getMessage() + ").");
    }

    // set the orderId on all adjustments; this list will include order and
    // item adjustments...
    if (UtilValidate.isNotEmpty(orderAdjustments)) {
        Iterator<GenericValue> iter = orderAdjustments.iterator();

        while (iter.hasNext()) {
            GenericValue orderAdjustment = iter.next();
            try {
                orderAdjustment.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
            } catch (IllegalArgumentException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                        "OrderErrorCouldNotGetNextSequenceIdForOrderAdjustmentCannotCreateOrder", locale));
            }

            orderAdjustment.set("orderId", orderId);
            orderAdjustment.set("createdDate", UtilDateTime.nowTimestamp());
            orderAdjustment.set("createdByUserLogin", userLogin.getString("userLoginId"));

            if (UtilValidate.isEmpty(orderAdjustment.get("orderItemSeqId"))) {
                orderAdjustment.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
            }
            if (UtilValidate.isEmpty(orderAdjustment.get("shipGroupSeqId"))) {
                orderAdjustment.set("shipGroupSeqId", DataModelConstants.SEQ_ID_NA);
            }
            toBeStored.add(orderAdjustment);
        }
    }

    // set the order item ship groups
    // commented when PurchaseOrder not created without shipment
    List<String> dropShipGroupIds = FastList.newInstance(); // this list will contain the ids of all the ship groups for drop shipments (no reservations)
    if (UtilValidate.isNotEmpty(orderItemShipGroupInfo)) {
        Iterator<GenericValue> osiInfos = orderItemShipGroupInfo.iterator();
        while (osiInfos.hasNext()) {
            GenericValue valueObj = osiInfos.next();
            valueObj.set("orderId", orderId);
            /* if ("OrderItemShipGroup".equals(valueObj.getEntityName())) {
                 // ship group
                 if (valueObj.get("carrierRoleTypeId") == null) {
               valueObj.set("carrierRoleTypeId", "CARRIER");
                 }
                 if (!UtilValidate.isEmpty(valueObj.getString("supplierPartyId"))) {
               dropShipGroupIds.add(valueObj.getString("shipGroupSeqId"));
                 }
            toBeStored.add(valueObj); // from out side of if we bring here
             } else */
            if ("OrderAdjustment".equals(valueObj.getEntityName())) {
                // shipping / tax adjustment(s)
                if (UtilValidate.isEmpty(valueObj.get("orderItemSeqId"))) {
                    valueObj.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
                }
                valueObj.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
                valueObj.set("createdDate", UtilDateTime.nowTimestamp());
                valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
                toBeStored.add(valueObj);
            }

        }
    }

    // set the item price info; NOTE: this must be after the orderItems are stored for referential integrity
    if (UtilValidate.isNotEmpty(orderItemPriceInfo)) {
        Iterator<GenericValue> oipii = orderItemPriceInfo.iterator();

        while (oipii.hasNext()) {
            GenericValue oipi = oipii.next();
            try {
                oipi.set("orderItemPriceInfoId", delegator.getNextSeqId("OrderItemPriceInfo"));
            } catch (IllegalArgumentException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                        "OrderErrorCouldNotGetNextSequenceIdForOrderItemPriceInfoCannotCreateOrder", locale));
            }

            oipi.set("orderId", orderId);
            toBeStored.add(oipi);
        }
    }

    // store the orderProductPromoUseInfos
    List<GenericValue> orderProductPromoUses = UtilGenerics.checkList(context.get("orderProductPromoUses"));
    if (UtilValidate.isNotEmpty(orderProductPromoUses)) {
        Iterator<GenericValue> orderProductPromoUseIter = orderProductPromoUses.iterator();
        while (orderProductPromoUseIter.hasNext()) {
            GenericValue productPromoUse = orderProductPromoUseIter.next();
            productPromoUse.set("orderId", orderId);
            toBeStored.add(productPromoUse);
        }
    }

    // store the orderProductPromoCodes
    Set<String> orderProductPromoCodes = UtilGenerics.checkSet(context.get("orderProductPromoCodes"));
    if (UtilValidate.isNotEmpty(orderProductPromoCodes)) {
        GenericValue orderProductPromoCode = delegator.makeValue("OrderProductPromoCode");
        Iterator<String> orderProductPromoCodeIter = orderProductPromoCodes.iterator();
        while (orderProductPromoCodeIter.hasNext()) {
            orderProductPromoCode.clear();
            orderProductPromoCode.set("orderId", orderId);
            orderProductPromoCode.set("productPromoCodeId", orderProductPromoCodeIter.next());
            toBeStored.add(orderProductPromoCode);
        }
    }

    try {
        // store line items, etc so that they will be there for the foreign key checks
        delegator.storeAll(toBeStored);

        successResult.put("orderId", orderId);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem with order storage or reservations", module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource_error, "OrderErrorCouldNotCreateOrderWriteError", locale)
                        + e.getMessage() + ").");
    }

    return successResult;
}

From source file:org.ofbiz.order.order.OrderServices.java

/** Service for creating a new order */
public static Map<String, Object> createOrder(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Security security = ctx.getSecurity();
    List<GenericValue> toBeStored = new LinkedList<GenericValue>();
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> successResult = ServiceUtil.returnSuccess();

    GenericValue userLogin = (GenericValue) context.get("userLogin");
    // get the order type
    String orderTypeId = (String) context.get("orderTypeId");
    String partyId = (String) context.get("partyId");
    String billFromVendorPartyId = (String) context.get("billFromVendorPartyId");

    // check security permissions for order:
    //  SALES ORDERS - if userLogin has ORDERMGR_SALES_CREATE or ORDERMGR_CREATE permission, or if it is same party as the partyId, or
    //                 if it is an AGENT (sales rep) creating an order for his customer
    //  PURCHASE ORDERS - if there is a PURCHASE_ORDER permission
    Map<String, Object> resultSecurity = new HashMap<String, Object>();
    boolean hasPermission = OrderServices.hasPermission(orderTypeId, partyId, userLogin, "CREATE", security);
    // final check - will pass if userLogin's partyId = partyId for order or if userLogin has ORDERMGR_CREATE permission
    // jacopoc: what is the meaning of this code block? FIXME
    if (!hasPermission) {
        partyId = ServiceUtil.getPartyIdCheckSecurity(userLogin, security, context, resultSecurity, "ORDERMGR",
                "_CREATE");
        if (resultSecurity.size() > 0) {
            return resultSecurity;
        }//ww  w  .j a  v  a  2  s .com
    }

    // get the product store for the order, but it is required only for sales orders
    String productStoreId = (String) context.get("productStoreId");
    GenericValue productStore = null;
    if ((orderTypeId.equals("SALES_ORDER")) && (UtilValidate.isNotEmpty(productStoreId))) {
        try {
            productStore = delegator.findByPrimaryKeyCache("ProductStore",
                    UtilMisc.toMap("productStoreId", productStoreId));
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource_error, "OrderErrorCouldNotFindProductStoreWithID",
                            UtilMisc.toMap("productStoreId", productStoreId), locale) + e.toString());
        }
    }

    // figure out if the order is immediately fulfilled based on product store settings
    boolean isImmediatelyFulfilled = false;
    if (productStore != null) {
        isImmediatelyFulfilled = "Y".equals(productStore.getString("isImmediatelyFulfilled"));
    }

    successResult.put("orderTypeId", orderTypeId);

    // lookup the order type entity
    GenericValue orderType = null;
    try {
        orderType = delegator.findByPrimaryKeyCache("OrderType", UtilMisc.toMap("orderTypeId", orderTypeId));
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource_error, "OrderErrorOrderTypeLookupFailed", locale)
                        + e.toString());
    }

    // make sure we have a valid order type
    if (orderType == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderErrorInvalidOrderTypeWithID", UtilMisc.toMap("orderTypeId", orderTypeId), locale));
    }

    // check to make sure we have something to order
    List<GenericValue> orderItems = UtilGenerics.checkList(context.get("orderItems"));
    if (orderItems.size() < 1) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error, "items.none", locale));
    }

    // all this marketing pkg auto stuff is deprecated in favor of MARKETING_PKG_AUTO productTypeId and a BOM of MANUF_COMPONENT assocs
    // these need to be retrieved now because they might be needed for exploding MARKETING_PKG_AUTO
    List<GenericValue> orderAdjustments = UtilGenerics.checkList(context.get("orderAdjustments"));
    List<GenericValue> orderItemShipGroupInfo = UtilGenerics.checkList(context.get("orderItemShipGroupInfo"));
    List<GenericValue> orderItemPriceInfo = UtilGenerics.checkList(context.get("orderItemPriceInfos"));

    // check inventory and other things for each item
    List<String> errorMessages = FastList.newInstance();
    Map<String, BigDecimal> normalizedItemQuantities = FastMap.newInstance();
    Map<String, String> normalizedItemNames = FastMap.newInstance();
    Map<String, GenericValue> itemValuesBySeqId = FastMap.newInstance();
    Iterator<GenericValue> itemIter = orderItems.iterator();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();

    //
    // need to run through the items combining any cases where multiple lines refer to the
    // same product so the inventory check will work correctly
    // also count quantities ordered while going through the loop
    while (itemIter.hasNext()) {
        GenericValue orderItem = itemIter.next();

        // start by putting it in the itemValuesById Map
        itemValuesBySeqId.put(orderItem.getString("orderItemSeqId"), orderItem);

        String currentProductId = orderItem.getString("productId");
        if (currentProductId != null) {
            // only normalize items with a product associated (ignore non-product items)
            if (normalizedItemQuantities.get(currentProductId) == null) {
                normalizedItemQuantities.put(currentProductId, orderItem.getBigDecimal("quantity"));
                normalizedItemNames.put(currentProductId, orderItem.getString("itemDescription"));
            } else {
                BigDecimal currentQuantity = normalizedItemQuantities.get(currentProductId);
                normalizedItemQuantities.put(currentProductId,
                        currentQuantity.add(orderItem.getBigDecimal("quantity")));
            }

            /* try {
            // count product ordered quantities
            // run this synchronously so it will run in the same transaction
            dispatcher.runSync("countProductQuantityOrdered", UtilMisc.<String, Object>toMap("productId", currentProductId, "quantity", orderItem.getBigDecimal("quantity"), "userLogin", userLogin));
             } catch (GenericServiceException e1) {
            Debug.logError(e1, "Error calling countProductQuantityOrdered service", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                    "OrderErrorCallingCountProductQuantityOrderedService",locale) + e1.toString());
             }*/
        }
    }

    if (!"PURCHASE_ORDER".equals(orderTypeId) && productStoreId == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderErrorTheProductStoreIdCanOnlyBeNullForPurchaseOrders", locale));
    }

    Timestamp orderDate = (Timestamp) context.get("orderDate");

    Iterator<String> normalizedIter = normalizedItemQuantities.keySet().iterator();
    while (normalizedIter.hasNext()) {
        // lookup the product entity for each normalized item; error on products not found
        String currentProductId = normalizedIter.next();
        BigDecimal currentQuantity = normalizedItemQuantities.get(currentProductId);
        String itemName = normalizedItemNames.get(currentProductId);
        GenericValue product = null;

        try {
            product = delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", currentProductId));
        } catch (GenericEntityException e) {
            String errMsg = UtilProperties.getMessage(resource_error, "product.not_found",
                    new Object[] { currentProductId }, locale);
            Debug.logError(e, errMsg, module);
            errorMessages.add(errMsg);
            continue;
        }

        if (product == null) {
            String errMsg = UtilProperties.getMessage(resource_error, "product.not_found",
                    new Object[] { currentProductId }, locale);
            Debug.logError(errMsg, module);
            errorMessages.add(errMsg);
            continue;
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            // check to see if introductionDate hasn't passed yet
            if (product.get("introductionDate") != null
                    && nowTimestamp.before(product.getTimestamp("introductionDate"))) {
                String excMsg = UtilProperties.getMessage(resource_error, "product.not_yet_for_sale",
                        new Object[] { getProductName(product, itemName), product.getString("productId") },
                        locale);
                Debug.logWarning(excMsg, module);
                errorMessages.add(excMsg);
                continue;
            }
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            boolean salesDiscontinuationFlag = false;
            // When past orders are imported, they should be imported even if sales discontinuation date is in the past but if the order date was before it
            if (orderDate != null && product.get("salesDiscontinuationDate") != null) {
                salesDiscontinuationFlag = orderDate.after(product.getTimestamp("salesDiscontinuationDate"))
                        && nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"));
            } else if (product.get("salesDiscontinuationDate") != null) {
                salesDiscontinuationFlag = nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"));
            }
            // check to see if salesDiscontinuationDate has passed
            if (salesDiscontinuationFlag) {
                String excMsg = UtilProperties.getMessage(resource_error, "product.no_longer_for_sale",
                        new Object[] { getProductName(product, itemName), product.getString("productId") },
                        locale);
                Debug.logWarning(excMsg, module);
                errorMessages.add(excMsg);
                continue;
            }
        }

        if ("SALES_ORDER".equals(orderTypeId)) {
            // check to see if we have inventory available
            try {
                Map<String, Object> invReqResult = dispatcher.runSync("isStoreInventoryAvailableOrNotRequired",
                        UtilMisc.toMap("productStoreId", productStoreId, "productId", product.get("productId"),
                                "product", product, "quantity", currentQuantity));
                if (ServiceUtil.isError(invReqResult)) {
                    errorMessages.add((String) invReqResult.get(ModelService.ERROR_MESSAGE));
                    List<String> errMsgList = UtilGenerics
                            .checkList(invReqResult.get(ModelService.ERROR_MESSAGE_LIST));
                    errorMessages.addAll(errMsgList);
                } else if (!"Y".equals(invReqResult.get("availableOrNotRequired"))) {
                    String invErrMsg = UtilProperties.getMessage(resource_error, "product.out_of_stock",
                            new Object[] { getProductName(product, itemName), currentProductId }, locale);
                    Debug.logWarning(invErrMsg, module);
                    errorMessages.add(invErrMsg);
                    continue;
                }
            } catch (GenericServiceException e) {
                String errMsg = "Fatal error calling inventory checking services: " + e.toString();
                Debug.logError(e, errMsg, module);
                errorMessages.add(errMsg);
            }
        }
    }

    // add the fixedAsset id to the workefforts map by obtaining the fixed Asset number from the FixedAssetProduct table
    List<GenericValue> workEfforts = UtilGenerics.checkList(context.get("workEfforts")); // is an optional parameter from this service but mandatory for rental items
    Iterator<GenericValue> orderItemIter = orderItems.iterator();
    while (orderItemIter.hasNext()) {
        GenericValue orderItem = orderItemIter.next();
        if ("RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) {
            // check to see if workefforts are available for this order type.
            if (UtilValidate.isEmpty(workEfforts)) {
                String errMsg = "Work Efforts missing for ordertype RENTAL_ORDER_ITEM " + "Product: "
                        + orderItem.getString("productId");
                Debug.logError(errMsg, module);
                errorMessages.add(errMsg);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource_error, "OrderRentalOrderItems", locale));
            }
            Iterator<GenericValue> we = workEfforts.iterator(); // find the related workEffortItem (workEffortId = orderSeqId)
            while (we.hasNext()) {
                // create the entity maps required.
                GenericValue workEffort = we.next();
                if (workEffort.getString("workEffortId").equals(orderItem.getString("orderItemSeqId"))) {
                    List<GenericValue> selFixedAssetProduct = null;
                    try {
                        List<GenericValue> allFixedAssetProduct = delegator.findByAnd("FixedAssetProduct",
                                UtilMisc.toMap("productId", orderItem.getString("productId"),
                                        "fixedAssetProductTypeId", "FAPT_USE"));
                        selFixedAssetProduct = EntityUtil.filterByDate(allFixedAssetProduct, nowTimestamp,
                                "fromDate", "thruDate", true);
                    } catch (GenericEntityException e) {
                        String excMsg = "Could not find related Fixed Asset for the product: "
                                + orderItem.getString("productId");
                        Debug.logError(excMsg, module);
                        errorMessages.add(excMsg);
                        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                                "OrderCouldNotFindRelatedFixedAssetForTheProduct",
                                UtilMisc.toMap("productId", orderItem.getString("productId")), locale));
                    }

                    if (UtilValidate.isNotEmpty(selFixedAssetProduct)) {
                        Iterator<GenericValue> firstOne = selFixedAssetProduct.iterator();
                        if (firstOne.hasNext()) {
                            GenericValue fixedAssetProduct = delegator.makeValue("FixedAssetProduct");
                            fixedAssetProduct = firstOne.next();
                            workEffort.set("fixedAssetId", fixedAssetProduct.get("fixedAssetId"));
                            workEffort.set("quantityToProduce", orderItem.get("quantity")); // have quantity easy available later...
                            workEffort.set("createdByUserLogin", userLogin.get("userLoginId"));
                        }
                    }
                    break; // item found, so go to next orderitem.
                }
            }
        }
    }

    if (errorMessages.size() > 0) {
        return ServiceUtil.returnError(errorMessages);
    }

    // the inital status for ALL order types
    String initialStatus = "ORDER_CREATED";
    successResult.put("statusId", initialStatus);

    // create the order object
    String orderId = (String) context.get("orderId");
    String orgPartyId = null;
    if (productStore != null) {
        orgPartyId = productStore.getString("payToPartyId");
    } else if (billFromVendorPartyId != null) {
        orgPartyId = billFromVendorPartyId;
    }

    if (UtilValidate.isNotEmpty(orgPartyId)) {
        Map<String, Object> getNextOrderIdContext = FastMap.newInstance();
        getNextOrderIdContext.putAll(context);
        getNextOrderIdContext.put("partyId", orgPartyId);
        getNextOrderIdContext.put("userLogin", userLogin);

        if ((orderTypeId.equals("SALES_ORDER")) || (productStoreId != null)) {
            getNextOrderIdContext.put("productStoreId", productStoreId);
        }
        if (UtilValidate.isEmpty(orderId)) {
            try {
                getNextOrderIdContext = ctx.makeValidContext("getNextOrderId", "IN", getNextOrderIdContext);
                Map<String, Object> getNextOrderIdResult = dispatcher.runSync("getNextOrderId",
                        getNextOrderIdContext);
                if (ServiceUtil.isError(getNextOrderIdResult)) {
                    String errMsg = UtilProperties.getMessage(resource_error,
                            "OrderErrorGettingNextOrderIdWhileCreatingOrder", locale);
                    return ServiceUtil.returnError(errMsg, null, null, getNextOrderIdResult);
                }
                orderId = (String) getNextOrderIdResult.get("orderId");
            } catch (GenericServiceException e) {
                String errMsg = UtilProperties.getMessage(resource_error,
                        "OrderCaughtGenericServiceExceptionWhileGettingOrderId", locale);
                Debug.logError(e, errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
        }
    }

    if (UtilValidate.isEmpty(orderId)) {
        // for purchase orders or when other orderId generation fails, a product store id should not be required to make an order
        orderId = delegator.getNextSeqId("OrderHeader");
    }

    String billingAccountId = (String) context.get("billingAccountId");
    if (orderDate == null) {
        orderDate = nowTimestamp;
    }

    Map<String, Object> orderHeaderMap = UtilMisc.<String, Object>toMap("orderId", orderId, "orderTypeId",
            orderTypeId, "orderDate", orderDate, "entryDate", nowTimestamp, "statusId", initialStatus,
            "billingAccountId", billingAccountId);
    orderHeaderMap.put("orderName", context.get("orderName"));
    orderHeaderMap.put("estimatedDeliveryDate", context.get("estimatedDeliveryDate"));
    orderHeaderMap.put("isEnableAcctg", context.get("isEnableAcctg"));
    if (isImmediatelyFulfilled) {
        // also flag this order as needing inventory issuance so that when it is set to complete it will be issued immediately (needsInventoryIssuance = Y)
        orderHeaderMap.put("needsInventoryIssuance", "Y");
    }
    GenericValue orderHeader = delegator.makeValue("OrderHeader", orderHeaderMap);

    // determine the sales channel
    String salesChannelEnumId = (String) context.get("salesChannelEnumId");
    if ((salesChannelEnumId == null) || salesChannelEnumId.equals("UNKNWN_SALES_CHANNEL")) {
        // try the default store sales channel
        if (orderTypeId.equals("SALES_ORDER") && (productStore != null)) {
            salesChannelEnumId = productStore.getString("defaultSalesChannelEnumId");
        }
        // if there's still no channel, set to unknown channel
        if (salesChannelEnumId == null) {
            salesChannelEnumId = "UNKNWN_SALES_CHANNEL";
        }
    }
    orderHeader.set("salesChannelEnumId", salesChannelEnumId);

    if (context.get("currencyUom") != null) {
        orderHeader.set("currencyUom", context.get("currencyUom"));
    }

    if (context.get("firstAttemptOrderId") != null) {
        orderHeader.set("firstAttemptOrderId", context.get("firstAttemptOrderId"));
    }

    if (context.get("grandTotal") != null) {
        orderHeader.set("grandTotal", context.get("grandTotal"));
    }

    if (UtilValidate.isNotEmpty(context.get("visitId"))) {
        orderHeader.set("visitId", context.get("visitId"));
    }

    if (UtilValidate.isNotEmpty(context.get("internalCode"))) {
        orderHeader.set("internalCode", context.get("internalCode"));
    }

    if (UtilValidate.isNotEmpty(context.get("externalId"))) {
        orderHeader.set("externalId", context.get("externalId"));
    }

    if (UtilValidate.isNotEmpty(context.get("originFacilityId"))) {
        orderHeader.set("originFacilityId", context.get("originFacilityId"));
    }
    if (UtilValidate.isNotEmpty(context.get("productSubscriptionTypeId"))) {
        orderHeader.set("productSubscriptionTypeId", context.get("productSubscriptionTypeId"));
    }
    if (UtilValidate.isNotEmpty(context.get("shipmentId"))) {
        orderHeader.set("shipmentId", context.get("shipmentId"));
    }
    if (UtilValidate.isNotEmpty(context.get("purposeTypeId"))) {
        orderHeader.set("purposeTypeId", context.get("purposeTypeId"));
    }
    if (UtilValidate.isNotEmpty(context.get("productStoreId"))) {
        orderHeader.set("productStoreId", context.get("productStoreId"));
    }

    if (UtilValidate.isNotEmpty(context.get("transactionId"))) {
        orderHeader.set("transactionId", context.get("transactionId"));
    }

    if (UtilValidate.isNotEmpty(context.get("terminalId"))) {
        orderHeader.set("terminalId", context.get("terminalId"));
    }

    if (UtilValidate.isNotEmpty(context.get("autoOrderShoppingListId"))) {
        orderHeader.set("autoOrderShoppingListId", context.get("autoOrderShoppingListId"));
    }

    if (UtilValidate.isNotEmpty(context.get("webSiteId"))) {
        orderHeader.set("webSiteId", context.get("webSiteId"));
    }

    if (userLogin != null && userLogin.get("userLoginId") != null) {
        orderHeader.set("createdBy", userLogin.getString("userLoginId"));
    }
    if (UtilValidate.isNotEmpty(context.get("orderName"))) {
        orderHeader.set("orderName", context.get("orderName"));
    }
    // first try to create the OrderHeader; if this does not fail, continue.
    try {
        delegator.create(orderHeader);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot create OrderHeader entity; problems with insert", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                "OrderOrderCreationFailedPleaseNotifyCustomerService", locale));
    }

    // create the order status record
    String orderStatusSeqId = delegator.getNextSeqId("OrderStatus");
    GenericValue orderStatus = delegator.makeValue("OrderStatus",
            UtilMisc.toMap("orderStatusId", orderStatusSeqId));
    orderStatus.set("orderId", orderId);
    orderStatus.set("statusId", orderHeader.getString("statusId"));
    orderStatus.set("statusDatetime", nowTimestamp);
    orderStatus.set("statusUserLogin", userLogin.getString("userLoginId"));
    toBeStored.add(orderStatus);

    // before processing orderItems process orderItemGroups so that they'll be in place for the foreign keys and what not
    List<GenericValue> orderItemGroups = UtilGenerics.checkList(context.get("orderItemGroups"));
    if (UtilValidate.isNotEmpty(orderItemGroups)) {
        Iterator<GenericValue> orderItemGroupIter = orderItemGroups.iterator();
        while (orderItemGroupIter.hasNext()) {
            GenericValue orderItemGroup = orderItemGroupIter.next();
            orderItemGroup.set("orderId", orderId);
            toBeStored.add(orderItemGroup);
        }
    }

    // set the order items
    Iterator<GenericValue> oi = orderItems.iterator();
    while (oi.hasNext()) {
        GenericValue orderItem = oi.next();
        orderItem.set("orderId", orderId);
        toBeStored.add(orderItem);

        // create the item status record
        /* String itemStatusId = delegator.getNextSeqId("OrderStatus");
         GenericValue itemStatus = delegator.makeValue("OrderStatus", UtilMisc.toMap("orderStatusId", itemStatusId));
         itemStatus.put("statusId", orderItem.get("statusId"));
         itemStatus.put("orderId", orderId);
         itemStatus.put("orderItemSeqId", orderItem.get("orderItemSeqId"));
         itemStatus.put("statusDatetime", nowTimestamp);
         itemStatus.set("statusUserLogin", userLogin.getString("userLoginId"));
         toBeStored.add(itemStatus);*/
    }

    // set the order attributes
    List<GenericValue> orderAttributes = UtilGenerics.checkList(context.get("orderAttributes"));
    if (UtilValidate.isNotEmpty(orderAttributes)) {
        Iterator<GenericValue> oattr = orderAttributes.iterator();
        while (oattr.hasNext()) {
            GenericValue oatt = oattr.next();
            oatt.set("orderId", orderId);
            toBeStored.add(oatt);
        }
    }

    // set the order item attributes
    List<GenericValue> orderItemAttributes = UtilGenerics.checkList(context.get("orderItemAttributes"));
    if (UtilValidate.isNotEmpty(orderItemAttributes)) {
        Iterator<GenericValue> oiattr = orderItemAttributes.iterator();
        while (oiattr.hasNext()) {
            GenericValue oiatt = oiattr.next();
            oiatt.set("orderId", orderId);
            toBeStored.add(oiatt);
        }
    }

    // create the order internal notes
    List<String> orderInternalNotes = UtilGenerics.checkList(context.get("orderInternalNotes"));
    if (UtilValidate.isNotEmpty(orderInternalNotes)) {
        Iterator<String> orderInternalNotesIt = orderInternalNotes.iterator();
        while (orderInternalNotesIt.hasNext()) {
            String orderInternalNote = orderInternalNotesIt.next();
            try {
                Map<String, Object> noteOutputMap = dispatcher.runSync("createOrderNote",
                        UtilMisc.<String, Object>toMap("orderId", orderId, "internalNote", "Y", "note",
                                orderInternalNote, "userLogin", userLogin));
                if (ServiceUtil.isError(noteOutputMap)) {
                    return ServiceUtil
                            .returnError(
                                    UtilProperties.getMessage(resource, "OrderOrderNoteCannotBeCreated",
                                            UtilMisc.toMap("errorString", ""), locale),
                                    null, null, noteOutputMap);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error creating internal notes while creating order: " + e.toString(),
                        module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                        "OrderOrderNoteCannotBeCreated", UtilMisc.toMap("errorString", e.toString()), locale));
            }
        }
    }

    // create the order public notes
    List<String> orderNotes = UtilGenerics.checkList(context.get("orderNotes"));
    if (UtilValidate.isNotEmpty(orderNotes)) {
        Iterator<String> orderNotesIt = orderNotes.iterator();
        while (orderNotesIt.hasNext()) {
            String orderNote = orderNotesIt.next();
            try {
                Map<String, Object> noteOutputMap = dispatcher.runSync("createOrderNote",
                        UtilMisc.<String, Object>toMap("orderId", orderId, "internalNote", "N", "note",
                                orderNote, "userLogin", userLogin));
                if (ServiceUtil.isError(noteOutputMap)) {
                    return ServiceUtil
                            .returnError(
                                    UtilProperties.getMessage(resource, "OrderOrderNoteCannotBeCreated",
                                            UtilMisc.toMap("errorString", ""), locale),
                                    null, null, noteOutputMap);
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error creating notes while creating order: " + e.toString(), module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                        "OrderOrderNoteCannotBeCreated", UtilMisc.toMap("errorString", e.toString()), locale));
            }
        }
    }

    // create the workeffort records
    // and connect them with the orderitem over the WorkOrderItemFulfillment
    // create also the techData calendars to keep track of availability of the fixed asset.
    if (UtilValidate.isNotEmpty(workEfforts)) {
        List<GenericValue> tempList = new LinkedList<GenericValue>();
        Iterator<GenericValue> we = workEfforts.iterator();
        while (we.hasNext()) {
            // create the entity maps required.
            GenericValue workEffort = we.next();
            GenericValue workOrderItemFulfillment = delegator.makeValue("WorkOrderItemFulfillment");
            // find fixed asset supplied on the workeffort map
            GenericValue fixedAsset = null;
            Debug.logInfo("find the fixedAsset", module);
            try {
                fixedAsset = delegator.findByPrimaryKey("FixedAsset",
                        UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")));
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource_error, "OrderFixedAssetNotFoundFixedAssetId",
                                UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")), locale));
            }
            if (fixedAsset == null) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource_error, "OrderFixedAssetNotFoundFixedAssetId",
                                UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")), locale));
            }
            // see if this fixed asset has a calendar, when no create one and attach to fixed asset
            Debug.logInfo("find the techdatacalendar", module);
            GenericValue techDataCalendar = null;
            try {
                techDataCalendar = fixedAsset.getRelatedOne("TechDataCalendar");
            } catch (GenericEntityException e) {
                Debug.logInfo("TechData calendar does not exist yet so create for fixedAsset: "
                        + fixedAsset.get("fixedAssetId"), module);
            }
            if (techDataCalendar == null) {
                Iterator<GenericValue> fai = tempList.iterator();
                while (fai.hasNext()) {
                    GenericValue currentValue = fai.next();
                    if ("FixedAsset".equals(currentValue.getEntityName()) && currentValue
                            .getString("fixedAssetId").equals(workEffort.getString("fixedAssetId"))) {
                        fixedAsset = currentValue;
                        break;
                    }
                }
                Iterator<GenericValue> tdci = tempList.iterator();
                while (tdci.hasNext()) {
                    GenericValue currentValue = tdci.next();
                    if ("TechDataCalendar".equals(currentValue.getEntityName()) && currentValue
                            .getString("calendarId").equals(fixedAsset.getString("calendarId"))) {
                        techDataCalendar = currentValue;
                        break;
                    }
                }
            }
            if (techDataCalendar == null) {
                techDataCalendar = delegator.makeValue("TechDataCalendar");
                Debug.logInfo("create techdata calendar because it does not exist", module);
                String calendarId = delegator.getNextSeqId("TechDataCalendar");
                techDataCalendar.set("calendarId", calendarId);
                tempList.add(techDataCalendar);
                Debug.logInfo("update fixed Asset", module);
                fixedAsset.set("calendarId", calendarId);
                tempList.add(fixedAsset);
            }
            // then create the workEffort and the workOrderItemFulfillment to connect to the order and orderItem
            workOrderItemFulfillment.set("orderItemSeqId", workEffort.get("workEffortId").toString()); // orderItemSeqNo is stored here so save first
            // workeffort
            String workEffortId = delegator.getNextSeqId("WorkEffort"); // find next available workEffortId
            workEffort.set("workEffortId", workEffortId);
            workEffort.set("workEffortTypeId", "ASSET_USAGE");
            toBeStored.add(workEffort); // store workeffort before workOrderItemFulfillment because of workEffortId key constraint
            // workOrderItemFulfillment
            workOrderItemFulfillment.set("workEffortId", workEffortId);
            workOrderItemFulfillment.set("orderId", orderId);
            toBeStored.add(workOrderItemFulfillment);
            //                Debug.logInfo("Workeffort "+ workEffortId + " created for asset " + workEffort.get("fixedAssetId") + " and order "+ workOrderItemFulfillment.get("orderId") + "/" + workOrderItemFulfillment.get("orderItemSeqId") + " created", module);
            //
            // now create the TechDataExcDay, when they do not exist, create otherwise update the capacity values
            // please note that calendarId is the same for (TechData)Calendar, CalendarExcDay and CalendarExWeek
            Timestamp estimatedStartDate = workEffort.getTimestamp("estimatedStartDate");
            Timestamp estimatedCompletionDate = workEffort.getTimestamp("estimatedCompletionDate");
            long dayCount = (estimatedCompletionDate.getTime() - estimatedStartDate.getTime()) / 86400000;
            while (--dayCount >= 0) {
                GenericValue techDataCalendarExcDay = null;
                // find an existing Day exception record
                Timestamp exceptionDateStartTime = UtilDateTime
                        .getDayStart(new Timestamp(estimatedStartDate.getTime()), (int) dayCount);
                try {
                    techDataCalendarExcDay = delegator.findByPrimaryKey("TechDataCalendarExcDay",
                            UtilMisc.toMap("calendarId", fixedAsset.get("calendarId"), "exceptionDateStartTime",
                                    exceptionDateStartTime));
                } catch (GenericEntityException e) {
                    Debug.logInfo(" techData excday record not found so creating........", module);
                }
                if (techDataCalendarExcDay == null) {
                    Iterator<GenericValue> tdcedi = tempList.iterator();
                    while (tdcedi.hasNext()) {
                        GenericValue currentValue = tdcedi.next();
                        if ("TechDataCalendarExcDay".equals(currentValue.getEntityName())
                                && currentValue.getString("calendarId")
                                        .equals(fixedAsset.getString("calendarId"))
                                && currentValue.getTimestamp("exceptionDateStartTime")
                                        .equals(exceptionDateStartTime)) {
                            techDataCalendarExcDay = currentValue;
                            break;
                        }
                    }
                }
                if (techDataCalendarExcDay == null) {
                    techDataCalendarExcDay = delegator.makeValue("TechDataCalendarExcDay");
                    techDataCalendarExcDay.set("calendarId", fixedAsset.get("calendarId"));
                    techDataCalendarExcDay.set("exceptionDateStartTime", exceptionDateStartTime);
                    techDataCalendarExcDay.set("usedCapacity", BigDecimal.ZERO); // initialise to zero
                    techDataCalendarExcDay.set("exceptionCapacity",
                            fixedAsset.getBigDecimal("productionCapacity"));
                    //                       Debug.logInfo(" techData excday record not found creating for calendarId: " + techDataCalendarExcDay.getString("calendarId") +
                    //                               " and date: " + exceptionDateStartTime.toString(), module);
                }
                // add the quantity to the quantity on the date record
                BigDecimal newUsedCapacity = techDataCalendarExcDay.getBigDecimal("usedCapacity")
                        .add(workEffort.getBigDecimal("quantityToProduce"));
                // check to see if the requested quantity is available on the requested day but only when the maximum capacity is set on the fixed asset
                if (fixedAsset.get("productionCapacity") != null) {
                    //                       Debug.logInfo("see if maximum not reached, available:  " + techDataCalendarExcDay.getString("exceptionCapacity") +
                    //                               " already allocated: " + techDataCalendarExcDay.getString("usedCapacity") +
                    //                                " Requested: " + workEffort.getString("quantityToProduce"), module);
                    if (newUsedCapacity
                            .compareTo(techDataCalendarExcDay.getBigDecimal("exceptionCapacity")) > 0) {
                        String errMsg = "ERROR: fixed_Asset_sold_out AssetId: " + workEffort.get("fixedAssetId")
                                + " on date: " + techDataCalendarExcDay.getString("exceptionDateStartTime");
                        Debug.logError(errMsg, module);
                        errorMessages.add(errMsg);
                        continue;
                    }
                }
                techDataCalendarExcDay.set("usedCapacity", newUsedCapacity);
                tempList.add(techDataCalendarExcDay);
                //                  Debug.logInfo("Update success CalendarID: " + techDataCalendarExcDay.get("calendarId").toString() +
                //                            " and for date: " + techDataCalendarExcDay.get("exceptionDateStartTime").toString() +
                //                            " and for quantity: " + techDataCalendarExcDay.getDouble("usedCapacity").toString(), module);
            }
        }
        if (tempList.size() > 0) {
            toBeStored.addAll(tempList);
        }
    }
    if (errorMessages.size() > 0) {
        return ServiceUtil.returnError(errorMessages);
    }

    // set the orderId on all adjustments; this list will include order and
    // item adjustments...
    if (UtilValidate.isNotEmpty(orderAdjustments)) {
        Iterator<GenericValue> iter = orderAdjustments.iterator();

        while (iter.hasNext()) {
            GenericValue orderAdjustment = iter.next();
            try {
                orderAdjustment.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
            } catch (IllegalArgumentException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                        "OrderErrorCouldNotGetNextSequenceIdForOrderAdjustmentCannotCreateOrder", locale));
            }

            orderAdjustment.set("orderId", orderId);
            orderAdjustment.set("createdDate", UtilDateTime.nowTimestamp());
            orderAdjustment.set("createdByUserLogin", userLogin.getString("userLoginId"));

            if (UtilValidate.isEmpty(orderAdjustment.get("orderItemSeqId"))) {
                orderAdjustment.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
            }
            if (UtilValidate.isEmpty(orderAdjustment.get("shipGroupSeqId"))) {
                orderAdjustment.set("shipGroupSeqId", DataModelConstants.SEQ_ID_NA);
            }
            toBeStored.add(orderAdjustment);
        }
    }

    // set the order contact mechs
    List<GenericValue> orderContactMechs = UtilGenerics.checkList(context.get("orderContactMechs"));
    if (UtilValidate.isNotEmpty(orderContactMechs)) {
        Iterator<GenericValue> ocmi = orderContactMechs.iterator();

        while (ocmi.hasNext()) {
            GenericValue ocm = ocmi.next();
            ocm.set("orderId", orderId);
            toBeStored.add(ocm);
        }
    }

    // set the order item contact mechs
    List<GenericValue> orderItemContactMechs = UtilGenerics.checkList(context.get("orderItemContactMechs"));
    if (UtilValidate.isNotEmpty(orderItemContactMechs)) {
        Iterator<GenericValue> oicmi = orderItemContactMechs.iterator();

        while (oicmi.hasNext()) {
            GenericValue oicm = oicmi.next();
            oicm.set("orderId", orderId);
            toBeStored.add(oicm);
        }
    }

    // set the order item ship groups
    // commented when PurchaseOrder not created without shipment
    List<String> dropShipGroupIds = FastList.newInstance(); // this list will contain the ids of all the ship groups for drop shipments (no reservations)
    if (UtilValidate.isNotEmpty(orderItemShipGroupInfo)) {
        Iterator<GenericValue> osiInfos = orderItemShipGroupInfo.iterator();
        while (osiInfos.hasNext()) {
            GenericValue valueObj = osiInfos.next();
            valueObj.set("orderId", orderId);
            /* if ("OrderItemShipGroup".equals(valueObj.getEntityName())) {
            // ship group
            if (valueObj.get("carrierRoleTypeId") == null) {
                valueObj.set("carrierRoleTypeId", "CARRIER");
            }
            if (!UtilValidate.isEmpty(valueObj.getString("supplierPartyId"))) {
                dropShipGroupIds.add(valueObj.getString("shipGroupSeqId"));
            }
             toBeStored.add(valueObj); // from out side of if we bring here
             } else */
            if ("OrderAdjustment".equals(valueObj.getEntityName())) {
                // shipping / tax adjustment(s)
                if (UtilValidate.isEmpty(valueObj.get("orderItemSeqId"))) {
                    valueObj.set("orderItemSeqId", DataModelConstants.SEQ_ID_NA);
                }
                valueObj.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
                valueObj.set("createdDate", UtilDateTime.nowTimestamp());
                valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
                toBeStored.add(valueObj);
            }

        }
    }

    // set the additional party roles
    Map<String, List<String>> additionalPartyRole = UtilGenerics
            .checkMap(context.get("orderAdditionalPartyRoleMap"));
    if (additionalPartyRole != null) {
        for (Map.Entry<String, List<String>> entry : additionalPartyRole.entrySet()) {
            String additionalRoleTypeId = entry.getKey();
            List<String> parties = entry.getValue();
            if (parties != null) {
                Iterator<String> apIt = parties.iterator();
                while (apIt.hasNext()) {
                    String additionalPartyId = apIt.next();
                    toBeStored.add(delegator.makeValue("PartyRole",
                            UtilMisc.toMap("partyId", additionalPartyId, "roleTypeId", additionalRoleTypeId)));
                    toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId,
                            "partyId", additionalPartyId, "roleTypeId", additionalRoleTypeId)));
                }
            }
        }
    }

    // set the item survey responses
    List<GenericValue> surveyResponses = UtilGenerics.checkList(context.get("orderItemSurveyResponses"));
    if (UtilValidate.isNotEmpty(surveyResponses)) {
        Iterator<GenericValue> oisr = surveyResponses.iterator();
        while (oisr.hasNext()) {
            GenericValue surveyResponse = oisr.next();
            surveyResponse.set("orderId", orderId);
            toBeStored.add(surveyResponse);
        }
    }

    // set the item price info; NOTE: this must be after the orderItems are stored for referential integrity
    if (UtilValidate.isNotEmpty(orderItemPriceInfo)) {
        Iterator<GenericValue> oipii = orderItemPriceInfo.iterator();

        while (oipii.hasNext()) {
            GenericValue oipi = oipii.next();
            try {
                oipi.set("orderItemPriceInfoId", delegator.getNextSeqId("OrderItemPriceInfo"));
            } catch (IllegalArgumentException e) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
                        "OrderErrorCouldNotGetNextSequenceIdForOrderItemPriceInfoCannotCreateOrder", locale));
            }

            oipi.set("orderId", orderId);
            toBeStored.add(oipi);
        }
    }

    // set the item associations
    List<GenericValue> orderItemAssociations = UtilGenerics.checkList(context.get("orderItemAssociations"));
    if (UtilValidate.isNotEmpty(orderItemAssociations)) {
        Iterator<GenericValue> oia = orderItemAssociations.iterator();
        while (oia.hasNext()) {
            GenericValue orderItemAssociation = oia.next();
            if (orderItemAssociation.get("toOrderId") == null) {
                orderItemAssociation.set("toOrderId", orderId);
            } else if (orderItemAssociation.get("orderId") == null) {
                orderItemAssociation.set("orderId", orderId);
            }
            toBeStored.add(orderItemAssociation);
        }
    }

    // store the orderProductPromoUseInfos
    List<GenericValue> orderProductPromoUses = UtilGenerics.checkList(context.get("orderProductPromoUses"));
    if (UtilValidate.isNotEmpty(orderProductPromoUses)) {
        Iterator<GenericValue> orderProductPromoUseIter = orderProductPromoUses.iterator();
        while (orderProductPromoUseIter.hasNext()) {
            GenericValue productPromoUse = orderProductPromoUseIter.next();
            productPromoUse.set("orderId", orderId);
            toBeStored.add(productPromoUse);
        }
    }

    // store the orderProductPromoCodes
    Set<String> orderProductPromoCodes = UtilGenerics.checkSet(context.get("orderProductPromoCodes"));
    if (UtilValidate.isNotEmpty(orderProductPromoCodes)) {
        GenericValue orderProductPromoCode = delegator.makeValue("OrderProductPromoCode");
        Iterator<String> orderProductPromoCodeIter = orderProductPromoCodes.iterator();
        while (orderProductPromoCodeIter.hasNext()) {
            orderProductPromoCode.clear();
            orderProductPromoCode.set("orderId", orderId);
            orderProductPromoCode.set("productPromoCodeId", orderProductPromoCodeIter.next());
            toBeStored.add(orderProductPromoCode);
        }
    }

    /* DEJ20050529 the OLD way, where a single party had all roles... no longer doing things this way...
    // define the roles for the order
    List userOrderRoleTypes = null;
    if ("SALES_ORDER".equals(orderTypeId)) {
    userOrderRoleTypes = UtilMisc.toList("END_USER_CUSTOMER", "SHIP_TO_CUSTOMER", "BILL_TO_CUSTOMER", "PLACING_CUSTOMER");
    } else if ("PURCHASE_ORDER".equals(orderTypeId)) {
    userOrderRoleTypes = UtilMisc.toList("SHIP_FROM_VENDOR", "BILL_FROM_VENDOR", "SUPPLIER_AGENT");
    } else {
    // TODO: some default behavior
    }
            
    // now add the roles
    if (userOrderRoleTypes != null) {
    Iterator i = userOrderRoleTypes.iterator();
    while (i.hasNext()) {
        String roleType = (String) i.next();
        String thisParty = partyId;
        if (thisParty == null) {
            thisParty = "_NA_";  // will always set these roles so we can query
        }
        // make sure the party is in the role before adding
        toBeStored.add(delegator.makeValue("PartyRole", UtilMisc.toMap("partyId", partyId, "roleTypeId", roleType)));
        toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId", partyId, "roleTypeId", roleType)));
    }
    }
    */

    // see the attributeRoleMap definition near the top of this file for attribute-role mappings
    Map<String, String> attributeRoleMap = salesAttributeRoleMap;
    GenericValue orderHeaderType = null;
    try {
        orderHeaderType = delegator.findOne("OrderType", UtilMisc.toMap("orderTypeId", orderTypeId), false);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problems to get orderType", module);
    }
    if (("PURCHASE_ORDER".equals(orderTypeId)) || (UtilValidate.isNotEmpty(orderHeaderType)
            && ("PURCHASE_ORDER".equals(orderHeaderType.getString("parentTypeId"))))) {
        attributeRoleMap = purchaseAttributeRoleMap;
        //Debug.log("===orderTypeId==beforeRole="+orderTypeId);
    }
    for (Map.Entry<String, String> attributeRoleEntry : attributeRoleMap.entrySet()) {
        if (UtilValidate.isNotEmpty(context.get(attributeRoleEntry.getKey()))) {
            // make sure the party is in the role before adding
            toBeStored.add(delegator.makeValue("PartyRole", UtilMisc.toMap("partyId",
                    context.get(attributeRoleEntry.getKey()), "roleTypeId", attributeRoleEntry.getValue())));
            toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId",
                    context.get(attributeRoleEntry.getKey()), "roleTypeId", attributeRoleEntry.getValue())));
        }
    }

    // set the affiliate -- This is going to be removed...
    String affiliateId = (String) context.get("affiliateId");
    if (UtilValidate.isNotEmpty(affiliateId)) {
        toBeStored.add(delegator.makeValue("OrderRole",
                UtilMisc.toMap("orderId", orderId, "partyId", affiliateId, "roleTypeId", "AFFILIATE")));
    }

    // set the distributor
    String distributorId = (String) context.get("distributorId");
    if (UtilValidate.isNotEmpty(distributorId)) {
        toBeStored.add(delegator.makeValue("OrderRole",
                UtilMisc.toMap("orderId", orderId, "partyId", distributorId, "roleTypeId", "DISTRIBUTOR")));
    }

    // find all parties in role VENDOR associated with WebSite OR ProductStore (where WebSite overrides, if specified), associated first valid with the Order
    if (UtilValidate.isNotEmpty(context.get("productStoreId"))) {
        try {
            List<GenericValue> productStoreRoles = delegator.findByAnd("ProductStoreRole",
                    UtilMisc.toMap("roleTypeId", "VENDOR", "productStoreId", context.get("productStoreId")),
                    UtilMisc.toList("-fromDate"));
            productStoreRoles = EntityUtil.filterByDate(productStoreRoles, true);
            GenericValue productStoreRole = EntityUtil.getFirst(productStoreRoles);
            if (productStoreRole != null) {
                toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId",
                        productStoreRole.get("partyId"), "roleTypeId", "VENDOR")));
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error looking up Vendor for the current Product Store", module);
        }

    }
    if (UtilValidate.isNotEmpty(context.get("webSiteId"))) {
        try {
            List<GenericValue> webSiteRoles = delegator.findByAnd("WebSiteRole",
                    UtilMisc.toMap("roleTypeId", "VENDOR", "webSiteId", context.get("webSiteId")),
                    UtilMisc.toList("-fromDate"));
            webSiteRoles = EntityUtil.filterByDate(webSiteRoles, true);
            GenericValue webSiteRole = EntityUtil.getFirst(webSiteRoles);
            if (webSiteRole != null) {
                toBeStored.add(delegator.makeValue("OrderRole", UtilMisc.toMap("orderId", orderId, "partyId",
                        webSiteRole.get("partyId"), "roleTypeId", "VENDOR")));
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Error looking up Vendor for the current Web Site", module);
        }

    }

    // set the order payment info
    List<GenericValue> orderPaymentInfos = UtilGenerics.checkList(context.get("orderPaymentInfo"));
    if (UtilValidate.isNotEmpty(orderPaymentInfos)) {
        Iterator<GenericValue> oppIter = orderPaymentInfos.iterator();
        while (oppIter.hasNext()) {
            GenericValue valueObj = oppIter.next();
            valueObj.set("orderId", orderId);
            if ("OrderPaymentPreference".equals(valueObj.getEntityName())) {
                if (valueObj.get("orderPaymentPreferenceId") == null) {
                    valueObj.set("orderPaymentPreferenceId", delegator.getNextSeqId("OrderPaymentPreference"));
                    valueObj.set("createdDate", UtilDateTime.nowTimestamp());
                    valueObj.set("createdByUserLogin", userLogin.getString("userLoginId"));
                }
                if (valueObj.get("statusId") == null) {
                    valueObj.set("statusId", "PAYMENT_NOT_RECEIVED");
                }
            }
            toBeStored.add(valueObj);
        }
    }

    // store the trackingCodeOrder entities
    List<GenericValue> trackingCodeOrders = UtilGenerics.checkList(context.get("trackingCodeOrders"));
    if (UtilValidate.isNotEmpty(trackingCodeOrders)) {
        Iterator<GenericValue> tkcdordIter = trackingCodeOrders.iterator();
        while (tkcdordIter.hasNext()) {
            GenericValue trackingCodeOrder = tkcdordIter.next();
            trackingCodeOrder.set("orderId", orderId);
            toBeStored.add(trackingCodeOrder);
        }
    }

    // store the OrderTerm entities

    List<GenericValue> orderTerms = UtilGenerics.checkList(context.get("orderTerms"));
    if (UtilValidate.isNotEmpty(orderTerms)) {
        Iterator<GenericValue> orderTermIter = orderTerms.iterator();
        while (orderTermIter.hasNext()) {
            GenericValue orderTerm = orderTermIter.next();
            orderTerm.set("orderId", orderId);
            if (orderTerm.get("orderItemSeqId") == null) {
                orderTerm.set("orderItemSeqId", "_NA_");
            }
            toBeStored.add(orderTerm);
        }
    }

    // if a workEffortId is passed, then prepare a OrderHeaderWorkEffort value
    String workEffortId = (String) context.get("workEffortId");
    if (UtilValidate.isNotEmpty(workEffortId)) {
        GenericValue orderHeaderWorkEffort = delegator.makeValue("OrderHeaderWorkEffort");
        orderHeaderWorkEffort.set("orderId", orderId);
        orderHeaderWorkEffort.set("workEffortId", workEffortId);
        toBeStored.add(orderHeaderWorkEffort);
    }

    try {
        // store line items, etc so that they will be there for the foreign key checks
        delegator.storeAll(toBeStored);

        // START inventory reservation
        // commented when PurchaseOrder not created without shipment
        /*List<String> resErrorMessages = new LinkedList<String>();
        try {
        reserveInventory(delegator, dispatcher, userLogin, locale, orderItemShipGroupInfo, dropShipGroupIds, itemValuesBySeqId,
                orderTypeId, productStoreId, resErrorMessages);
        } catch (GeneralException e) {
        return ServiceUtil.returnError(e.getMessage());
        }
                
        if (resErrorMessages.size() > 0) {
        return ServiceUtil.returnError(resErrorMessages);
        }*/
        // END inventory reservation

        successResult.put("orderId", orderId);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Problem with order storage or reservations", module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource_error, "OrderErrorCouldNotCreateOrderWriteError", locale)
                        + e.getMessage() + ").");
    }

    return successResult;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public BigDecimal[] getGutSchlechtInarbeit(Integer lossollarbeitsplanIId, Integer personalIId,
        java.sql.Timestamp tVon, java.sql.Timestamp tBis, TheClientDto theClientDto) {
    LosgutschlechtDto[] dtos = losgutschlechtFindByLossollarbeitsplanIId(lossollarbeitsplanIId);
    LossollarbeitsplanDto lossollarbeitsplanDto = lossollarbeitsplanFindByPrimaryKey(lossollarbeitsplanIId);
    LosDto losDto = losFindByPrimaryKey(lossollarbeitsplanDto.getLosIId());

    BigDecimal bdGut = new BigDecimal(0);
    BigDecimal bdSchlecht = new BigDecimal(0);
    BigDecimal bdInarbeit = new BigDecimal(0);
    BigDecimal bdOffen = losDto.getNLosgroesse();

    for (int i = 0; i < dtos.length; i++) {

        if (personalIId != null && dtos[i].getZeitdatenIId() != null) {
            Zeitdaten z = em.find(Zeitdaten.class, dtos[i].getZeitdatenIId());

            if (z.getPersonalIId().equals(personalIId)) {

                if ((tVon == null || tVon != null && tVon.before(z.getTZeit()))
                        && (tBis == null || tBis != null && tBis.after(z.getTZeit()))) {
                    bdGut = bdGut.add(dtos[i].getNGut());
                    bdSchlecht = bdSchlecht.add(dtos[i].getNSchlecht());
                    bdInarbeit = bdInarbeit.add(dtos[i].getNInarbeit());
                }//from w w w  .  j ava  2s .c o m

            }

        } else {

            bdGut = bdGut.add(dtos[i].getNGut());
            bdSchlecht = bdSchlecht.add(dtos[i].getNSchlecht());
            bdInarbeit = bdInarbeit.add(dtos[i].getNInarbeit());
        }

    }

    bdOffen = bdOffen.subtract(bdGut).subtract(bdSchlecht);

    boolean bTheoretischeIstZeit = false;

    try {
        ParametermandantDto parameterIstZeit = (ParametermandantDto) getParameterFac().getMandantparameter(
                theClientDto.getMandant(), ParameterFac.KATEGORIE_PERSONAL,
                ParameterFac.PARAMETER_THEORETISCHE_IST_ZEIT_RECHNUNG);

        bTheoretischeIstZeit = ((Boolean) parameterIstZeit.getCWertAsObject());

    } catch (RemoteException ex5) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER, ex5);
    }
    // lt. WH:Wenn TheoretischeIstZeit und "nicht ruesten", dann die
    // Gut/Schlecht Stueck der Ruestzeit des AGs abziehen

    if (bTheoretischeIstZeit == true) {

        // Wenn nicht ruesten
        if (lossollarbeitsplanDto.getAgartCNr() != null) {

            Query query = em.createNamedQuery("LossollarbeitsplanfindByLosIIdIArbeitsgangnummer");
            query.setParameter(1, lossollarbeitsplanDto.getLosIId());
            query.setParameter(2, lossollarbeitsplanDto.getIArbeitsgangnummer());
            Collection<?> cl = query.getResultList();

            if (cl != null) {
                Iterator<?> iterator = cl.iterator();
                while (iterator.hasNext()) {
                    Lossollarbeitsplan lossollarbeitsplanTemp = (Lossollarbeitsplan) iterator.next();
                    if (lossollarbeitsplanTemp.getAgartCNr() == null) {
                        LosgutschlechtDto[] dtosRuestZeit = losgutschlechtFindByLossollarbeitsplanIId(
                                lossollarbeitsplanTemp.getIId());

                        for (int i = 0; i < dtosRuestZeit.length; i++) {
                            bdOffen = bdOffen.subtract(dtosRuestZeit[i].getNGut())
                                    .subtract(dtosRuestZeit[i].getNSchlecht());
                        }

                    }
                }

            }
        }
    }

    return new BigDecimal[] { bdGut, bdSchlecht, bdInarbeit, bdOffen };
}