Example #1
0
  private static void updateMultiBase() {
    // Calcul automatique du ht des saisies de vente avec facture

    System.err.println("Start");
    // on recupere les differentes bases
    ComptaPropsConfiguration instance = ComptaPropsConfiguration.create();
    Configuration.setInstance(instance);
    SQLBase base = Configuration.getInstance().getBase();
    SQLTable tableBase = base.getTable("SOCIETE_COMMON");

    SQLSelect sel = new SQLSelect(base, false);
    sel.addSelect(tableBase.getField("DATABASE_NAME"));

    List listBasesNX =
        (List)
            Configuration.getInstance()
                .getBase()
                .getDataSource()
                .execute(sel.asString(), new ArrayListHandler());

    // for (int i = 0; i < listBasesNX.size(); i++) {
    // Object[] tmp = (Object[]) listBasesNX.get(i);
    //
    // setOrdreComptePCE(tmp[0].toString());
    // }

    reOrderCompteID("Default");
    System.err.println("End");
  }
Example #2
0
  private ValidState computeCodeValidity() {
    final String code = this.textCode.getText().trim();

    if (VariablePayeSQLElement.isForbidden(code))
      return ValidState.createCached(false, "Code réservé");

    // on vérifie que la variable n'existe pas déja
    final SQLSelect selAllCodeName = new SQLSelect(getTable().getBase());

    selAllCodeName.addSelectFunctionStar("count");
    selAllCodeName.setWhere(new Where(getTable().getField("CODE"), "=", code));

    final int idSelected = this.getSelectedID();
    if (idSelected >= SQLRow.MIN_VALID_ID) {
      selAllCodeName.andWhere(new Where(getTable().getField("ID"), "!=", idSelected));
    }

    final Number rubCount =
        (Number)
            getTable().getDBSystemRoot().getDataSource().executeScalar(selAllCodeName.asString());
    if (rubCount.intValue() > 0) return ValidState.createCached(false, "Code déjà attribué");

    final SQLSelect selAllVarName = new SQLSelect(getTable().getBase());
    final SQLTable tableVar = getTable().getTable("VARIABLE_PAYE");
    selAllVarName.addSelectFunctionStar("count");
    selAllVarName.setWhere(new Where(tableVar.getField("NOM"), "=", code));
    final Number payVarCount =
        (Number)
            getTable().getDBSystemRoot().getDataSource().executeScalar(selAllVarName.asString());

    return ValidState.createCached(
        payVarCount.intValue() == 0, "Code déjà attribué à une variable de paye");
  }
Example #3
0
 protected void walk(ItemTreeModel model, Group gr, Object o) {
   int cc = model.getChildCount(o);
   for (int i = 0; i < cc; i++) {
     ActivableMutableTreeNode child = (ActivableMutableTreeNode) model.getChild(o, i);
     if (child.isActive()) {
       final Item userObject = (Item) child.getUserObject();
       if (userObject instanceof Group) {
         final Group item = new Group(userObject.getId());
         item.setLocalHint(new LayoutHints(userObject.getLocalHint()));
         gr.add(item);
         walk(model, item, child);
       } else {
         final Item item = new Item(userObject.getId());
         item.setLocalHint(new LayoutHints(userObject.getLocalHint()));
         final SQLTable table =
             ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable(n.getTable());
         if (table.contains(userObject.getId())) {
           SQLField field = table.getField(userObject.getId());
           if (!field.isPrimaryKey()
               && !field.getName().endsWith("ORDRE")
               && !field.getName().endsWith("ARCHIVE")) {
             gr.add(item);
           }
         }
       }
     }
   }
 }
