public static int procesProduction(
     MProduction production, Timestamp movementDate, boolean mustBeStocked) {
   ProcessInfo pi = MWorkflow.runDocumentActionWorkflow(production, "CO");
   if (pi.isError()) {
     throw new RuntimeException(pi.getSummary());
   } else {
     if (production.isUseProductionPlan()) {
       Query planQuery =
           new Query(
               Env.getCtx(),
               I_M_ProductionPlan.Table_Name,
               "M_ProductionPlan.M_Production_ID=?",
               production.get_TrxName());
       List<MProductionPlan> plans =
           planQuery.setParameters(production.getM_Production_ID()).list();
       int linesCount = 0;
       for (MProductionPlan plan : plans) {
         MProductionLine[] lines = plan.getLines();
         linesCount += lines.length;
       }
       return linesCount;
     } else {
       return production.getLines().length;
     }
   }
 }
Esempio n. 2
0
 /**
  * ************************************************************************ Start Workflow.
  *
  * @param AD_Workflow_ID workflow
  * @return true if started
  */
 private boolean startWorkflow(int AD_Workflow_ID) {
   log.fine(AD_Workflow_ID + " - " + m_pi);
   boolean started = false;
   if (DB.isRemoteProcess()) {
     log.info("trying to running on the server");
     Server server = CConnection.get().getServer();
     try {
       if (server != null) { // 	See ServerBean
         log.info("running on the server");
         m_pi = server.workflow(m_wscctx, m_pi, AD_Workflow_ID);
         log.finest("server => " + m_pi);
         started = true;
       }
     } catch (Exception ex) {
       log.log(Level.SEVERE, "AppsServer error", ex);
       started = false;
     }
   }
   //	Run locally
   if (!started && !m_IsServerProcess) {
     log.info("running locally");
     MWorkflow wf = MWorkflow.get(m_wscctx, AD_Workflow_ID);
     MWFProcess wfProcess = null;
     if (m_pi.isBatch()) wfProcess = wf.start(m_pi); // 	may return null
     else wfProcess = wf.startWait(m_pi); // 	may return null
     started = wfProcess != null;
   }
   return started;
 } //  startWorkflow
Esempio n. 3
0
 /**
  * ************************************************************************ Start Database Process
  *
  * @param ProcedureName PL/SQL procedure name
  * @return true if success
  */
 private boolean startDBProcess(String ProcedureName) {
   //  execute on this thread/connection
   log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")");
   String sql = "{call " + ProcedureName + "(?)}";
   try {
     CallableStatement cstmt = DB.prepareCall(sql, ResultSet.CONCUR_UPDATABLE, null); // 	ro??
     cstmt.setInt(1, m_pi.getAD_PInstance_ID());
     cstmt.executeUpdate();
     cstmt.close();
   } catch (Exception e) {
     log.log(Level.SEVERE, sql, e);
     m_pi.setSummary(Msg.getMsg(m_wscctx, "ProcessRunError") + " " + e.getLocalizedMessage());
     m_pi.setError(true);
     return false;
   }
   //	log.fine(Log.l4_Data, "ProcessCtl.startProcess - done");
   return true;
 } //  startDBProcess
Esempio n. 4
0
 /**
  * ************************************************************************ Start Java Process
  * Class. instanciate the class implementing the interface ProcessCall. The class can be a
  * Server/Client class (when in Package org compiere.process or org.compiere.model) or a client
  * only class (e.g. in org.compiere.report)
  *
  * @return true if success
  */
 private boolean startProcess() {
   log.fine(m_pi.toString());
   boolean started = false;
   if (DB.isRemoteProcess()) {
     Server server = CConnection.get().getServer();
     try {
       if (server != null) { // 	See ServerBean
         m_pi = server.process(m_wscctx, m_pi);
         log.finest("server => " + m_pi);
         started = true;
       }
     } catch (UndeclaredThrowableException ex) {
       Throwable cause = ex.getCause();
       if (cause != null) {
         if (cause instanceof InvalidClassException)
           log.log(
               Level.SEVERE, "Version Server <> Client: " + cause.toString() + " - " + m_pi, ex);
         else
           log.log(Level.SEVERE, "AppsServer error(1b): " + cause.toString() + " - " + m_pi, ex);
       } else log.log(Level.SEVERE, " AppsServer error(1) - " + m_pi, ex);
       started = false;
     } catch (Exception ex) {
       Throwable cause = ex.getCause();
       if (cause == null) cause = ex;
       log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause);
       started = false;
     }
   }
   //	Run locally
   if (!started && !m_IsServerProcess) {
     ProcessCall myObject = null;
     try {
       Class myClass = Class.forName(m_pi.getClassName());
       myObject = (ProcessCall) myClass.newInstance();
       if (myObject == null) m_pi.setSummary("No Instance for " + m_pi.getClassName(), true);
       else myObject.startProcess(m_wscctx, m_pi, m_trx);
       if (m_trx != null) {
         m_trx.commit();
         m_trx.close();
       }
     } catch (Exception e) {
       if (m_trx != null) {
         m_trx.rollback();
         m_trx.close();
       }
       m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true);
       log.log(Level.SEVERE, m_pi.getClassName(), e);
     }
   }
   return !m_pi.isError();
 } //  startProcess
