Example usage for java.sql Timestamp before

List of usage examples for java.sql Timestamp before

Introduction

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

Prototype

public boolean before(Timestamp ts) 

Source Link

Document

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

Usage

From source file:com.lp.webapp.zemecs.CommandZE.java

private String getMeldungGebuchtFuerBDE(Object data, String taetigkeit, TheClientDto theClientDto)
        throws Exception {

    HashMap<?, ?> hmParameter = (HashMap<?, ?>) data;
    ZeitdatenDto zeitdatenDto = (ZeitdatenDto) hmParameter.get("zeitdaten");
    String person = (String) hmParameter.get("person");
    String beleg = (String) hmParameter.get("beleg");
    MaschineDto maschine = (MaschineDto) hmParameter.get("maschine");

    Integer taetigkeitIId_Kommt = getZeiterfassungsFac()
            .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_KOMMT, theClientDto).getIId();
    Integer taetigkeitIId_Geht = getZeiterfassungsFac()
            .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_GEHT, theClientDto).getIId();

    String tmp = "Letzte Buchung: " + person + ", ";
    if (beleg != null) {
        tmp += beleg + ", ";
    }//from   w ww.j  a  v a 2 s .  com

    if (hmParameter.containsKey("fertig")) {
        tmp += " Fertig-Buchung, ";
    } else {
        if (maschine != null && maschine.getBezeichnung().trim().length() > 0) {
            tmp += " Maschine: " + maschine.getBezeichnung() + ", ";
        }
    }

    if (zeitdatenDto.getTaetigkeitIId() != null) {
        tmp += "Sondert\u00E4tigkeit: " + taetigkeit;
    } else {
        if (taetigkeit != null) {
            tmp += "T\u00E4tigkeit: " + taetigkeit;
        }
    }

    tmp += " um " + Helper.formatTimestamp(zeitdatenDto.getTZeit(), new Locale("de", "AT"));

    // Meldung ob KOMMT/GEHT fehlt
    Timestamp tBis = new Timestamp(zeitdatenDto.getTZeit().getTime() + 100);
    ZeitdatenDto[] zeitdatenDtos = getZeiterfassungsFac()
            .zeitdatenFindZeitdatenEinesTagesUndEinerPersonOnheBelegzeiten(zeitdatenDto.getPersonalIId(),
                    Helper.cutTimestamp(zeitdatenDto.getTZeit()), tBis);
    boolean bKommtfuerHeuteFehlt = true;
    for (int i = 0; i < zeitdatenDtos.length; i++) {
        ZeitdatenDto zeitdatenDtoZeile = zeitdatenDtos[i];
        if (zeitdatenDtoZeile.getTaetigkeitIId() != null
                && zeitdatenDtoZeile.getTaetigkeitIId().equals(taetigkeitIId_Kommt)) {
            bKommtfuerHeuteFehlt = false;

            break;
        }
    }

    if (bKommtfuerHeuteFehlt == true) {
        tmp += "<br><font color=\"#FF0000\">KOMMT f\u00FCr heute fehlt</font>";
    }

    Timestamp tLetztesGeht = null;
    Timestamp tLetztesKommt = null;

    // Meldung ob GEHT ind den etzten Tagen fehlt
    // Hole letztes GEHT
    Session session = FLRSessionFactory.getFactory().openSession();
    org.hibernate.Criteria liste = session.createCriteria(FLRZeitdaten.class);
    liste.add(Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_PERSONAL_I_ID, zeitdatenDto.getPersonalIId()));
    liste.add(Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_TAETIGKEIT_I_ID, taetigkeitIId_Geht));
    liste.add(
            Expression.lt(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT, Helper.cutTimestamp(zeitdatenDto.getTZeit())));

    liste.addOrder(Order.desc(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT));
    liste.setMaxResults(1);
    List<?> letzerAuftrag = liste.list();

    Iterator<?> it = letzerAuftrag.iterator();

    if (it.hasNext()) {
        FLRZeitdaten flrLetzerAuftrag = (FLRZeitdaten) it.next();
        tLetztesGeht = new Timestamp(flrLetzerAuftrag.getT_zeit().getTime());
    }
    session.close();

    session = FLRSessionFactory.getFactory().openSession();
    liste = session.createCriteria(FLRZeitdaten.class);
    liste.add(Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_PERSONAL_I_ID, zeitdatenDto.getPersonalIId()));
    liste.add(Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_TAETIGKEIT_I_ID, taetigkeitIId_Kommt));
    liste.add(
            Expression.lt(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT, Helper.cutTimestamp(zeitdatenDto.getTZeit())));

    liste.addOrder(Order.desc(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT));
    liste.setMaxResults(1);
    letzerAuftrag = liste.list();

    it = letzerAuftrag.iterator();

    if (it.hasNext()) {
        FLRZeitdaten flrLetzerAuftrag = (FLRZeitdaten) it.next();
        tLetztesKommt = new Timestamp(flrLetzerAuftrag.getT_zeit().getTime());
    }

    if (tLetztesGeht != null && tLetztesKommt != null) {
        if (tLetztesGeht.before(tLetztesKommt)) {
            tmp += "<br><font color=\"#FF0000\">Letzte GEHT-Buchung fehlt.</font>";
        }
    }
    if (tLetztesKommt != null && tLetztesGeht == null) {
        tmp += "<br><font color=\"#FF0000\">Letzte GEHT-Buchung fehlt.</font>";
    }

    return tmp;

}

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