Example #4
0
  /**
   * Création d'une société à partir de la base GestionDefault
   *
   * @param baseDefault nom de la base par défaut
   * @param newBase nom de la nouvelle base
   */
  public static void dupliqueDB(String baseDefault, String newBase, StatusListener l) {
    final DBSystemRoot sysRoot = Configuration.getInstance().getSystemRoot();

    // FIXME ADD TRIGGER TO UPDATE SOLDE COMPTE_PCE
    // ComptaPropsConfiguration instance = ComptaPropsConfiguration.create();
    // Configuration.setInstance(instance);

    try {
      log(l, "Création du schéma");
      if (!sysRoot.getRootsToMap().contains(baseDefault)) {
        sysRoot.getRootsToMap().add(baseDefault);
        sysRoot.refetch(Collections.singleton(baseDefault));
      }
      final DBRoot baseSQLDefault = sysRoot.getRoot(baseDefault);
      log(l, "Traitement des " + baseSQLDefault.getChildrenNames().size() + " tables");

      final SQLCreateRoot createRoot =
          baseSQLDefault.getDefinitionSQL(sysRoot.getServer().getSQLSystem());
      final SQLDataSource ds = sysRoot.getDataSource();
      // be safe don't add DROP SCHEMA
      ds.execute(createRoot.asString(newBase, false, true));
      sysRoot.getRootsToMap().add(newBase);
      // TODO find a more functional way
      final boolean origVal = Boolean.getBoolean(SQLSchema.NOAUTO_CREATE_METADATA);
      if (!origVal) System.setProperty(SQLSchema.NOAUTO_CREATE_METADATA, "true");
      sysRoot.refetch(Collections.singleton(newBase));
      if (!origVal) System.setProperty(SQLSchema.NOAUTO_CREATE_METADATA, "false");
      final DBRoot baseSQLNew = sysRoot.getRoot(newBase);

      final Set<SQLTable> newTables = baseSQLNew.getTables();
      int i = 0;
      final SQLSyntax syntax = sysRoot.getServer().getSQLSystem().getSyntax();
      // MAYBE SQLCreateRoot can avoid creating foreign constraints, then we insert data,
      // finally SQLCreateRoot adds just the constraints
      ds.execute(syntax.disableFKChecks(baseSQLNew));
      for (final SQLTable table : newTables) {
        String tableName = table.getName();

        log(l, "Copie de la table " + tableName + " " + (i + 1) + "/" + newTables.size());
        // Dump Table
        dumpTable(baseSQLDefault, table);
        log(l, "Table " + tableName + " " + (i + 1) + "/" + newTables.size() + " OK");
        i++;
      }
      ds.execute(syntax.enableFKChecks(baseSQLNew));

      if (syntax.getSystem() == SQLSystem.POSTGRESQL) {
        log(l, "Maj des séquences des tables");
        new FixSerial(sysRoot).changeAll(baseSQLNew);
      }

      log(l, "Duplication terminée");

    } catch (Throwable e) {
      e.printStackTrace();
      ExceptionHandler.handle("Erreur pendant la création de la base!", e);
      log(l, "Erreur pendant la duplication");
    }
  }
Example #5
0
 /**
  * copie l'integralite de la table "tableName" de la base "base" dans la nouvelle base "baseNew"
  *
  * @param base
  * @param baseNew
  * @param tableName
  */
 private static void dumpTable(DBRoot source, SQLTable newTable) {
   try {
     SQLRowValues.insertFromTable(newTable, source.getTable(newTable.getName()));
   } catch (SQLException e) {
     System.err.println("Unable to dump table " + newTable.getName());
     e.printStackTrace();
   }
 }
Example #6
0
  public static void addUndefined(SQLBase base) {
    Set<String> tableNames = base.getTableNames();
    for (String tableName : tableNames) {
      SQLTable table = base.getTable(tableName);
      SQLField fieldPrimaryKey = table.getKey();

      if (fieldPrimaryKey != null
          && fieldPrimaryKey.getType().getJavaType().getSuperclass() != null
          && fieldPrimaryKey.getType().getJavaType().getSuperclass() == Number.class) {

        String patch =
            "INSERT INTO \"" + tableName + "\"(\"" + fieldPrimaryKey.getName() + "\") VALUES (1)";
        base.execute(patch);
      }
    }
  }
  public static final List<SQLRowValues> fetchRows(
      final Configuration conf,
      final SQLTable foreignTable,
      List<SQLField> fieldsToFetch,
      final Where where) {
    // TODO: a cleaner par Sylvain
    SQLRowValues graphToFetch =
        ElementComboBoxUtils.getGraphToFetch(conf, foreignTable, fieldsToFetch);
    final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(graphToFetch, false);
    final String tableName = foreignTable.getName();
    BaseFillSQLRequest.setupForeign(fetcher);
    final ITransformer<SQLSelect, SQLSelect> origSelTransf = fetcher.getSelTransf();
    fetcher.setSelTransf(
        new ITransformer<SQLSelect, SQLSelect>() {
          @Override
          public SQLSelect transformChecked(SQLSelect sel) {
            if (origSelTransf != null) sel = origSelTransf.transformChecked(sel);
            boolean lockSelect = true;
            if (lockSelect) {
              sel.addWaitPreviousWriteTXTable(tableName);
            }
            for (final Path orderP : Collections.singletonList(new Path(foreignTable))) {
              sel.addOrder(sel.assurePath(tableName, orderP), false);
            }
            if (where != null) {
              sel.andWhere(where);
            }
            return sel;
          }
        });

    final SQLRowValuesListFetcher comboSelect = fetcher.freeze();
    final List<SQLRowValues> fetchedRows = comboSelect.fetch();
    return fetchedRows;
  }
  public static final StringWithId createItem(
      Configuration conf, SQLTable primaryTable, final SQLRowValues rs, List<SQLField> fields) {
    final String desc;
    if (rs.getID() == primaryTable.getUndefinedID()) desc = "?";
    else
      desc =
          CollectionUtils.join(
              getShowAs(conf).expandGroupBy(fields),
              " ◄ ",
              new ITransformer<Tuple2<Path, List<FieldPath>>, Object>() {
                public Object transformChecked(Tuple2<Path, List<FieldPath>> ancestorFields) {
                  final List<String> filtered =
                      CollectionUtils.transformAndFilter(
                          ancestorFields.get1(),
                          new ITransformer<FieldPath, String>() {
                            // no need to keep this Transformer in an attribute
                            // even when creating one per line it's the same speed
                            public String transformChecked(FieldPath input) {
                              return input.getString(rs);
                            }
                          },
                          IPredicate.notNullPredicate(),
                          new ArrayList<String>());
                  return CollectionUtils.join(filtered, " ");
                }
              });
    // don't store the whole SQLRowValues to save some memory
    final StringWithId res = new StringWithId(rs.getID(), desc);

    return res;
  }
  public void updateSelection(int[] rowIndex) {
    System.err.println("Update Selection");
    this.creditSelection = 0;
    this.debitSelection = 0;

    if (rowIndex != null) {
      for (int i = 0; i < rowIndex.length; i++) {

        SQLRow row = tableEcr.getRow(rowIndex[i]);

        if (row != null) {

          // if (row.getString("POINTEE").trim().length() == 0) {
          this.debitSelection += ((Long) row.getObject("DEBIT")).longValue();
          this.creditSelection += ((Long) row.getObject("CREDIT")).longValue();
          // }
          /*
           * else {
           *
           * this.debitSelection -= row.getFloat("DEBIT"); this.creditSelection -=
           * row.getFloat("CREDIT"); }
           */
        }
      }
    }
    this.fireTableDataChanged();
  }