Esempio n. 5
0
  public IPrintingService findPrintingService(final ProcessInfo pi) {
    final Properties ctx = Env.getCtx();
    final int AD_Client_ID = Env.getAD_Client_ID(ctx);
    final int AD_Org_ID = Env.getAD_Org_ID(ctx);
    final int AD_Role_ID = Env.getAD_Role_ID(ctx);
    final int AD_User_ID = Env.getAD_User_ID(ctx);
    final int AD_Process_ID = pi.getAD_Process_ID();
    final int C_DocType_ID =
        Services.get(IDocActionBL.class).getC_DocType_ID(ctx, pi.getTable_ID(), pi.getRecord_ID());
    final String printerType = null;

    return findPrintingService0(
        ctx,
        AD_Client_ID,
        AD_Org_ID,
        AD_Role_ID,
        AD_User_ID,
        C_DocType_ID,
        AD_Process_ID,
        printerType);
  }
Esempio n. 6
0
  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    if (Check.isEmpty(System.getProperty("PropertyFile"), true)) {
      throw new AdempiereException("Please set the PropertyFile");
    }

    final String outputFolder = System.getProperty("OutputFolder");
    if (Check.isEmpty(outputFolder, true)) {
      throw new AdempiereException("Please set the OutputFolder");
    }

    final String entityType = System.getProperty("EntityType");
    if (Check.isEmpty(entityType, true)) {
      throw new AdempiereException("Please set the EntityType");
    }

    CLogMgt.initialize(true); // just to make sure we are using the client side settings

    AdempiereToolsHelper.getInstance().startupMinimal();

    final ProcessInfo pi = new ProcessInfo("GenerateCanonicalXSD", -1, 0, 0);
    pi.setParameter(
        new ProcessInfoParameter[] {
          new ProcessInfoParameter("Target_Directory", outputFolder, null, null, null),
          new ProcessInfoParameter("EntityType", entityType, null, null, null),
        });
    pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx()));

    final GenerateCanonicalXSD process = new GenerateCanonicalXSD();
    process.p_FilterBy_AD_Client_ID = false;

    CLogMgt.setLevel(Level.INFO);
    process.startProcess(Env.getCtx(), pi, ITrx.TRX_None);

    //
    // CanonicalXSDGenerator.validateXML(new File("d:/tmp/C_BPartner.xml"), proc.getSchemaFile());
    // CanonicalXSDGenerator.validateXML(new File("d:/tmp/clientPartners.xml"),
    // proc.getSchemaFile());
  }
Esempio n. 7
0
  /**
   * Async Process - Do it all. <code>
   * - Get Instance ID
   * - Get Parameters
   * - execute (lock - start process - unlock)
   *  </code> Creates a ProcessCtl instance, which calls lockUI and unlockUI if parent is a
   * ASyncProcess <br>
   * Called from ProcessCtl.startProcess, ProcessDialog.actionPerformed, APanel.cmd_print,
   * APanel.actionButton, VPaySelect.cmd_generate
   *
   * @param parent ASyncProcess & Container
   * @param WindowNo window no
   * @param pi ProcessInfo process info
   * @param trx Transaction
   * @return worker started ProcessCtl instance or null for workflow
   */
  public static WProcessCtl process(
      Object parent, int WindowNo, ProcessInfo pi, Trx trx, HttpServletRequest request) {
    log.fine("WindowNo=" + WindowNo + " - " + pi);
    WebSessionCtx wsc = WebSessionCtx.get(request);
    MPInstance instance = new MPInstance(wsc.ctx, pi.getAD_Process_ID(), pi.getRecord_ID());

    if (!instance.save()) {
      pi.setSummary(Msg.getMsg(wsc.ctx, "ProcessNoInstance"));
      pi.setError(true);
      return null;
    }
    pi.setAD_PInstance_ID(instance.getAD_PInstance_ID());

    //	Get Parameters (Dialog)
    /**
     * ProcessParameter para = new ProcessParameter (Env.getFrame((Container)parent), WindowNo, pi);
     * if (para.initDialog()) { para.setVisible(true); if (!para.isOK()) { pi.setSummary
     * (Msg.getMsg(Env.getCtx(), "ProcessCancelled")); pi.setError (true); return null; } }
     */
    //	execute
    WProcessCtl worker = new WProcessCtl(parent, pi, trx, wsc.ctx);
    worker.start(); // 	MUST be start!
    return worker;
  } //	execute