public List getViewModules(String userId, String courseId) throws Exception {
    Connection dbConnection = null;
    List resList = new ArrayList();
    List courseIdList = new ArrayList();
    List sectionsList = null;/*from www.jav a  2s  .c  o  m*/
    Module mod = null;
    Query sectionQuery = null;

    try {
        dbConnection = SqlService.borrowConnection();
        //Check the special access table to see if there are any records
        //for this user in this course
        ResultSet accRs, rs = null;
        String sql = "select a.module_id,a.start_date,a.end_date from melete_special_access a,melete_course_module c where a.users like ? and a.module_id=c.module_id and c.course_id = ?";
        PreparedStatement accPstmt = dbConnection.prepareStatement(sql);
        accPstmt.setString(1, "%" + userId + "%");
        accPstmt.setString(2, courseId);
        accRs = accPstmt.executeQuery();
        Map accMap = new HashMap();
        if (accRs != null) {
            int accModuleId;
            while (accRs.next()) {
                accModuleId = accRs.getInt("module_id");
                AccessDates ad = new AccessDates(accRs.getTimestamp("start_date"),
                        accRs.getTimestamp("end_date"));
                accMap.put(accModuleId, ad);
            }
        }
        sql = "select m.module_id,c.seq_no,m.title as modTitle,m.whats_next,m.seq_xml,d.start_date,d.end_date,s.section_id,s.content_type,s.title as secTitle from melete_module m inner join melete_module_shdates d on m.module_id=d.module_id inner join melete_course_module c on m.module_id=c.module_id left outer join melete_section s on m.module_id = s.module_id where c.course_id = ? and c.delete_flag=0 and c.archv_flag=0 and (s.delete_flag=0 or s.delete_flag is NULL) order by c.seq_no";
        PreparedStatement pstmt = dbConnection.prepareStatement(sql);
        pstmt.setString(1, courseId);
        rs = pstmt.executeQuery();
        ViewSecBean vsBean = null;
        Map vsBeanMap = null;
        SubSectionUtilImpl ssuImpl;
        StringBuffer rowClassesBuf;
        List vsBeanList = null;
        int prevModId = 0, prevSeqNo = 0;
        int moduleId, seqNo;
        ViewModBean vmBean = null;
        String seqXml, prevSeqXml = null;
        java.sql.Timestamp startTimestamp, endTimestamp;
        if (rs != null) {
            while (rs.next()) {

                moduleId = rs.getInt("module_id");
                seqNo = rs.getInt("seq_no");
                seqXml = rs.getString("seq_xml");

                //                   Associate vsBeans to vmBean
                //This means its a new module
                if ((prevModId != 0) && (moduleId != prevModId)) {
                    if (vsBeanMap != null) {
                        if (vsBeanMap.size() > 0) {
                            ssuImpl = new SubSectionUtilImpl();
                            ssuImpl.traverseDom(prevSeqXml, Integer.toString(prevSeqNo));
                            xmlSecList = ssuImpl.getXmlSecList();
                            rowClassesBuf = new StringBuffer();

                            //Comment for now
                            xmlSecList = correctSections(vsBeanMap, mod, xmlSecList);
                            vsBeanList = new ArrayList();
                            processViewSections(vsBeanMap, vsBeanList, xmlSecList, rowClassesBuf);
                            vmBean.setVsBeans(vsBeanList);
                            vmBean.setRowClasses(rowClassesBuf.toString());
                        }
                    }
                    vsBeanMap = null;
                }

                //Populate each vsBean and add to vsBeanMap
                int sectionId = rs.getInt("section_id");
                if (sectionId != 0) {
                    if (vsBeanMap == null)
                        vsBeanMap = new LinkedHashMap();

                    vsBean = new ViewSecBean();
                    vsBean.setSectionId(sectionId);
                    vsBean.setContentType(rs.getString("content_type"));
                    vsBean.setTitle(rs.getString("secTitle"));
                    vsBeanMap.put(new Integer(sectionId), vsBean);
                }

                //Populate vmBean
                //This means its the first module or a new module
                if ((prevModId == 0) || (moduleId != prevModId)) {
                    vmBean = new ViewModBean();
                    vmBean.setModuleId(moduleId);
                    vmBean.setSeqNo(seqNo);
                    vmBean.setTitle(rs.getString("modTitle"));
                    vmBean.setWhatsNext(rs.getString("whats_next"));
                    vmBean.setSeqXml(seqXml);

                    // what's next display seq number is number of top level sections + 1
                    SubSectionUtilImpl ssuImpl1 = new SubSectionUtilImpl();
                    int top = ssuImpl1.noOfTopLevelSections(seqXml);
                    top = top + 1;
                    String ns_number = new String(seqNo + ".");
                    ns_number = ns_number.concat(Integer.toString(top));
                    vmBean.setNextStepsNumber(ns_number);

                    startTimestamp = null;
                    endTimestamp = null;

                    //If special access is set up, use those dates; otherwise,
                    //use module dates
                    if (accMap.size() > 0) {
                        AccessDates ad = (AccessDates) accMap.get(moduleId);
                        if (ad == null) {
                            startTimestamp = rs.getTimestamp("start_date");
                            endTimestamp = rs.getTimestamp("end_date");
                        } else {
                            startTimestamp = ad.getAccStartTimestamp();
                            endTimestamp = ad.getAccEndTimestamp();
                        }
                    } else {
                        startTimestamp = rs.getTimestamp("start_date");
                        endTimestamp = rs.getTimestamp("end_date");
                    }

                    java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(
                            Calendar.getInstance().getTimeInMillis());

                    if (((startTimestamp == null) || (startTimestamp.before(currentTimestamp)))
                            && ((endTimestamp == null) || (endTimestamp.after(currentTimestamp)))) {
                        vmBean.setVisibleFlag(true);
                    } else {
                        vmBean.setVisibleFlag(false);
                    }
                    if (startTimestamp != null) {
                        vmBean.setStartDate(new java.util.Date(
                                startTimestamp.getTime() + (startTimestamp.getNanos() / 1000000)));
                    }
                    if (endTimestamp != null) {
                        vmBean.setEndDate(new java.util.Date(
                                endTimestamp.getTime() + (endTimestamp.getNanos() / 1000000)));
                    }
                    resList.add(vmBean);
                }

                prevModId = moduleId;
                prevSeqNo = seqNo;
                prevSeqXml = seqXml;

            } //End while

            //The last module will not have had its sections added
            //so we do it here
            if (vsBeanMap != null) {
                if (vsBeanMap.size() > 0) {
                    ssuImpl = new SubSectionUtilImpl();
                    ssuImpl.traverseDom(prevSeqXml, Integer.toString(prevSeqNo));
                    xmlSecList = ssuImpl.getXmlSecList();
                    rowClassesBuf = new StringBuffer();

                    xmlSecList = correctSections(vsBeanMap, mod, xmlSecList);
                    vsBeanList = new ArrayList();
                    processViewSections(vsBeanMap, vsBeanList, xmlSecList, rowClassesBuf);
                    vmBean.setVsBeans(vsBeanList);
                    vmBean.setRowClasses(rowClassesBuf.toString());
                }
            }
            accRs.close();
            accPstmt.close();
            rs.close();
            pstmt.close();
        }
    } catch (Exception e) {
        if (logger.isErrorEnabled())
            logger.error(e);
        throw e;
    } finally {
        try {
            if (dbConnection != null)
                SqlService.returnConnection(dbConnection);
        } catch (Exception e1) {
            if (logger.isErrorEnabled())
                logger.error(e1);
            throw e1;
        }
    }

    return resList;
}

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