Example #10
0
  public static void setOrder(SQLBase base) {
    Set<String> tableNames = base.getTableNames();
    for (String tableName : tableNames) {
      SQLTable table = base.getTable(tableName);
      // SQLField fieldPrimaryKey = table.getKey();
      SQLField field = table.getOrderField();

      if (field != null) {
        base.execute(
            "ALTER TABLE \""
                + tableName
                + "\" ALTER COLUMN \""
                + field.getName()
                + "\" SET DEFAULT 0;");
        base.execute(
            "ALTER TABLE \""
                + tableName
                + "\" ALTER COLUMN \""
                + field.getName()
                + "\" SET NOT NULL;");
      }
    }
  }
  private int[] getMouvement(int idPiece) {

    int[] idS = null;

    SQLBase b = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
    SQLTable tableMvt = b.getTable("MOUVEMENT");

    SQLSelect sel = new SQLSelect(b);
    sel.addSelect(tableMvt.getField("NUMERO"));
    sel.setWhere(tableMvt.getField("ID_PIECE"), "=", idPiece);

    List l = (List) b.getDataSource().execute(sel.asString(), new ArrayListHandler());

    if (l.size() > 0) {
      idS = new int[l.size()];
    }

    for (int i = 0; i < l.size(); i++) {
      Object[] tmp = (Object[]) l.get(i);
      idS[i] = Integer.parseInt(tmp[0].toString());
    }

    return idS;
  }