Esempio n. 8
0
  /**
   * Test
   *
   * @param args ignored
   */
  public static void main(String[] args) {

    Adempiere.startupEnvironment(false);
    CLogMgt.setLevel(Level.CONFIG);

    ColumnEncryption columnEncryption = new ColumnEncryption();

    int processId = 328; // AD_ColumnEncryption
    int columnId = 417; // AD_User - Password
    Env.setContext(Env.getCtx(), I_AD_Column.COLUMNNAME_AD_Column_ID, columnId);

    MPInstance instance;
    MPInstancePara instanceParameters;

    instance = new MPInstance(Env.getCtx(), processId, columnId);
    instance.saveEx();

    instanceParameters = new MPInstancePara(instance, 10);
    instanceParameters.setParameter(I_AD_Column.COLUMNNAME_IsEncrypted, true);
    instanceParameters.saveEx();

    instanceParameters = new MPInstancePara(instance, 20);
    instanceParameters.setParameter("ChangeSetting", true);
    instanceParameters.saveEx();

    ProcessInfo pi = new ProcessInfo("AD_ColumnEncryption", processId);
    pi.setRecord_ID(instance.getRecord_ID());
    pi.setAD_PInstance_ID(instance.getAD_PInstance_ID());
    pi.setAD_Client_ID(0);
    pi.setAD_User_ID(100);

    columnEncryption.startProcess(Env.getCtx(), pi, null);

    /*List<MUser> users = new Query(Env.getCtx(), I_AD_User.Table_Name , "Password IS NOT NULL", null).list();
    for (MUser user : users)
    {
        user.setPassword(user.getPassword());
        user.saveEx();
    }*/

    processId = 53259; // Convert password to hashed

    pi = new ProcessInfo("AD_User_HashPassword", processId);
    pi.setAD_Client_ID(0);
    pi.setAD_User_ID(100);

    HashPasswords process = new HashPasswords();
    process.startProcess(Env.getCtx(), pi, null);
  }
  // add main method, preparing for nightly build
  public static void main(String[] args) {
    Adempiere.startupEnvironment(false);
    CLogMgt.setLevel(Level.FINE);
    s_log.info("Synchronize Terminology");
    s_log.info("-----------------------");
    ProcessInfo pi = new ProcessInfo("Synchronize Terminology", 172);
    pi.setAD_Client_ID(0);
    pi.setAD_User_ID(100);

    SynchronizeTerminology sc = new SynchronizeTerminology();
    sc.startProcess(Env.getCtx(), pi, null);

    System.out.println(
        "Process=" + pi.getTitle() + " Error=" + pi.isError() + " Summary=" + pi.getSummary());
  }
  /**
   * Main test
   *
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) {
    Adempiere.startupEnvironment(true);
    CLogMgt.setLevel(Level.INFO);

    Properties ctx = Env.getCtx();
    int AD_Process_ID = 53156; // HARDCODED

    MPInstance pinstance = new MPInstance(ctx, AD_Process_ID, -1);
    pinstance.saveEx();

    ProcessInfo pi = new ProcessInfo("", AD_Process_ID, 0, 0);
    pi.setAD_Client_ID(Env.getAD_Client_ID(ctx));
    pi.setAD_User_ID(Env.getAD_User_ID(ctx));
    pi.setAD_PInstance_ID(pinstance.getAD_PInstance_ID());
    //
    EnableNativeSequence proc = new EnableNativeSequence();
    proc.startProcess(ctx, pi, null);
    if (pi.isError()) {
      throw new AdempiereException(pi.getSummary());
    }
  }
  @Override
  protected String doIt() throws Exception {
    // Obtiene fecha actual del sistema
    calendario.getTime();

    // Si el día es el 1ero del mes le resto uno al mes y calculo la Pauta de Rebajas del mes
    // anterior
    if (calendario.get(Calendar.DAY_OF_MONTH) == 1) {
      calendario.add(Calendar.DAY_OF_MONTH, -1);
      fechaActual = calendario.getTime();
    }

    int month = 0;
    int year = 0;

    month = calendario.get(Calendar.MONTH) + 1;
    year = calendario.get(Calendar.YEAR);
    String fecha = "";

    if (month < 10) {
      fecha = "0" + month + "-" + year;
    } else {
      fecha = "" + month + "-" + year;
    }

    String SQLDel = "DELETE FROM XX_VMR_PatternOfDiscount";

    try {
      PreparedStatement pstmtDel = DB.prepareStatement(SQLDel, null);
      ResultSet rsDel = pstmtDel.executeQuery();
      rsDel.close();
      pstmtDel.close();

    } catch (Exception e) {
      log.log(Level.SEVERE, SQLDel, e);
      return "";
    }

    String SQL =
        "SELECT SUM(XX_INITIALINVENTORYQUANTITY) AS CANTINI, "
            + "SUM(XX_INITIALINVENTORYAMOUNT) AS MONTOINI, "
            + "(SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + "
            + "SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + SUM(XX_MOVEMENTQUANTITY) + "
            + "SUM(XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, (SUM(XX_INITIALINVENTORYAMOUNT) + "
            + "SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + "
            + "SUM(XX_MOVEMENTAMOUNT) + SUM(XX_AdjustmentsAmount)) AS MONTOFIN, "
            + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYQUANTITY) + "
            + "SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + "
            + "SUM(XX_MOVEMENTQUANTITY) + SUM(XX_ADJUSTMENTSQUANTITY))/2) AS CANTPROM, "
            + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYAMOUNT) + SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + "
            + "SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + SUM(XX_MOVEMENTAMOUNT) + "
            + "SUM(XX_AdjustmentsAmount))/2) AS MONTOPROM, M_Product_ID "
            + "FROM XX_VCN_Inventory "
            + "WHERE XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
            + " GROUP BY M_Product_ID";

    try {
      PreparedStatement pstmt = DB.prepareStatement(SQL, null);
      ResultSet rs = pstmt.executeQuery();

      while (rs.next()) { // System.out.println(rs.getInt(7));
        cantInventIni = rs.getInt(1);
        montoInventIni = rs.getBigDecimal(2);
        cantInventFin = rs.getInt(3);
        montoInventFin = rs.getBigDecimal(4);
        cantInventProm = rs.getBigDecimal(5);
        montoInventProm = rs.getBigDecimal(6);
        /*System.out.println(cantInventIni);
        System.out.println(montoInventIni);
        System.out.println(cantInventFin);
        System.out.println(montoInventFin);
        System.out.println(cantInventProm);
        System.out.println(montoInventProm);*/

        if ((rs.getInt(7) != 0)
            && (cantInventFin != 0)
            && (montoInventFin != new BigDecimal(0))
            && (cantInventProm != new BigDecimal(0))
            && (montoInventProm != new BigDecimal(0))) {
          String SQL2 =
              "SELECT SUM(XX_SALESQUANTITY), SUM(XX_SALESAMOUNT), M_Product_ID "
                  + "FROM XX_VCN_Inventory "
                  + "WHERE M_Product_ID="
                  + rs.getInt(7)
                  + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                  + " GROUP BY M_Product_ID";

          try {
            PreparedStatement pstmt2 = DB.prepareStatement(SQL2, null);
            ResultSet rs2 = pstmt2.executeQuery();

            while (rs2.next()) {
              cantVentaMes = rs2.getInt(1);
              montoVentaMes = rs2.getBigDecimal(2);
              /*System.out.println(cantVentaMes);
              System.out.println(montoVentaMes);*/

              if ((cantVentaMes != 0) && (montoVentaMes != new BigDecimal(0))) {
                cantRotacion =
                    new BigDecimal(cantVentaMes * 12)
                        .divide(cantInventProm, 2, RoundingMode.HALF_UP);

                MProduct producto = new MProduct(Env.getCtx(), rs.getInt(7), null);

                String SQL3 =
                    "SELECT SUM(XX_INITIALINVENTORYQUANTITY) AS CANTINI, "
                        + "SUM(XX_INITIALINVENTORYAMOUNT) AS MONTOINI, "
                        + "(SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + "
                        + "SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + SUM(XX_MOVEMENTQUANTITY) + "
                        + "SUM(XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, (SUM(XX_INITIALINVENTORYAMOUNT) + "
                        + "SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + "
                        + "SUM(XX_MOVEMENTAMOUNT) + SUM(XX_AdjustmentsAmount)) AS MONTOFIN, "
                        + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYQUANTITY) + "
                        + "SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + "
                        + "SUM(XX_MOVEMENTQUANTITY) + SUM(XX_ADJUSTMENTSQUANTITY))/2) AS CANTPROM, "
                        + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYAMOUNT) + SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + "
                        + "SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + SUM(XX_MOVEMENTAMOUNT) + "
                        + "SUM(XX_AdjustmentsAmount))/2) AS MONTOPROM, XX_VMR_Department_ID "
                        + "FROM XX_VCN_Inventory "
                        + "WHERE XX_VMR_Department_ID="
                        + producto.getXX_VMR_Department_ID()
                        + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                        + " GROUP BY XX_VMR_Department_ID";

                try {
                  PreparedStatement pstmt3 = DB.prepareStatement(SQL3, null);
                  ResultSet rs3 = pstmt3.executeQuery();

                  while (rs3.next()) {
                    cantInvIniDep = rs3.getInt(1);
                    montoInvIniDep = rs3.getBigDecimal(2);
                    cantInvFinDep = rs.getInt(3);
                    montoInvFinDep = rs.getBigDecimal(4);
                    cantInvPromDep = rs.getBigDecimal(5);
                    montoInvPromDep = rs.getBigDecimal(6);
                    /*System.out.println(cantInvIniDep);
                    System.out.println(montoInvIniDep);
                    System.out.println(cantInvFinDep);
                    System.out.println(montoInvFinDep);
                    System.out.println(cantInvPromDep);
                    System.out.println(montoInvPromDep);*/

                    if ((cantInvFinDep != 0)
                        && (montoInvFinDep != new BigDecimal(0))
                        && (cantInvPromDep != new BigDecimal(0))
                        && (montoInvPromDep != new BigDecimal(0))) {
                      String SQL4 =
                          "SELECT SUM(XX_SALESQUANTITY), SUM(XX_SALESAMOUNT), XX_VMR_Department_ID "
                              + "FROM XX_VCN_Inventory "
                              + "WHERE XX_VMR_Department_ID="
                              + producto.getXX_VMR_Department_ID()
                              + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                              + " GROUP BY XX_VMR_Department_ID";

                      try {
                        PreparedStatement pstmt4 = DB.prepareStatement(SQL4, null);
                        ResultSet rs4 = pstmt4.executeQuery();

                        while (rs4.next()) {
                          cantVentaMesDep = rs4.getInt(1);
                          montoVentaMesDep = rs4.getBigDecimal(2);
                          /*System.out.println(cantVentaMesDep);
                          System.out.println(montoVentaMesDep);*/

                          if ((cantVentaMesDep != 0) && (montoVentaMesDep != new BigDecimal(0))) {
                            cantRotaDep =
                                new BigDecimal(cantVentaMesDep * 12)
                                    .divide(cantInvPromDep, 2, RoundingMode.HALF_UP);
                            // System.out.println(cantRotacion+"rota"+cantRotaDep+"dsssss"+cantRotacion.compareTo(cantRotaDep));
                            if (cantRotacion.compareTo(cantRotaDep) < 0) {
                              int cant = 0;
                              int consecutive = 0;
                              BigDecimal monto = new BigDecimal(0);
                              int patternDiscountID = 0;

                              String SQL5 =
                                  "SELECT (SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + "
                                      + "SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + SUM(XX_MOVEMENTQUANTITY) + "
                                      + "SUM(XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, M_Product_ID, "
                                      + "XX_VMR_Category_ID, XX_CONSECUTIVEPRICE, M_AttributeSetInstance_ID "
                                      + "FROM XX_VCN_Inventory "
                                      + "WHERE M_Product_ID="
                                      + rs.getInt(7)
                                      + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                                      + "GROUP BY M_Product_ID, XX_VMR_Category_ID, XX_CONSECUTIVEPRICE, M_AttributeSetInstance_ID";

                              try {
                                PreparedStatement pstmt5 = DB.prepareStatement(SQL5, null);
                                ResultSet rs5 = pstmt5.executeQuery();

                                while (rs5.next()) {
                                  cant = rs5.getInt(1);
                                  consecutive = rs5.getInt(4);

                                  if ((cant != 0) && (consecutive != 0)) {
                                    String SQL6 =
                                        "SELECT DISTINCT(i.XX_ConsecutivePrice), i.M_Product_ID, "
                                            + "i.M_AttributeSetInstance_ID, c.Created, c.XX_SalePrice, "
                                            + "m.XX_VMR_TypeInventory_ID, r.XX_Range1, r.XX_Range2, r.XX_Range3 "
                                            + "FROM XX_VCN_Inventory i, XX_VMR_PriceConsecutive c, M_Product m, XX_VMR_RangeDaysPromote r "
                                            + "WHERE i.M_Product_ID="
                                            + rs.getInt(7)
                                            + " AND i.M_Product_ID=c.M_Product_ID "
                                            + "AND i.M_Product_ID=m.M_Product_ID "
                                            + "AND i.M_AttributeSetInstance_ID="
                                            + rs5.getInt(5)
                                            + " AND i.M_AttributeSetInstance_ID=c.M_AttributeSetInstance_ID "
                                            + "AND i.XX_ConsecutivePrice="
                                            + rs5.getInt(4)
                                            + " AND i.XX_VMR_Category_ID=r.XX_VMR_Category_ID "
                                            + "AND m.XX_VMR_TypeInventory_ID=r.XX_VMR_TypeInventory_ID "
                                            + "AND i.XX_INVENTORYMONTH='11' AND i.XX_INVENTORYYEAR='2009' "; // to_char(i.Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy')";

                                    try {
                                      PreparedStatement pstmt6 = DB.prepareStatement(SQL6, null);
                                      ResultSet rs6 = pstmt6.executeQuery();

                                      if (rs6.next()) {
                                        monto = rs6.getBigDecimal(5);
                                        long fechaInicial = rs6.getDate(4).getTime();
                                        long fechaFinal = fechaActual.getTime();
                                        long diferencia = fechaFinal - fechaInicial;
                                        double dias =
                                            Math.floor(diferencia / (1000 * 60 * 60 * 24));
                                        diasVida = (int) dias;
                                        /*System.out.println(rs6.getInt(7));
                                        System.out.println(rs6.getInt(8));
                                        System.out.println(rs6.getInt(9));*/
                                        patternDiscountID = getPatternOfDiscount(rs.getInt(7));

                                        if (patternDiscountID != 0) {
                                          // instancio pauta de rebaja con el id que devolvio
                                          patternDiscount =
                                              new X_XX_VMR_PatternOfDiscount(
                                                  Env.getCtx(), patternDiscountID, null);
                                        } else {
                                          // instancio pauta de rebaja nueva
                                          patternDiscount =
                                              new X_XX_VMR_PatternOfDiscount(Env.getCtx(), 0, null);
                                        }

                                        if ((diasVida >= rs6.getInt(7))
                                            && (diasVida < rs6.getInt(8))) {
                                          patternDiscount.setM_Product_ID(producto.get_ID());
                                          patternDiscount.setXX_QuantityPromotion20(
                                              patternDiscount.getXX_QuantityPromotion20() + cant);
                                          patternDiscount.setXX_AmountPromotion20(
                                              patternDiscount
                                                  .getXX_AmountPromotion20()
                                                  .add(monto.multiply(new BigDecimal(cant))));
                                          patternDiscount.save();
                                        } else if ((diasVida >= rs6.getInt(8))
                                            && ((rs6.getInt(9) == 0)
                                                || (diasVida < rs6.getInt(9)))) {
                                          patternDiscount.setM_Product_ID(producto.get_ID());
                                          patternDiscount.setXX_QuantityPromotion30(
                                              patternDiscount.getXX_QuantityPromotion30() + cant);
                                          patternDiscount.setXX_AmountPromotion30(
                                              patternDiscount
                                                  .getXX_AmountPromotion30()
                                                  .add(monto.multiply(new BigDecimal(cant))));
                                          patternDiscount.save();
                                        } else if ((diasVida >= rs6.getInt(9))
                                            && (rs6.getInt(9) != 0)) {
                                          patternDiscount.setM_Product_ID(producto.get_ID());
                                          patternDiscount.setXX_QuantityPromotion50(
                                              patternDiscount.getXX_QuantityPromotion50() + cant);
                                          patternDiscount.setXX_AmountPromotion50(
                                              patternDiscount
                                                  .getXX_AmountPromotion50()
                                                  .add(monto.multiply(new BigDecimal(cant))));
                                          patternDiscount.save();
                                        }

                                        if (patternDiscount.get_ID() != 0) {
                                          quantity =
                                              patternDiscount.getXX_QuantityPromotion20()
                                                  + patternDiscount.getXX_QuantityPromotion30()
                                                  + patternDiscount.getXX_QuantityPromotion50();
                                          amount =
                                              patternDiscount
                                                  .getXX_AmountPromotion20()
                                                  .add(patternDiscount.getXX_AmountPromotion30())
                                                  .add(patternDiscount.getXX_AmountPromotion50());

                                          patternDiscount.setXX_FinalInventoryQuantity(quantity);
                                          patternDiscount.setXX_FinalInventoryAmount(amount);
                                          patternDiscount.setXX_DATE(fecha);
                                          patternDiscount.save();
                                        }
                                      }
                                      rs6.close();
                                      pstmt6.close();
                                    } catch (SQLException e) {
                                      e.printStackTrace();
                                    }
                                  }
                                }
                                rs5.close();
                                pstmt5.close();
                              } catch (SQLException e) {
                                e.printStackTrace();
                              }
                            }
                          } else {
                            int cant = 0;
                            int consecutive = 0;
                            BigDecimal monto = new BigDecimal(0);
                            int patternDiscountID = 0;

                            String SQL5 =
                                "SELECT (SUM(i.XX_INITIALINVENTORYQUANTITY) + SUM(i.XX_PREVIOUSADJUSTMENTSQUANTITY) + "
                                    + "SUM(i.XX_SHOPPINGQUANTITY) + SUM(i.XX_SALESQUANTITY) + SUM(i.XX_MOVEMENTQUANTITY) + "
                                    + "SUM(i.XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, i.M_Product_ID, "
                                    + "i.XX_VMR_Category_ID, i.XX_CONSECUTIVEPRICE, i.M_AttributeSetInstance_ID "
                                    + "FROM XX_VCN_Inventory i, M_Product m "
                                    + "WHERE i.M_Product_ID="
                                    + rs.getInt(7)
                                    + " AND m.M_Product_ID=i.M_Product_ID "
                                    + "AND m.XX_VMR_TypeInventory_ID="
                                    + typeInv
                                    + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                                    + "GROUP BY M_Product_ID, XX_VMR_Category_ID, XX_CONSECUTIVEPRICE, M_AttributeSetInstance_ID";

                            try {
                              PreparedStatement pstmt5 = DB.prepareStatement(SQL5, null);
                              ResultSet rs5 = pstmt5.executeQuery();

                              while (rs5.next()) {
                                cant = rs5.getInt(1);
                                consecutive = rs5.getInt(4);

                                if ((cant != 0) && (consecutive != 0)) {
                                  String SQL6 =
                                      "SELECT DISTINCT(i.XX_ConsecutivePrice), i.M_Product_ID, "
                                          + "i.M_AttributeSetInstance_ID, c.Created, c.XX_SalePrice, "
                                          + "m.XX_VMR_TypeInventory_ID, r.XX_Range1, r.XX_Range2, r.XX_Range3 "
                                          + "FROM XX_VCN_Inventory i, XX_VMR_PriceConsecutive c, M_Product m, XX_VMR_RangeDaysPromote r "
                                          + "WHERE i.M_Product_ID="
                                          + rs.getInt(7)
                                          + " AND i.M_Product_ID=c.M_Product_ID "
                                          + "AND i.M_Product_ID=m.M_Product_ID "
                                          + "AND i.M_AttributeSetInstance_ID="
                                          + rs5.getInt(5)
                                          + " AND i.M_AttributeSetInstance_ID=c.M_AttributeSetInstance_ID "
                                          + "AND i.XX_ConsecutivePrice="
                                          + rs5.getInt(4)
                                          + " AND i.XX_VMR_Category_ID=r.XX_VMR_Category_ID "
                                          + "AND m.XX_VMR_TypeInventory_ID=r.XX_VMR_TypeInventory_ID "
                                          + "AND i.XX_INVENTORYMONTH='11' AND i.XX_INVENTORYYEAR='2009' "; // to_char(i.Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy')";

                                  try {
                                    PreparedStatement pstmt6 = DB.prepareStatement(SQL6, null);
                                    ResultSet rs6 = pstmt6.executeQuery();

                                    if (rs6.next()) {
                                      monto = rs6.getBigDecimal(5);
                                      long fechaInicial = rs6.getDate(4).getTime();
                                      long fechaFinal = fechaActual.getTime();
                                      long diferencia = fechaFinal - fechaInicial;
                                      double dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));
                                      diasVida = (int) dias;

                                      patternDiscountID = getPatternOfDiscount(rs.getInt(7));

                                      if (patternDiscountID != 0) {
                                        // instancio pauta de rebaja con el id que devolvio
                                        patternDiscount =
                                            new X_XX_VMR_PatternOfDiscount(
                                                Env.getCtx(), patternDiscountID, null);
                                      } else {
                                        // instancio pauta de rebaja nueva;
                                        patternDiscount =
                                            new X_XX_VMR_PatternOfDiscount(Env.getCtx(), 0, null);
                                      }

                                      if (diasVida > rs6.getInt(9)) {
                                        patternDiscount.setM_Product_ID(producto.get_ID());
                                        patternDiscount.setXX_DATE(fecha);
                                        patternDiscount.setXX_QuantityPromotion50(cant);
                                        patternDiscount.setXX_AmountPromotion50(
                                            monto.multiply(new BigDecimal(cant)));

                                        if ((patternDiscount.getXX_QuantityPromotion20() != 0)
                                            || (patternDiscount.getXX_QuantityPromotion30() != 0)
                                            || (patternDiscount.getXX_QuantityPromotion50() != 0)) {
                                          quantity =
                                              patternDiscount.getXX_QuantityPromotion20()
                                                  + patternDiscount.getXX_QuantityPromotion30()
                                                  + patternDiscount.getXX_QuantityPromotion50();
                                          amount =
                                              patternDiscount
                                                  .getXX_AmountPromotion20()
                                                  .add(patternDiscount.getXX_AmountPromotion30())
                                                  .add(patternDiscount.getXX_AmountPromotion50());

                                          patternDiscount.setXX_FinalInventoryQuantity(quantity);
                                          patternDiscount.setXX_FinalInventoryAmount(amount);
                                        }
                                        patternDiscount.save();
                                      }
                                    }
                                    rs6.close();
                                    pstmt6.close();
                                  } catch (SQLException e) {
                                    e.printStackTrace();
                                  }
                                }
                              }
                              rs5.close();
                              pstmt5.close();
                            } catch (SQLException e) {
                              e.printStackTrace();
                            }
                          }
                        }
                        rs4.close();
                        pstmt4.close();
                      } catch (SQLException e) {
                        e.printStackTrace();
                      }
                    }
                  }
                  rs3.close();
                  pstmt3.close();
                } catch (SQLException e) {
                  e.printStackTrace();
                }
              }
            }
            rs2.close();
            pstmt2.close();
          } catch (SQLException e) {
            e.printStackTrace();
          }
        }
      }
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }

    if (getCountPatternOfDiscount() != 0) {
      // Abre la ventana de Pauta de Rebajas
      AWindow window_patternDiscount = new AWindow();
      Query query = Query.getEqualQuery("ISACTIVE", "Y");
      String wind = Env.getCtx().getContext("#XX_L_W_PATTERNOFDISCOUNT_ID");
      Integer win = Integer.parseInt(wind);
      window_patternDiscount.initWindow(win, query);
      AEnv.showCenterScreen(window_patternDiscount);

      // LLama al proceso de exportar la data de compiere al as/400
      MPInstance mpi =
          new MPInstance(
              Env.getCtx(),
              Env.getCtx().getContextAsInt("#XX_L_PROCESSPATTERNDISCOUNT_ID"),
              patternDiscount.get_ID());
      mpi.save();

      ProcessInfo pi =
          new ProcessInfo("", Env.getCtx().getContextAsInt("#XX_L_PROCESSPATTERNDISCOUNT_ID"));
      pi.setRecord_ID(mpi.getRecord_ID());
      pi.setAD_PInstance_ID(mpi.get_ID());
      pi.setAD_Process_ID(Env.getCtx().getContextAsInt("#XX_L_PROCESSPATTERNDISCOUNT_ID"));
      pi.setClassName("");
      pi.setTitle("");

      ProcessCtl pc = new ProcessCtl(null, pi, null);
      pc.start();

      return "";
    } else {
      return "No hay Pauta de Rebajas";
    }
  }