@TransactionAttribute(TransactionAttributeType.NEVER)
public LosDto createLoseAusAuftrag(LosDto losDto, Integer auftragIId, TheClientDto theClientDto) {

    LosDto losReturn = null;/*from  w  ww  .j  a  v a  2s .  c om*/
    try {
        AuftragDto auftragDto = getAuftragFac().auftragFindByPrimaryKey(auftragIId);

        KundeDto kdDto = getKundeFac().kundeFindByPrimaryKey(auftragDto.getKundeIIdAuftragsadresse(),
                theClientDto);
        if (auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_ANGELEGT)
                || auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_OFFEN)
                || auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_TEILERLEDIGT)) {
            AuftragpositionDto[] dtos = getAuftragpositionFac().auftragpositionFindByAuftrag(auftragIId);
            for (int i = 0; i < dtos.length; i++) {
                StuecklisteDto stuecklisteDto = getStuecklisteFac()
                        .stuecklisteFindByMandantCNrArtikelIIdOhneExc(dtos[i].getArtikelIId(), theClientDto);
                if (stuecklisteDto != null) {
                    if (dtos[i].getNOffeneMenge() != null && dtos[i].getNOffeneMenge().doubleValue() > 0)
                        losDto.setAuftragpositionIId(dtos[i].getIId());
                    losDto.setNLosgroesse(dtos[i].getNOffeneMenge());

                    // SP1595 Termine berechnen

                    Timestamp tAuftragsliefertermin = dtos[i].getTUebersteuerbarerLiefertermin();

                    Timestamp tEnde = Helper.addiereTageZuTimestamp(tAuftragsliefertermin,
                            -kdDto.getILieferdauer());

                    int durchlaufzeit = 0;
                    if (stuecklisteDto.getNDefaultdurchlaufzeit() != null) {
                        durchlaufzeit = stuecklisteDto.getNDefaultdurchlaufzeit().intValue();
                    }

                    Timestamp tBeginn = Helper.addiereTageZuTimestamp(tEnde, -durchlaufzeit);

                    if (tBeginn.before(Helper.cutTimestamp(new Timestamp(System.currentTimeMillis())))) {

                        tBeginn = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));
                        tEnde = Helper.addiereTageZuTimestamp(tBeginn, durchlaufzeit);
                    }

                    losDto.setTProduktionsbeginn(new java.sql.Date(tBeginn.getTime()));
                    losDto.setTProduktionsende(new java.sql.Date(tEnde.getTime()));

                    losDto.setStuecklisteIId(stuecklisteDto.getIId());
                    losReturn = getFertigungFac().createLos(losDto, theClientDto);
                }
            }
        }
    } catch (RemoteException e) {
        throwEJBExceptionLPRespectOld(e);
    }
    return losReturn;
}

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