Example #12
0
  protected void changeImpl(final SQLTable t) throws SQLException {
    this.getStream().print(t.getName() + "... ");
    if (this.getFields().size() == 0) throw new IllegalStateException("no fields defined");
    this.getStream().print(getFields() + " ");

    // test if duplicates can happen
    if (t.getPKsNames().equals(this.getFields())
        || t.getConstraint(ConstraintType.UNIQUE, getFields()) != null)
      this.getStream().println("already");
    else {
      this.getStream()
          .println(
              SQLUtils.executeAtomic(
                  getDS(),
                  new ConnectionHandlerNoSetup<String, SQLException>() {
                    @Override
                    public String handle(SQLDataSource ds) throws SQLException {
                      // cannot just select * group by into a tmp table, delete from t, and insert
                      // since when "grouping by" each selected column must be an aggregate

                      // need a primary key to differentiate duplicates
                      final String addedPK;
                      if (t.getKey() == null) {
                        addedPK = SQLSyntax.ID_NAME;
                        ds.execute(
                            new AlterTable(t)
                                .addColumn(addedPK, getSyntax().getPrimaryIDDefinition())
                                .asString());
                        t.fetchFields();
                      } else addedPK = null;
                      assert t.getKey() != null;

                      // find out one ID per unique row
                      final SQLSelect sel = new SQLSelect(t.getBase());
                      sel.addSelect(t.getKey(), "min");
                      for (final String f : getFields()) sel.addGroupBy(t.getField(f));
                      ds.execute(
                          "CREATE TEMPORARY TABLE "
                              + SQLBase.quoteIdentifier("ID_TO_KEEP")
                              + " as "
                              + sel.asString());

                      // delete the rest
                      ds.execute(
                          t.getBase()
                              .quote(
                                  "DELETE FROM %f where %n not in (SELECT * from "
                                      + SQLBase.quoteIdentifier("ID_TO_KEEP")
                                      + ")",
                                  t,
                                  t.getKey()));

                      // add constraint
                      if (addedPK != null) {
                        ds.execute(new AlterTable(t).dropColumn(addedPK).asString());
                        ds.execute(
                            new AlterTable(t)
                                .addClause(
                                    "ADD PRIMARY KEY("
                                        + SQLSyntax.quoteIdentifiers(getFields())
                                        + ")",
                                    ClauseType.ADD_CONSTRAINT)
                                .asString());
                        return "added primary key";
                      } else {
                        ds.execute(
                            new AlterTable(t).addUniqueConstraint("uniq", getFields()).asString());
                        return "added unique constraint";
                      }
                    }
                  }));
    }
  }
  public SuppressionEcrituresPanel(final int idMvt) {
    this.setLayout(new GridBagLayout());
    final GridBagConstraints c = new DefaultGridBagConstraints();
    c.weightx = 1;
    SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
    SQLTable tableMouvement = base.getTable("MOUVEMENT");
    SQLRow rowMvt = tableMouvement.getRow(idMvt);
    JLabel label = new JLabel("Vous allez supprimer la piéce n°" + rowMvt.getInt("ID_PIECE"));
    JLabelWarning warning = new JLabelWarning();
    JPanel panelLabel = new JPanel();
    panelLabel.add(warning);
    panelLabel.add(label);

    c.gridwidth = GridBagConstraints.REMAINDER;
    this.add(panelLabel, c);

    // TODO afficher les numeros de mouvement implique
    int[] idS = getMouvement(rowMvt.getInt("ID_PIECE"));
    if (idS == null) {
      ExceptionHandler.handle(
          "Aucun mouvement associé à la piéce n°"
              + ((rowMvt != null) ? rowMvt.getInt("ID_PIECE") : "mouvement nul"));
    } else {
      StringBuffer s = new StringBuffer();
      s.append("Elle est composée par les mouvements : (");
      JLabel labelMouv = new JLabel();
      // c.gridwidth = 1;
      c.gridy++;
      c.gridx = 0;
      this.add(labelMouv, c);
      s.append(idS[0]);
      for (int i = 1; i < idS.length; i++) {

        s.append(", ");
        s.append(idS[i]);
      }
      s.append(')');
      labelMouv.setText(s.toString());
    }

    JButton buttonOK = new JButton("OK");
    JButton buttonCancel = new JButton("Annuler");

    c.gridwidth = 1;
    c.gridy++;
    c.gridx = 0;
    this.add(buttonOK, c);
    c.gridx++;
    this.add(buttonCancel, c);

    buttonOK.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            EcritureSQLElement elt =
                (EcritureSQLElement)
                    Configuration.getInstance().getDirectory().getElement("ECRITURE");
            elt.archiveMouvement(idMvt);
            ((JFrame) SwingUtilities.getRoot(SuppressionEcrituresPanel.this)).dispose();
          }
        });
    buttonCancel.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            ((JFrame) SwingUtilities.getRoot(SuppressionEcrituresPanel.this)).dispose();
          }
        });
  }