Esempio n. 12
0
  // @emmie custom
  public String generate(
      IStatusBar statusBar, KeyNamePair docTypeKNPair, int C_POS_ID, String docActionSelected)
        // @emmie custom
      {
    String info = "";
    String trxName = Trx.createTrxName("IVG");
    Trx trx = Trx.get(trxName, true); // trx needs to be committed too

    setSelectionActive(false); //  prevents from being called twice
    statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InvGenerateGen"));
    statusBar.setStatusDB(String.valueOf(getSelection().size()));

    //	Prepare Process
    int AD_Process_ID = 0;

    if (docTypeKNPair.getKey() == MRMA.Table_ID) {
      AD_Process_ID =
          PROCESS_C_INVOICE_GENERATERMA_MANUAL; // C_Invoice_GenerateRMA -
                                                // org.adempiere.process.InvoiceGenerateRMA
    } else {
      AD_Process_ID = PROCESS_C_INVOICE_GENERATE_MANUAL; // HARDCODED    C_InvoiceCreate
    }
    MPInstance instance = new MPInstance(Env.getCtx(), AD_Process_ID, 0);
    if (!instance.save()) {
      info = Msg.getMsg(Env.getCtx(), "ProcessNoInstance");
      return info;
    }

    // insert selection
    StringBuffer insert = new StringBuffer();
    insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
    int counter = 0;
    for (Integer selectedId : getSelection()) {
      counter++;
      if (counter > 1) insert.append(" UNION ");
      insert.append("SELECT ");
      insert.append(instance.getAD_PInstance_ID());
      insert.append(", ");
      insert.append(selectedId);
      insert.append(" FROM DUAL ");

      if (counter == 1000) {
        if (DB.executeUpdate(insert.toString(), trxName) < 0) {
          String msg = "No Invoices"; //  not translated!
          info = msg;
          log.config(msg);
          trx.rollback();
          return info;
        }
        insert = new StringBuffer();
        insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
        counter = 0;
      }
    }
    if (counter > 0) {
      if (DB.executeUpdate(insert.toString(), trxName) < 0) {
        String msg = "No Invoices"; //  not translated!
        info = msg;
        log.config(msg);
        trx.rollback();
        return info;
      }
    }

    ProcessInfo pi = new ProcessInfo("", AD_Process_ID);
    pi.setAD_PInstance_ID(instance.getAD_PInstance_ID());

    //	Add Parameters
    MPInstancePara para = new MPInstancePara(instance, 10);
    para.setParameter("Selection", "Y");
    if (!para.save()) {
      String msg = "No Selection Parameter added"; //  not translated
      info = msg;
      log.log(Level.SEVERE, msg);
      return info;
    }

    para = new MPInstancePara(instance, 20);
    para.setParameter("DocAction", docActionSelected);

    if (!para.save()) {
      String msg = "No DocAction Parameter added"; //  not translated
      info = msg;
      log.log(Level.SEVERE, msg);
      return info;
    }
    // @emmie custom
    para = new MPInstancePara(instance, 30);
    para.setParameter("C_POS_ID", C_POS_ID);

    if (!para.save()) {
      String msg = "No C_POS_ID Parameter added"; //  not translated
      info = msg;
      log.log(Level.SEVERE, msg);
      return info;
    }
    // @emmie custom

    setTrx(trx);
    setProcessInfo(pi);

    return info;
  } //	generateInvoices