@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public int wiederholendeLoseAnlegen(TheClientDto theClientDto) {

    int iAnzahlAngelegterLose = 0;
    DateFormatSymbols symbols = new DateFormatSymbols(theClientDto.getLocUi());
    String[] defaultMonths = symbols.getMonths();
    int iStandarddurchlaufzeit = 0;
    try {/* ww w  .  j  av a2 s .  c om*/
        ParametermandantDto parameter = getParameterFac().getMandantparameter(theClientDto.getMandant(),
                ParameterFac.KATEGORIE_FERTIGUNG, ParameterFac.INTERNEBESTELLUNG_DEFAULTDURCHLAUFZEIT);
        iStandarddurchlaufzeit = ((Integer) parameter.getCWertAsObject()).intValue();
    } catch (RemoteException ex2) {
        throwEJBExceptionLPRespectOld(ex2);
    }

    Session session = FLRSessionFactory.getFactory().openSession();

    Criteria crit = session.createCriteria(FLRWiederholendelose.class);

    crit.add(Restrictions.eq("mandant_c_nr", theClientDto.getMandant()));
    crit.add(Restrictions.eq(FertigungFac.FLR_WIEDERHOLENDELOSE_B_VERSTECKT, Helper.boolean2Short(false)));

    List<?> resultList = crit.list();
    Iterator<?> resultListIterator = resultList.iterator();
    while (resultListIterator.hasNext()) {
        FLRWiederholendelose flrWiederholendelose = (FLRWiederholendelose) resultListIterator.next();

        // Naechster faelliger Termin nach Heute
        Calendar cBeginn = Calendar.getInstance();
        cBeginn.setTimeInMillis(flrWiederholendelose.getT_termin().getTime());

        String intervall = flrWiederholendelose.getAuftragwiederholungsintervall_c_nr();

        Timestamp tHeute = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));

        while (cBeginn.getTimeInMillis() < tHeute.getTime()) {

            if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_2WOECHENTLICH)) {
                cBeginn.set(Calendar.DAY_OF_MONTH, cBeginn.get(Calendar.DAY_OF_MONTH) + 14);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_WOECHENTLICH)) {
                cBeginn.set(Calendar.DAY_OF_MONTH, cBeginn.get(Calendar.DAY_OF_MONTH) + 7);
            }

            if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 1);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_2JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 2);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_3JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 3);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_4JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 4);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_5JAHR)) {
                cBeginn.set(Calendar.YEAR, cBeginn.get(Calendar.YEAR) + 5);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_MONATLICH)) {
                cBeginn.set(Calendar.MONTH, cBeginn.get(Calendar.MONTH) + 1);
            } else if (intervall.equals(AuftragServiceFac.AUFTRAGWIEDERHOLUNGSINTERVALL_QUARTAL)) {
                cBeginn.set(Calendar.MONTH, cBeginn.get(Calendar.MONTH) + 3);
            }
        }

        Timestamp tBeginndatumFuerLos = new Timestamp(cBeginn.getTimeInMillis());
        // Voreilende Tage abziehen

        String monatsname = defaultMonths[cBeginn.get(Calendar.MONTH)];
        int iJahr = cBeginn.get(Calendar.YEAR);

        int iTageVoreilend = flrWiederholendelose.getI_tagevoreilend();
        cBeginn.set(Calendar.DAY_OF_MONTH, cBeginn.get(Calendar.DAY_OF_MONTH) - iTageVoreilend);

        Timestamp tAnlagedatum = new Timestamp(cBeginn.getTimeInMillis());

        if (tAnlagedatum.before(tHeute) || tAnlagedatum.equals(tHeute)) {
            // try {
            Query query = em.createNamedQuery("LosfindWiederholendeloseIIdTProduktionsbeginnMandantCNr");
            query.setParameter(1, flrWiederholendelose.getI_id());
            query.setParameter(2, tBeginndatumFuerLos);
            query.setParameter(3, theClientDto.getMandant());
            Collection<?> cl = query.getResultList();
            // if (cl.isEmpty()) {
            // throw new EJBExceptionLP(EJBExceptionLP.FEHLER, null);
            // }
            LosDto[] lose = assembleLosDtos(cl);

            // Wenn noch nicht angelegt
            if (lose.length == 0) {

                WiederholendeloseDto dto = wiederholendeloseFindByPrimaryKey(flrWiederholendelose.getI_id());
                String projektname = "";
                if (dto.getCProjekt() != null) {
                    projektname += dto.getCProjekt() + " ";
                }
                projektname += monatsname + " " + iJahr;

                if (projektname.length() > 50) {
                    projektname = projektname.substring(0, 49);
                }

                LosDto losDto = new LosDto();
                losDto.setWiederholendeloseIId(dto.getIId());
                losDto.setCProjekt(projektname);
                losDto.setFertigungsgruppeIId(dto.getFertigungsgruppeIId());
                losDto.setKostenstelleIId(dto.getKostenstelleIId());
                losDto.setLagerIIdZiel(dto.getLagerIIdZiel());
                losDto.setMandantCNr(theClientDto.getMandant());
                losDto.setNLosgroesse(dto.getNLosgroesse());
                losDto.setPartnerIIdFertigungsort(dto.getPartnerIIdFertigungsort());
                losDto.setStuecklisteIId(dto.getStuecklisteIId());
                losDto.setTProduktionsbeginn(new java.sql.Date(tBeginndatumFuerLos.getTime()));

                // Produktionsende

                try {

                    int laufzeit = iStandarddurchlaufzeit;
                    if (dto.getStuecklisteIId() != null) {
                        StuecklisteDto stuecklisteDto = getStuecklisteFac()
                                .stuecklisteFindByPrimaryKey(dto.getStuecklisteIId(), theClientDto);
                        if (stuecklisteDto.getNDefaultdurchlaufzeit() != null) {
                            laufzeit = stuecklisteDto.getNDefaultdurchlaufzeit().intValue();
                        }
                    }
                    Calendar cTemp = Calendar.getInstance();
                    cTemp.setTimeInMillis(tBeginndatumFuerLos.getTime());
                    cTemp.set(Calendar.DAY_OF_MONTH, cTemp.get(Calendar.DAY_OF_MONTH) + laufzeit);
                    losDto.setTProduktionsende(new java.sql.Date(cTemp.getTime().getTime()));
                    context.getBusinessObject(FertigungFac.class).createLos(losDto, theClientDto);
                } catch (RemoteException ex1) {
                    throwEJBExceptionLPRespectOld(ex1);
                }

                iAnzahlAngelegterLose++;
            }
            // }
            // catch (FinderException ex) {
            // throw new EJBExceptionLP(EJBExceptionLP.FEHLER, ex);
            // }

        }

    }

    return iAnzahlAngelegterLose;
}

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