Example #14
0
  public static void fixUserCommon(int base) {

    if (Configuration.getInstance() == null) {
      Configuration.setInstance(ComptaPropsConfiguration.create());
    }
    Configuration instance = Configuration.getInstance();
    SQLTable tableSociete = Configuration.getInstance().getBase().getTable("SOCIETE_COMMON");

    String baseName = tableSociete.getRow(base).getString("DATABASE_NAME");

    instance.getBase().getDBSystemRoot().getRootsToMap().clear();
    try {
      Set<String> s = new HashSet<String>();
      s.add(baseName);
      instance.getBase().fetchTables(s);
    } catch (SQLException e) {
      throw new IllegalStateException("could not access societe base", e);
    }

    System.err.println("baseName" + baseName);
    instance.getSystemRoot().prependToRootPath("Common");
    instance.getSystemRoot().prependToRootPath(baseName);

    SQLSchema baseSQL = instance.getBase().getSchema(baseName);

    DatabaseMetaData dbMetaDataSociete;
    try {
      dbMetaDataSociete = baseSQL.getBase().getDataSource().getConnection().getMetaData();

      String[] type = new String[1];
      type[0] = "TABLE";
      ResultSet rs = dbMetaDataSociete.getTables("", baseSQL.getName(), "%", null);

      System.err.println("Start " + rs.getFetchSize());
      int i = 0;
      while (rs.next()) {

        if (rs.getString("TABLE_TYPE") != null
            && rs.getString("TABLE_TYPE").equalsIgnoreCase("TABLE")) {
          // System.err.println("FIND TABLE");
          // baseSQL.getTableNames();
          final SQLTable table = baseSQL.getTable(rs.getString("TABLE_NAME"));
          Set<SQLField> s = table.getFields();
          for (SQLField field : s) {
            if (field.getName().equalsIgnoreCase("ID_USER_COMMON_CREATE")
                || field.getName().equalsIgnoreCase("ID_USER_COMMON_MODIFY")) {
              Object o = field.getDefaultValue();
              if (o == null || (o instanceof Integer && ((Integer) o) == 0)) {

                System.err.println("Bad default on " + field);
                baseSQL
                    .getBase()
                    .execute(
                        "ALTER TABLE \""
                            + field.getTable().getSchema().getName()
                            + "\".\""
                            + field.getTable().getName()
                            + "\" ALTER COLUMN \""
                            + field.getName()
                            + "\" SET DEFAULT 1;");

                baseSQL
                    .getBase()
                    .execute(
                        "UPDATE \""
                            + field.getTable().getSchema().getName()
                            + "\".\""
                            + field.getTable().getName()
                            + "\" SET \""
                            + field.getName()
                            + "\"=1 WHERE \""
                            + field.getName()
                            + "\"=0 OR \""
                            + field.getName()
                            + "\" IS NULL;");
              }
            }
          }
        }
        // System.err.println(i++ + " " + rs.getString("TABLE_TYPE"));
      }
      rs.close();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #15
0
 /**
  * Add a column and its foreign constraint
  *
  * @param fk the field name, eg "ID_BAT".
  * @param foreignTable the referenced table, eg /BATIMENT/.
  * @param absolute <code>true</code> if the link should include the whole name of <code>
  *     foreignTable</code>, <code>false</code> if the link should just be its name.
  * @return this.
  * @see #addForeignColumn(String, SQLName, String, String)
  */
 public T addForeignColumn(String fk, SQLTable foreignTable, final boolean absolute) {
   final String defaultVal =
       foreignTable.getKey().getType().toString(foreignTable.getUndefinedIDNumber());
   final SQLName n = absolute ? foreignTable.getSQLName() : new SQLName(foreignTable.getName());
   return this.addForeignColumn(fk, n, foreignTable.getKey().getName(), defaultVal);
 }
Example #16
0
  /**
   * Affiche si il y a des différences entre les tables de base et baseDefault
   *
   * @param base
   * @param baseDefault
   */
  public static void compareDB(int base, int baseDefault) {

    try {
      if (Configuration.getInstance() == null) {
        Configuration.setInstance(ComptaPropsConfiguration.create());
      }
      Configuration instance = Configuration.getInstance();
      SQLTable tableSociete = Configuration.getInstance().getBase().getTable("SOCIETE_COMMON");

      String baseName = tableSociete.getRow(base).getString("DATABASE_NAME");
      String baseDefaultName = tableSociete.getRow(baseDefault).getString("DATABASE_NAME");

      instance.getBase().getDBSystemRoot().getRootsToMap().clear();
      try {
        Set<String> s = new HashSet<String>();
        s.add(baseName);
        s.add(baseDefaultName);
        instance.getBase().fetchTables(s);
      } catch (SQLException e) {
        throw new IllegalStateException("could not access societe base", e);
      }
      // instance.getBase().getDBRoot(baseName);
      // instance.getBase().getDBRoot(baseDefaultName);
      System.err.println("baseName" + baseName);
      System.err.println("baseDefault" + baseDefaultName);
      instance.getSystemRoot().prependToRootPath("Common");
      instance.getSystemRoot().prependToRootPath(baseName);
      instance.getSystemRoot().prependToRootPath(baseDefaultName);

      SQLSchema baseSQL = instance.getBase().getSchema(baseName);
      SQLSchema baseSQLDefault = instance.getBase().getSchema(baseDefaultName);

      DatabaseMetaData dbMetaDataSociete =
          baseSQL.getBase().getDataSource().getConnection().getMetaData();
      DatabaseMetaData dbMetaDataSocieteDefault =
          baseSQLDefault.getBase().getDataSource().getConnection().getMetaData();

      Map<String, Map<String, SQLField>> mapTableSociete =
          new HashMap<String, Map<String, SQLField>>();
      Map<String, Map<String, SQLField>> mapTableSocieteDefault =
          new HashMap<String, Map<String, SQLField>>();

      ResultSet rs = dbMetaDataSociete.getTables("", baseSQL.getName(), "%", null);

      System.err.println("Start");

      while (rs.next()) {
        // System.err.println(rs.getString("TABLE_NAME") + ", TYPE ::" +
        // rs.getString("TABLE_TYPE"));

        if (rs.getString("TABLE_TYPE") != null
            && rs.getString("TABLE_TYPE").equalsIgnoreCase("TABLE")) {
          Map<String, SQLField> m = new HashMap<String, SQLField>();
          baseSQL.getTableNames();
          Set<SQLField> s = baseSQL.getTable(rs.getString("TABLE_NAME")).getFields();
          for (SQLField field : s) {
            m.put(field.getName(), field);
          }
          mapTableSociete.put(rs.getString("TABLE_NAME"), m);
        }
      }
      rs.close();

      rs = dbMetaDataSocieteDefault.getTables("", baseSQLDefault.getName(), "%", null);

      while (rs.next()) {
        // System.err.println(rs.getString("TABLE_NAME") + ", TYPE ::" +
        // rs.getString("TABLE_TYPE"));
        if (rs.getString("TABLE_TYPE") != null
            && rs.getString("TABLE_TYPE").equalsIgnoreCase("TABLE")) {
          Map<String, SQLField> m = new HashMap<String, SQLField>();
          Set<SQLField> s = baseSQLDefault.getTable(rs.getString("TABLE_NAME")).getFields();
          for (SQLField field : s) {
            m.put(field.getName(), field);
          }
          mapTableSocieteDefault.put(rs.getString("TABLE_NAME"), m);
        }
      }
      rs.close();

      System.err.println("Test 1 " + mapTableSociete.keySet().size());
      // On verifie que toutes les tables de la societe sont contenues dans la base default
      for (String tableName : mapTableSociete.keySet()) {

        if (!mapTableSocieteDefault.containsKey(tableName)) {
          System.err.println(
              "!! **** La table " + tableName + " n'est pas dans la base " + baseDefault);

        } else {
          Map<String, SQLField> mSoc = mapTableSociete.get(tableName);
          Map<String, SQLField> mDef = mapTableSocieteDefault.get(tableName);
          if (mSoc.keySet().containsAll(mDef.keySet())) {
            if (mSoc.keySet().size() == mDef.keySet().size()) {
              System.err.println("Table " + tableName + " --- OK");
              compareTypeField(mSoc, mDef);
            } else {
              if (mSoc.keySet().size() > mDef.keySet().size()) {
                for (String fieldName : mDef.keySet()) {
                  mSoc.remove(fieldName);
                }
                System.err.println("!! **** Difference Table " + tableName);
                System.err.println(
                    tableSociete.getRow(baseDefault).getString("DATABASE_NAME")
                        + " Set Column "
                        + mSoc);
                System.err.println(
                    getAlterTable(
                        mSoc,
                        tableSociete.getRow(baseDefault).getString("DATABASE_NAME"),
                        tableName));
              } else {

              }
            }
          } else {
            // System.err.println("!! **** Difference Table " + tableName);
            // System.err.println(tableSociete.getRow(base).getString("DATABASE_NAME") +
            // " Set Column " + mapTableSociete.get(tableName));
            // System.err.println(tableSociete.getRow(baseDefault).getString("DATABASE_NAME")
            // + " Set Column " + mapTableSocieteDefault.get(tableName));
            for (String fieldName : mSoc.keySet()) {
              mDef.remove(fieldName);
            }
            System.err.println("!! **** Difference Table " + tableName);
            System.err.println(
                tableSociete.getRow(base).getString("DATABASE_NAME") + " Set Column " + mDef);
            System.err.println(
                getAlterTable(
                    mDef, tableSociete.getRow(base).getString("DATABASE_NAME"), tableName));
          }
        }
      }

      System.err.println("Test 2 " + mapTableSocieteDefault.keySet().size());
      // On verifie que toutes les tables de la base default sont contenues dans la base
      // societe
      for (Iterator i = mapTableSocieteDefault.keySet().iterator(); i.hasNext(); ) {
        Object tableName = i.next();
        if (!mapTableSociete.containsKey(tableName)) {
          System.err.println(
              "!! **** La table " + tableName + " n'est pas dans la base " + baseDefault);
        }
      }

      SQLSchema schem = instance.getBase().getSchema("Common");

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
  private void genereMouvement() throws IllegalArgumentException {

    SQLRow saisieRow =
        GenerationMvtSaisieVenteComptoir.saisieVCTable.getRow(this.idSaisieVenteComptoir);
    SQLRow clientRow = base.getTable("CLIENT").getRow(saisieRow.getInt("ID_CLIENT"));
    SQLRow taxeRow = base.getTable("TAXE").getRow(saisieRow.getInt("ID_TAXE"));

    // Calcul des montants
    PrixTTC prixTTC = new PrixTTC(((Long) saisieRow.getObject("MONTANT_TTC")).longValue());
    PrixHT prixHT = new PrixHT(prixTTC.calculLongHT(taxeRow.getFloat("TAUX") / 100));
    long service = ((Long) saisieRow.getObject("MONTANT_SERVICE")).longValue();

    // iniatilisation des valeurs de la map
    this.date = (Date) saisieRow.getObject("DATE");
    String string = "Vente comptoir ";
    final String rowLib = saisieRow.getObject("NOM").toString();
    if (rowLib != null && rowLib.trim().length() > 0) {
      string += rowLib.trim();
    } else {
      string += saisieRow.getForeignRow("ID_ARTICLE").getString("NOM");
    }
    this.nom = string;
    this.mEcritures.put("DATE", this.date);
    this.mEcritures.put("NOM", this.nom);
    this.mEcritures.put("ID_JOURNAL", GenerationMvtSaisieVenteComptoir.journal);
    this.mEcritures.put("ID_MOUVEMENT", new Integer(1));

    // on calcule le nouveau numero de mouvement
    if (this.idMvt == 1) {
      this.idMvt =
          getNewMouvement(
              GenerationMvtSaisieVenteComptoir.source, this.idSaisieVenteComptoir, 1, string);
      this.mEcritures.put("ID_MOUVEMENT", new Integer(this.idMvt));
    }

    // generation des ecritures + maj des totaux du compte associe

    // compte Vente
    if (service != 0) {

      int idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
      if (idCompteVenteService <= 1) {
        try {
          idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteVenteService));
      this.mEcritures.put("DEBIT", new Long(0));
      this.mEcritures.put("CREDIT", new Long(service));
      ajoutEcriture();

      // System.out.println("___________---> Value " + (prixHT.getValue() - service));
      if ((prixHT.getLongValue() - service) > 0) {
        int idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
        if (idCompteVenteProduit <= 1) {
          try {
            idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteVenteProduit));
        this.mEcritures.put("DEBIT", new Long(0));
        this.mEcritures.put("CREDIT", new Long(prixHT.getLongValue() - service));
        ajoutEcriture();
      }

    } else {

      int idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
      if (idCompteVenteProduit <= 1) {
        try {
          idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteVenteProduit));
      this.mEcritures.put("DEBIT", new Long(0));
      this.mEcritures.put("CREDIT", new Long(prixHT.getLongValue()));
      ajoutEcriture();
    }

    // compte TVA
    long tva = prixTTC.calculLongTVA(taxeRow.getFloat("TAUX") / 100.0);
    if (tva > 0) {
      int idCompteTVA = rowPrefsCompte.getInt("ID_COMPTE_PCE_TVA_VENTE");
      if (idCompteTVA <= 1) {
        try {
          idCompteTVA = ComptePCESQLElement.getIdComptePceDefault("TVACollectee");
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteTVA));
      this.mEcritures.put("DEBIT", new Long(0));
      this.mEcritures.put("CREDIT", new Long(tva));
      ajoutEcriture();
    }

    // compte Clients
    int idCompteClient = clientRow.getInt("ID_COMPTE_PCE");
    if (idCompteClient <= 1) {
      idCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT");
      if (idCompteClient <= 1) {
        try {
          idCompteClient = ComptePCESQLElement.getIdComptePceDefault("Clients");
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    this.mEcritures.put("ID_COMPTE_PCE", new Integer(idCompteClient));
    this.mEcritures.put("DEBIT", new Long(prixTTC.getLongValue()));
    this.mEcritures.put("CREDIT", new Long(0));
    ajoutEcriture();

    // Règlement
    String s = "Vente comptoir ";
    final String name = saisieRow.getObject("NOM").toString();
    if (name != null && rowLib.trim().length() > 0) {
      s += name.trim();
    } else {
      s += saisieRow.getForeignRow("ID_ARTICLE").getString("NOM");
    }
    SQLRow modeRegRow = saisieRow.getForeignRow("ID_MODE_REGLEMENT");

    new GenerationReglementVenteNG(
        s, clientRow, prixTTC, this.date, modeRegRow, saisieRow, mvtTable.getRow(this.idMvt));

    // On place le nuemro de mouvement associe à la saisie
    SQLRowValues valSaisieVC = new SQLRowValues(GenerationMvtSaisieVenteComptoir.saisieVCTable);
    valSaisieVC.put("ID_MOUVEMENT", new Integer(this.idMvt));

    try {
      if (valSaisieVC.getInvalid() == null) {
        // ajout de l'ecriture
        valSaisieVC.update(this.idSaisieVenteComptoir);
      }
    } catch (SQLException e) {
      System.err.println(
          "Erreur à l'insertion dans la table " + valSaisieVC.getTable().getName() + " : " + e);
      e.printStackTrace();
    }
  }
Example #18
0
  public void run() {

    SQLRow rowPrefCompte = tablePrefCompte.getRow(2);
    this.rowPrefCompteVals.loadAbsolutelyAll(rowPrefCompte);
    // TVA Coll
    int idCompteTVACol = this.rowPrefCompteVals.getInt("ID_COMPTE_PCE_TVA_VENTE");
    if (idCompteTVACol <= 1) {
      String compte;
      try {
        compte = ComptePCESQLElement.getComptePceDefault("TVACollectee");
        idCompteTVACol = ComptePCESQLElement.getId(compte);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    SQLRow rowCompteTVACol = tableCompte.getRow(idCompteTVACol);

    // TVA Ded
    int idCompteTVADed = this.rowPrefCompteVals.getInt("ID_COMPTE_PCE_TVA_ACHAT");
    if (idCompteTVADed <= 1) {
      try {
        String compte = ComptePCESQLElement.getComptePceDefault("TVADeductible");
        idCompteTVADed = ComptePCESQLElement.getId(compte);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    SQLRow rowCompteTVADed = tableCompte.getRow(idCompteTVADed);

    // TVA intracomm
    int idCompteTVAIntra = this.rowPrefCompteVals.getInt("ID_COMPTE_PCE_TVA_INTRA");
    if (idCompteTVAIntra <= 1) {
      try {
        String compte = ComptePCESQLElement.getComptePceDefault("TVAIntraComm");
        idCompteTVAIntra = ComptePCESQLElement.getId(compte);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    SQLRow rowCompteTVAIntra = tableCompte.getRow(idCompteTVAIntra);

    // Achats intracomm
    int idCompteAchatsIntra = this.rowPrefCompteVals.getInt("ID_COMPTE_PCE_ACHAT_INTRA");
    if (idCompteAchatsIntra <= 1) {
      try {
        String compte = ComptePCESQLElement.getComptePceDefault("AchatsIntra");
        idCompteAchatsIntra = ComptePCESQLElement.getId(compte);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    SQLRow rowCompteAchatIntra = tableCompte.getRow(idCompteAchatsIntra);

    // TVA immo
    int idCompteTVAImmo = this.rowPrefCompteVals.getInt("ID_COMPTE_PCE_TVA_IMMO");
    if (idCompteTVAImmo <= 1) {
      try {
        String compte = ComptePCESQLElement.getComptePceDefault("TVAImmo");
        idCompteTVAImmo = ComptePCESQLElement.getId(compte);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    SQLRow rowCompteTVAImmo = tableCompte.getRow(idCompteTVAImmo);

    PdfGenerator_3310 p = new PdfGenerator_3310();
    this.m = new HashMap<String, Object>();

    long v010 = -this.sommeCompte.soldeCompte(70, 70, true, this.dateDebut, this.dateFin);
    this.m.put("A01", GestionDevise.round(v010));

    // long vA02 = this.sommeCompte.soldeCompte(70, 70, true, this.dateDebut, this.dateFin);
    this.m.put("A02", "");
    long tvaIntra =
        -this.sommeCompte.sommeCompteFils(
            rowCompteTVAIntra.getString("NUMERO"), new Date(100, 0, 1), this.dateFin);
    long achatsIntra =
        this.sommeCompte.sommeCompteFils(
            rowCompteAchatIntra.getString("NUMERO"), this.dateDebut, this.dateFin);
    this.m.put("A03", GestionDevise.round(achatsIntra));
    this.m.put("A04", "");
    this.m.put("A05", "");
    this.m.put("A06", "");
    this.m.put("A07", "");

    long tvaCol =
        -this.sommeCompte.sommeCompteFils(
                rowCompteTVACol.getString("NUMERO"), new Date(100, 0, 1), this.dateFin)
            + tvaIntra;
    this.m.put("B08", GestionDevise.round(tvaCol));
    this.m.put("B08HT", GestionDevise.round(Math.round(tvaCol / 0.196)));
    this.m.put("B09", "");
    this.m.put("B09HT", "");
    this.m.put("B09B", "");
    this.m.put("B09BHT", "");

    this.m.put("B10", "");
    this.m.put("B10HT", "");
    this.m.put("B11", "");
    this.m.put("B11HT", "");
    this.m.put("B12", "");
    this.m.put("B12HT", "");
    this.m.put("B13", "");
    this.m.put("B13HT", "");
    this.m.put("B14", "");
    this.m.put("B14HT", "");

    this.m.put("B15", "");
    this.m.put("B16", GestionDevise.round(tvaCol));
    this.m.put("B17", GestionDevise.round(tvaIntra));
    this.m.put("B18", "");
    long tvaImmo =
        this.sommeCompte.sommeCompteFils(
            rowCompteTVAImmo.getString("NUMERO"), new Date(100, 0, 1), this.dateFin);
    this.m.put("B19", GestionDevise.round(tvaImmo));

    long tvaAutre =
        this.sommeCompte.sommeCompteFils(
            rowCompteTVADed.getString("NUMERO"), new Date(100, 0, 1), this.dateFin);
    this.m.put("B20", GestionDevise.round(tvaAutre));
    this.m.put("B21", "");
    this.m.put("B22", "");
    this.m.put("B23", "");
    long tvaDed = tvaAutre + tvaImmo;
    this.m.put("B24", GestionDevise.round(tvaDed));

    this.m.put("C25", "");
    this.m.put("C26", "");
    this.m.put("C27", "");
    this.m.put("C28", GestionDevise.round(tvaCol - tvaDed));
    this.m.put("C29", "");
    this.m.put("C30", "");
    this.m.put("C31", "");
    this.m.put("C32", GestionDevise.round(tvaCol - tvaDed));

    p.generateFrom(this.m);

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            Map3310.this.bar.setValue(95);
          }
        });

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {

            String file =
                TemplateNXProps.getInstance().getStringProperty("Location3310PDF")
                    + File.separator
                    + String.valueOf(Calendar.getInstance().get(Calendar.YEAR))
                    + File.separator
                    + "result_3310_2.pdf";
            System.err.println(file);
            File f = new File(file);
            Gestion.openPDF(f);
            Map3310.this.bar.setValue(100);
          }
        });
  }