Esempio n. 13
0
  /**
   * Execute Process Instance and Lock UI. Calls lockUI and unlockUI if parent is a ASyncProcess
   *
   * <pre>
   * 	- Get Process Information
   *      - Call Class
   * 	- Submit SQL Procedure
   * 	- Run SQL Procedure
   * </pre>
   */
  public void run() {
    log.fine("AD_PInstance_ID=" + m_pi.getAD_PInstance_ID() + ", Record_ID=" + m_pi.getRecord_ID());

    //  Lock
    // lock();
    //	try {System.out.println(">> sleeping ..");sleep(20000);System.out.println(".. sleeping <<");}
    // catch (Exception e) {}

    //	Get Process Information: Name, Procedure Name, ClassName, IsReport, IsDirectPrint
    String ProcedureName = "";
    int AD_ReportView_ID = 0;
    int AD_Workflow_ID = 0;
    boolean IsReport = false;
    boolean IsDirectPrint = false;
    //
    String sql =
        "SELECT p.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," //	1..4
            + " p.isReport,p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," //	5..8
            + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE,"
            + " p.IsServerProcess "
            + "FROM AD_Process p"
            + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) "
            + "WHERE p.IsActive='Y'"
            + " AND i.AD_PInstance_ID=?";
    if (!Env.isBaseLanguage(m_wscctx, "AD_Process"))
      sql =
          "SELECT t.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," //	1..4
              + " p.isReport, p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," //	5..8
              + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE,"
              + " p.IsServerProcess "
              + "FROM AD_Process p"
              + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) "
              + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID"
              + " AND t.AD_Language='"
              + Env.getAD_Language(m_wscctx)
              + "') "
              + "WHERE p.IsActive='Y'"
              + " AND i.AD_PInstance_ID=?";
    //
    try {
      PreparedStatement pstmt =
          DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null);
      pstmt.setInt(1, m_pi.getAD_PInstance_ID());
      ResultSet rs = pstmt.executeQuery();
      if (rs.next()) {
        m_pi.setTitle(rs.getString(1));
        if (m_waiting != null) m_waiting.setTitle(m_pi.getTitle());
        ProcedureName = rs.getString(2);
        m_pi.setClassName(rs.getString(3));
        m_pi.setAD_Process_ID(rs.getInt(4));
        //	Report
        if ("Y".equals(rs.getString(5))) {
          IsReport = true;
          if ("Y".equals(rs.getString(6)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW))
            IsDirectPrint = true;
        }
        AD_ReportView_ID = rs.getInt(7);
        AD_Workflow_ID = rs.getInt(8);
        //
        int estimate = rs.getInt(9);
        if (estimate != 0) {
          m_pi.setEstSeconds(estimate + 1); //  admin overhead
          if (m_waiting != null) m_waiting.setTimerEstimate(m_pi.getEstSeconds());
        }
        m_IsServerProcess = "Y".equals(rs.getString(10));
      } else log.log(Level.SEVERE, "No AD_PInstance_ID=" + m_pi.getAD_PInstance_ID());
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      m_pi.setSummary(
          Msg.getMsg(m_wscctx, "ProcessNoProcedure") + " " + e.getLocalizedMessage(), true);
      // unlock();
      log.log(Level.SEVERE, "run", e);
      return;
    }

    //  No PL/SQL Procedure
    if (ProcedureName == null) ProcedureName = "";

    /** ******************************************************************** Workflow */
    if (AD_Workflow_ID > 0) {
      startWorkflow(AD_Workflow_ID);
      // unlock();
      return;
    }

    /** ******************************************************************** Start Optional Class */
    if (m_pi.getClassName() != null) {
      //	Run Class
      if (!startProcess()) {
        // unlock();
        return;
      }

      //  No Optional SQL procedure ... done
      if (!IsReport && ProcedureName.length() == 0) {
        // unlock ();
        return;
      }
      //  No Optional Report ... done
      if (IsReport && AD_ReportView_ID == 0) {
        // unlock ();
        return;
      }
    }

    //  If not a report, we need a prodedure name
    if (!IsReport && ProcedureName.length() == 0) {
      m_pi.setSummary(Msg.getMsg(m_wscctx, "ProcessNoProcedure"), true);
      // unlock();
      return;
    }

    /** ******************************************************************** Report submission */
    if (IsReport) {
      //	Optional Pre-Report Process
      if (ProcedureName.length() > 0) {
        if (!startDBProcess(ProcedureName)) {
          // unlock();
          return;
        }
      } //	Pre-Report

      //	Start Report	-----------------------------------------------
      boolean ok = ReportCtl.start(m_pi, IsDirectPrint);
      m_pi.setSummary("Report", !ok);
      // unlock ();
    }
    /** ******************************************************************** Process submission */
    else {
      if (!startDBProcess(ProcedureName)) {
        // unlock();
        return;
      }
      //	Success - getResult
      ProcessInfoUtil.setSummaryFromDB(m_pi);
      // unlock();
    } //	*** Process submission ***
    //	log.fine(Log.l3_Util, "ProcessCtl.run - done");
  } //  run