@TransactionAttribute(TransactionAttributeType.NEVER)
public ArrayList<LosAusAuftragDto> vorschlagMitUnterlosenAusAuftrag(Integer auftragIId,
        TheClientDto theClientDto) {/* w  w w  .  j a  v  a2 s.  c o m*/

    ArrayList<LosAusAuftragDto> losDtos = new ArrayList<LosAusAuftragDto>();

    try {

        ParametermandantDto parameterVorlaufzeit = getParameterFac().getMandantparameter(
                theClientDto.getSMandantenwaehrung(), ParameterFac.KATEGORIE_FERTIGUNG,
                ParameterFac.PARAMETER_DEFAULT_VORLAUFZEIT_INTERNEBESTELLUNG);
        int iVorlaufzeit = (Integer) parameterVorlaufzeit.getCWertAsObject();

        Integer stdFertigungsgruppeIId = null;
        FertigungsgruppeDto[] fertigungsgruppeDtos = getStuecklisteFac()
                .fertigungsgruppeFindByMandantCNr(theClientDto.getMandant(), theClientDto);

        if (fertigungsgruppeDtos.length > 0) {
            stdFertigungsgruppeIId = fertigungsgruppeDtos[0].getIId();
        }

        AuftragDto auftragDto = getAuftragFac().auftragFindByPrimaryKey(auftragIId);
        int iLieferdauerKunde = getKundeFac()
                .kundeFindByPrimaryKey(auftragDto.getKundeIIdAuftragsadresse(), theClientDto).getILieferdauer();

        if (auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_ANGELEGT)
                || auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_OFFEN)
                || auftragDto.getAuftragstatusCNr().equals(LocaleFac.STATUS_TEILERLEDIGT)) {
            AuftragpositionDto[] dtos = getAuftragpositionFac().auftragpositionFindByAuftrag(auftragIId);
            for (int i = 0; i < dtos.length; i++) {
                ArrayList<LosAusAuftragDto> losDtosPosition = new ArrayList<LosAusAuftragDto>();
                if (dtos[i].getPositionsartCNr().equals(AuftragServiceFac.AUFTRAGPOSITIONART_HANDEINGABE)) {

                    Timestamp tAuftragsliefertermin = dtos[i].getTUebersteuerbarerLiefertermin();
                    if (tAuftragsliefertermin == null) {
                        tAuftragsliefertermin = auftragDto.getDLiefertermin();
                    }

                    Timestamp tEnde = Helper.addiereTageZuTimestamp(tAuftragsliefertermin, -iLieferdauerKunde);

                    Timestamp tBeginn = Helper.addiereTageZuTimestamp(tEnde, -iVorlaufzeit);

                    LosAusAuftragDto laDto = new LosAusAuftragDto();
                    if (tBeginn.before(Helper.cutTimestamp(new Timestamp(System.currentTimeMillis())))) {
                        laDto.setBDatumVerschoben(true);
                        tBeginn = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));
                        tEnde = Helper.addiereTageZuTimestamp(tBeginn, iVorlaufzeit);
                    }

                    LosDto losDto = new LosDto();

                    losDto.setAuftragIId(auftragIId);
                    losDto.setAuftragpositionIId(dtos[i].getIId());

                    losDto.setTProduktionsbeginn(new java.sql.Date(tBeginn.getTime()));
                    losDto.setTProduktionsende(new java.sql.Date(tEnde.getTime()));
                    losDto.setLagerIIdZiel(getLagerFac().getHauptlagerDesMandanten(theClientDto).getIId());
                    losDto.setFertigungsgruppeIId(stdFertigungsgruppeIId);
                    losDto.setNLosgroesse(dtos[i].getNMenge());
                    losDto.setKostenstelleIId(auftragDto.getKostenstelleIId());
                    losDto.setCProjekt(dtos[i].getCBez());

                    laDto.setLosDto(losDto);

                    laDto.setAuftragpositionDto(dtos[i]);

                    laDto.setAuftragspositionsnummer(
                            getAuftragpositionFac().getPositionNummer(dtos[i].getIId()));

                    losDtos.add(laDto);

                } else {

                    // SP1107 Setartikelkopf ignorieren
                    Session session = null;
                    SessionFactory factory = FLRSessionFactory.getFactory();
                    session = factory.openSession();
                    Criteria crit = session.createCriteria(FLRAuftragposition.class);
                    crit.add(Restrictions.eq("position_i_id_artikelset", dtos[i].getIId()));

                    int iZeilen = crit.list().size();
                    session.close();
                    if (iZeilen > 0) {
                        continue;
                    }

                    StuecklisteDto stuecklisteDto = getStuecklisteFac()
                            .stuecklisteFindByMandantCNrArtikelIIdOhneExc(dtos[i].getArtikelIId(),
                                    theClientDto);
                    if (stuecklisteDto != null) {
                        if (dtos[i].getNMenge() != null && dtos[i].getNMenge().doubleValue() > 0) {

                            Timestamp tAuftragsliefertermin = dtos[i].getTUebersteuerbarerLiefertermin();
                            if (tAuftragsliefertermin == null) {
                                tAuftragsliefertermin = auftragDto.getDLiefertermin();
                            }

                            Timestamp tEnde = Helper.addiereTageZuTimestamp(tAuftragsliefertermin,
                                    -iLieferdauerKunde);

                            Timestamp tBeginn = tEnde;

                            if (stuecklisteDto.getNDefaultdurchlaufzeit() != null) {
                                tBeginn = Helper.addiereTageZuTimestamp(tEnde,
                                        -stuecklisteDto.getNDefaultdurchlaufzeit().intValue());
                            }
                            LosAusAuftragDto laDto = new LosAusAuftragDto();

                            LosDto losDto = new LosDto();

                            losDto.setAuftragIId(auftragIId);
                            losDto.setAuftragpositionIId(dtos[i].getIId());

                            losDto.setTProduktionsbeginn(new java.sql.Date(tBeginn.getTime()));
                            losDto.setTProduktionsende(new java.sql.Date(tEnde.getTime()));
                            losDto.setStuecklisteIId(stuecklisteDto.getIId());
                            losDto.setLagerIIdZiel(stuecklisteDto.getLagerIIdZiellager());
                            losDto.setCProjekt(auftragDto.getCBezProjektbezeichnung());
                            losDto.setFertigungsgruppeIId(stuecklisteDto.getFertigungsgruppeIId());
                            losDto.setNLosgroesse(dtos[i].getNMenge());
                            losDto.setKostenstelleIId(auftragDto.getKostenstelleIId());

                            laDto.setLosDto(losDto);

                            laDto.setAuftragpositionDto(dtos[i]);

                            laDto.setAuftragspositionsnummer(
                                    getAuftragpositionFac().getPositionNummer(dtos[i].getIId()));

                            laDto.setFehlmengen(getFehlmengeFac().getAnzahlFehlmengeEinesArtikels(
                                    stuecklisteDto.getArtikelIId(), theClientDto));

                            ArtikelreservierungDto eigeneReservierungDto = getReservierungFac()
                                    .artikelreservierungFindByBelegartCNrBelegartPositionIIdOhneExc(
                                            LocaleFac.BELEGART_AUFTRAG, dtos[i].getIId());

                            BigDecimal reservierungen = getReservierungFac()
                                    .getAnzahlReservierungen(stuecklisteDto.getArtikelIId(), theClientDto);

                            if (eigeneReservierungDto != null && eigeneReservierungDto.getNMenge() != null) {
                                if (reservierungen.subtract(eigeneReservierungDto.getNMenge())
                                        .doubleValue() < 0) {
                                    reservierungen = new BigDecimal(0);
                                } else {
                                    reservierungen = reservierungen.subtract(eigeneReservierungDto.getNMenge());
                                }
                            }

                            laDto.setReservierungen(reservierungen);

                            BigDecimal lagerstand = new BigDecimal(0);
                            LagerDto[] allelaegerDtos = getLagerFac()
                                    .lagerFindByMandantCNr(theClientDto.getMandant());

                            for (int j = 0; j < allelaegerDtos.length; j++) {
                                if (Helper.short2boolean(allelaegerDtos[j].getBInternebestellung())) {
                                    lagerstand = lagerstand
                                            .add(getLagerFac().getLagerstand(stuecklisteDto.getArtikelIId(),
                                                    allelaegerDtos[j].getIId(), theClientDto));
                                }

                            }

                            laDto.setLagerstand(lagerstand);
                            laDto.setOffeneFertigungsmenge(getFertigungFac()
                                    .getAnzahlInFertigung(stuecklisteDto.getArtikelIId(), theClientDto));

                            losDtosPosition.add(laDto);

                            ArrayList<?> stuecklisteAufegloest = getStuecklisteFac()
                                    .getStrukturDatenEinerStueckliste(stuecklisteDto.getIId(), theClientDto,
                                            StuecklisteReportFac.REPORT_STUECKLISTE_OPTION_SORTIERUNG_ARTIKELNR,
                                            0, null, false, true, dtos[i].getNMenge(), null, true);

                            for (int j = 0; j < stuecklisteAufegloest.size(); j++) {
                                StuecklisteMitStrukturDto strukt = (StuecklisteMitStrukturDto) stuecklisteAufegloest
                                        .get(j);

                                if (strukt.getStuecklistepositionDto() != null
                                        && strukt.getStuecklistepositionDto().getArtikelIId() != null) {
                                    losDtosPosition = holeAlleMoeglichenUnterloseEinerStueckliste(
                                            strukt.getStuecklistepositionDto().getArtikelIId(),
                                            strukt.getStuecklistepositionDto().getNZielmenge(), iVorlaufzeit,
                                            tBeginn, losDtosPosition, auftragDto, dtos[i].getNMenge(),
                                            theClientDto);

                                }

                            }

                            // Wenn Termin vor Heute, dann aauf nach Heute
                            // verschieben
                            java.sql.Date fruehesterProduktionsbeginnVorHeute = Helper
                                    .cutDate(new java.sql.Date(System.currentTimeMillis()));

                            for (int k = 0; k < losDtosPosition.size(); k++) {

                                if (losDtosPosition.get(k).getLosDto().getTProduktionsbeginn()
                                        .before(fruehesterProduktionsbeginnVorHeute)) {
                                    fruehesterProduktionsbeginnVorHeute = losDtosPosition.get(k).getLosDto()
                                            .getTProduktionsbeginn();
                                }

                            }

                            int iDiffTage = Helper.getDifferenzInTagen(fruehesterProduktionsbeginnVorHeute,
                                    new java.sql.Date(System.currentTimeMillis()));
                            if (iDiffTage > 0) {

                                for (int k = 0; k < losDtosPosition.size(); k++) {

                                    losDtosPosition.get(k).getLosDto()
                                            .setTProduktionsbeginn(Helper.addiereTageZuDatum(
                                                    losDtosPosition.get(k).getLosDto().getTProduktionsbeginn(),
                                                    iDiffTage));
                                    losDtosPosition.get(k).getLosDto()
                                            .setTProduktionsende(Helper.addiereTageZuDatum(
                                                    losDtosPosition.get(k).getLosDto().getTProduktionsende(),
                                                    iDiffTage));
                                    losDtosPosition.get(k).setBDatumVerschoben(true);

                                }
                            }

                            for (int k = 0; k < losDtosPosition.size(); k++) {
                                losDtos.add(losDtosPosition.get(k));
                            }
                        }
                    }
                }
            }
        }
    } catch (RemoteException e) {
        throwEJBExceptionLPRespectOld(e);
    }
    return losDtos;
}

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());
                }//  w w w.  j av  a 2 s.com

            }

        } 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 };
}

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;
        }/*  w  w w .j av  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;
            }
        }

    }

    // 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;
        }//w w  w .j av  a  2s  .  c  om
    }

    // 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;
}