OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
18 ilm 5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.config;
15
 
142 ilm 16
import org.openconcerto.erp.config.update.Updater_1_5;
144 ilm 17
import org.openconcerto.erp.core.humanresources.payroll.report.LignePayeSimplifiee;
93 ilm 18
import org.openconcerto.erp.core.sales.order.ui.EtatCommandeClient;
67 ilm 19
import org.openconcerto.erp.core.sales.quote.element.EtatDevisSQLElement;
61 ilm 20
import org.openconcerto.erp.modules.ModuleManager;
67 ilm 21
import org.openconcerto.erp.modules.ModuleReference;
182 ilm 22
import org.openconcerto.erp.rights.DepotStockViewRightEditor;
19 ilm 23
import org.openconcerto.sql.changer.convert.AddFK;
182 ilm 24
import org.openconcerto.sql.changer.convert.AddMDFields;
83 ilm 25
import org.openconcerto.sql.changer.convert.ChangeIDToInt;
182 ilm 26
import org.openconcerto.sql.changer.convert.MergeTable;
19 ilm 27
import org.openconcerto.sql.changer.correct.CorrectOrder;
18 ilm 28
import org.openconcerto.sql.changer.correct.FixSerial;
142 ilm 29
import org.openconcerto.sql.element.GroupSQLComponent;
73 ilm 30
import org.openconcerto.sql.model.AliasedTable;
19 ilm 31
import org.openconcerto.sql.model.DBRoot;
32
import org.openconcerto.sql.model.DBSystemRoot;
33
import org.openconcerto.sql.model.SQLBase;
34
import org.openconcerto.sql.model.SQLDataSource;
20 ilm 35
import org.openconcerto.sql.model.SQLField;
83 ilm 36
import org.openconcerto.sql.model.SQLField.Properties;
73 ilm 37
import org.openconcerto.sql.model.SQLInjector;
19 ilm 38
import org.openconcerto.sql.model.SQLName;
18 ilm 39
import org.openconcerto.sql.model.SQLRow;
40
import org.openconcerto.sql.model.SQLRowListRSH;
41
import org.openconcerto.sql.model.SQLRowValues;
73 ilm 42
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
80 ilm 43
import org.openconcerto.sql.model.SQLSchema;
18 ilm 44
import org.openconcerto.sql.model.SQLSelect;
19 ilm 45
import org.openconcerto.sql.model.SQLSyntax;
46
import org.openconcerto.sql.model.SQLSystem;
18 ilm 47
import org.openconcerto.sql.model.SQLTable;
48
import org.openconcerto.sql.model.Where;
57 ilm 49
import org.openconcerto.sql.model.graph.SQLKey;
80 ilm 50
import org.openconcerto.sql.request.Inserter;
83 ilm 51
import org.openconcerto.sql.request.Inserter.Insertion;
81 ilm 52
import org.openconcerto.sql.request.UpdateBuilder;
80 ilm 53
import org.openconcerto.sql.sqlobject.SQLTextCombo;
174 ilm 54
import org.openconcerto.sql.users.rights.TableAllRights;
18 ilm 55
import org.openconcerto.sql.utils.AlterTable;
19 ilm 56
import org.openconcerto.sql.utils.ChangeTable;
142 ilm 57
import org.openconcerto.sql.utils.ChangeTable.ClauseType;
58
import org.openconcerto.sql.utils.ChangeTable.DeferredClause;
19 ilm 59
import org.openconcerto.sql.utils.ReOrder;
80 ilm 60
import org.openconcerto.sql.utils.SQLCreateMoveableTable;
19 ilm 61
import org.openconcerto.sql.utils.SQLCreateTable;
62
import org.openconcerto.sql.utils.SQLUtils;
80 ilm 63
import org.openconcerto.sql.utils.SQLUtils.SQLFactory;
18 ilm 64
import org.openconcerto.ui.DefaultGridBagConstraints;
65
import org.openconcerto.ui.JLabelBold;
19 ilm 66
import org.openconcerto.utils.CollectionUtils;
18 ilm 67
import org.openconcerto.utils.ExceptionHandler;
73 ilm 68
import org.openconcerto.utils.ProductInfo;
174 ilm 69
import org.openconcerto.utils.StringUtils;
73 ilm 70
import org.openconcerto.utils.cc.ITransformer;
18 ilm 71
 
72
import java.awt.GridBagConstraints;
73
import java.awt.GridBagLayout;
74
import java.awt.Insets;
75
import java.awt.event.ActionEvent;
76
import java.awt.event.ActionListener;
61 ilm 77
import java.io.IOException;
67 ilm 78
import java.math.BigDecimal;
18 ilm 79
import java.sql.SQLException;
20 ilm 80
import java.sql.Types;
19 ilm 81
import java.util.ArrayList;
57 ilm 82
import java.util.Arrays;
80 ilm 83
import java.util.Collection;
84
import java.util.Collections;
19 ilm 85
import java.util.EnumSet;
57 ilm 86
import java.util.HashMap;
87
import java.util.HashSet;
18 ilm 88
import java.util.List;
57 ilm 89
import java.util.Map;
18 ilm 90
import java.util.Set;
91
 
92
import javax.swing.JButton;
93
import javax.swing.JLabel;
94
import javax.swing.JOptionPane;
95
import javax.swing.JPanel;
96
import javax.swing.JProgressBar;
97
import javax.swing.JTextField;
98
import javax.swing.SwingUtilities;
99
 
100
public class InstallationPanel extends JPanel {
57 ilm 101
    private static final boolean DEBUG_FK = false;
18 ilm 102
 
149 ilm 103
    public static void insertUndef(final SQLCreateTable ct) throws SQLException {
80 ilm 104
        // check that we can use insertReturnFirstField()
105
        if (ct.getPrimaryKey().size() != 1)
106
            throw new IllegalStateException("Not one and only one field in the PK : " + ct.getPrimaryKey());
107
        final Insertion<?> insertion = new Inserter(ct).insertReturnFirstField("(" + SQLBase.quoteIdentifier(SQLSyntax.ORDER_NAME) + ") VALUES(" + ReOrder.MIN_ORDER + ")", false);
108
        assert insertion.getCount() == 1;
109
        if (insertion.getRows().size() != 1)
110
            throw new IllegalStateException("Missing ID " + insertion.getRows());
111
        SQLTable.setUndefID(ct.getRoot().getSchema(), ct.getName(), ((Number) insertion.getRows().get(0)).intValue());
19 ilm 112
    }
113
 
149 ilm 114
    private static SQLName getTableName(final SQLCreateTable ct) {
19 ilm 115
        return new SQLName(ct.getRoot().getName(), ct.getName());
116
    }
117
 
18 ilm 118
    JProgressBar bar = new JProgressBar();
19 ilm 119
    boolean error;
18 ilm 120
 
121
    public InstallationPanel(final ServerFinderPanel finderPanel) {
122
        super(new GridBagLayout());
123
        setOpaque(false);
124
        GridBagConstraints c = new DefaultGridBagConstraints();
125
        JButton user = new JButton("Créer l'utilisateur");
57 ilm 126
        user.setOpaque(false);
18 ilm 127
        // JButton bd = new JButton("Créer la base de données");
128
        final JButton up = new JButton("Mise à niveau de la base");
57 ilm 129
        up.setOpaque(false);
18 ilm 130
        up.addActionListener(new ActionListener() {
131
 
132
            @Override
133
            public void actionPerformed(ActionEvent e) {
149 ilm 134
                if (finderPanel != null) {
135
                    finderPanel.saveConfigFile();
136
                }
18 ilm 137
                bar.setIndeterminate(true);
138
                up.setEnabled(false);
139
                new Thread(new Runnable() {
140
 
141
                    @Override
142
                    public void run() {
80 ilm 143
                        System.setProperty(SQLSchema.NOAUTO_CREATE_METADATA, "false");
19 ilm 144
                        final ComptaPropsConfiguration conf = ComptaPropsConfiguration.create(true);
18 ilm 145
 
149 ilm 146
                        updateDatabase(conf);
19 ilm 147
 
18 ilm 148
                        conf.destroy();
149
                        SwingUtilities.invokeLater(new Runnable() {
150
 
151
                            @Override
152
                            public void run() {
153
                                up.setEnabled(true);
41 ilm 154
                                bar.setValue(bar.getMaximum());
19 ilm 155
                                if (!error) {
156
                                    JOptionPane.showMessageDialog(InstallationPanel.this, "Mise à niveau réussie");
157
                                }
18 ilm 158
                            }
159
                        });
80 ilm 160
                        System.setProperty(SQLSchema.NOAUTO_CREATE_METADATA, "true");
18 ilm 161
                    }
162
                }, "Database structure updater").start();
163
 
164
            }
165
 
166
        });
149 ilm 167
        if (finderPanel != null && finderPanel.getToken() == null) {
61 ilm 168
            c.weightx = 1;
169
            c.gridwidth = GridBagConstraints.REMAINDER;
170
            this.add(new JLabelBold("Création de l'utilisateur openconcerto dans la base"), c);
171
            c.gridy++;
172
            c.weightx = 1;
173
            this.add(new JLabel("Identifiant de connexion de votre base "), c);
174
            c.gridy++;
175
            c.gridwidth = 1;
176
            c.weightx = 0;
177
            this.add(new JLabel("Login"), c);
178
            c.gridx++;
18 ilm 179
 
61 ilm 180
            final JTextField login = new JTextField();
181
            c.weightx = 1;
182
            this.add(login, c);
18 ilm 183
 
61 ilm 184
            c.gridx++;
185
            c.weightx = 0;
186
            this.add(new JLabel("Mot de passe"), c);
187
            c.gridx++;
188
            final JTextField mdp = new JTextField();
189
            c.weightx = 1;
190
            this.add(mdp, c);
18 ilm 191
 
61 ilm 192
            c.gridx = 0;
193
            c.gridy++;
194
            c.weightx = 0;
195
            c.anchor = GridBagConstraints.EAST;
196
            c.gridwidth = GridBagConstraints.REMAINDER;
197
            c.fill = GridBagConstraints.NONE;
198
            this.add(user, c);
199
            c.anchor = GridBagConstraints.WEST;
200
            c.fill = GridBagConstraints.HORIZONTAL;
201
            c.gridwidth = 1;
202
            user.addActionListener(new ActionListener() {
18 ilm 203
 
61 ilm 204
                @Override
205
                public void actionPerformed(ActionEvent e) {
206
                    try {
207
                        if (finderPanel.getServerConfig().createUserIfNeeded(login.getText(), mdp.getText())) {
208
                            JOptionPane.showMessageDialog(InstallationPanel.this, "L'utilisateur openconcerto a été correctement ajouté.");
209
                        } else {
210
                            JOptionPane.showMessageDialog(InstallationPanel.this, "L'utilisateur openconcerto existe déjà dans la base.");
211
                        }
212
                    } catch (Exception e1) {
213
                        e1.printStackTrace();
214
                        JOptionPane.showMessageDialog(InstallationPanel.this, "Une erreur est survenue pendant la connexion au serveur, vérifiez vos paramètres de connexion.");
18 ilm 215
                    }
216
                }
61 ilm 217
            });
18 ilm 218
 
61 ilm 219
            c.gridy++;
220
            c.weightx = 1;
221
            c.gridwidth = GridBagConstraints.REMAINDER;
222
            c.insets = new Insets(10, 3, 2, 2);
223
            this.add(new JLabelBold("Paramètrages de la base de données"), c);
224
            c.gridy++;
225
            c.insets = DefaultGridBagConstraints.getDefaultInsets();
226
            this.add(new JLabel("Création des fonctions SQL nécessaires (plpgsql)."), c);
227
            c.gridy++;
228
            c.weightx = 0;
229
            c.anchor = GridBagConstraints.EAST;
230
            c.gridwidth = GridBagConstraints.REMAINDER;
231
            c.fill = GridBagConstraints.NONE;
57 ilm 232
 
61 ilm 233
            JButton buttonPL = new JButton("Lancer");
234
            buttonPL.setOpaque(false);
235
            buttonPL.addActionListener(new ActionListener() {
25 ilm 236
 
61 ilm 237
                @Override
238
                public void actionPerformed(ActionEvent e) {
239
                    if (!finderPanel.getServerConfig().getType().equals(ServerFinderConfig.POSTGRESQL)) {
25 ilm 240
 
61 ilm 241
                    } else {
242
                        final ComptaPropsConfiguration conf = ComptaPropsConfiguration.create(true);
243
                        try {
244
                            final SQLDataSource ds = conf.getSystemRoot().getDataSource();
132 ilm 245
                            // ds.execute("CREATE FUNCTION plpgsql_call_handler() RETURNS
246
                            // language_handler AS '$libdir/plpgsql' LANGUAGE C;"
61 ilm 247
                            // + "\n"
248
                            // +
132 ilm 249
                            // "CREATE FUNCTION plpgsql_validator(oid) RETURNS void AS
250
                            // '$libdir/plpgsql' LANGUAGE C;"
61 ilm 251
                            // + "\n"
252
                            // +
132 ilm 253
                            // "CREATE TRUSTED PROCEDURAL LANGUAGE plpgsql HANDLER
254
                            // plpgsql_call_handler VALIDATOR plpgsql_validator;");
61 ilm 255
                            ds.execute("CREATE LANGUAGE plpgsql;");
256
 
257
                        } catch (Exception ex) {
258
                            System.err.println("Impossible d'ajouter le langage PLPGSQL. Peut etre est il déjà installé.");
259
                        }
25 ilm 260
                    }
61 ilm 261
                    JOptionPane.showMessageDialog(null, "Paramètrage terminé.");
25 ilm 262
                }
61 ilm 263
            });
264
            this.add(buttonPL, c);
265
        }
25 ilm 266
        c.gridy++;
267
        c.gridx = 0;
268
        c.weightx = 1;
269
        c.fill = GridBagConstraints.HORIZONTAL;
270
        c.anchor = GridBagConstraints.WEST;
271
        c.gridwidth = GridBagConstraints.REMAINDER;
272
        c.insets = new Insets(10, 3, 2, 2);
18 ilm 273
        this.add(new JLabelBold("Mise à niveau de la base OpenConcerto"), c);
274
        c.gridy++;
57 ilm 275
        c.insets = DefaultGridBagConstraints.getDefaultInsets();
276
        this.add(new JLabel("Cette opération est nécessaire à chaque mise à jour du logiciel."), c);
277
        c.gridy++;
278
        this.add(new JLabel("La mise à niveau peut prendre plusieurs minutes."), c);
279
        c.gridy++;
18 ilm 280
        this.add(this.bar, c);
281
        c.gridy++;
282
        c.weightx = 0;
283
        c.anchor = GridBagConstraints.EAST;
284
        c.gridwidth = GridBagConstraints.REMAINDER;
285
        c.fill = GridBagConstraints.NONE;
57 ilm 286
 
18 ilm 287
        this.add(up, c);
288
 
289
        c.anchor = GridBagConstraints.WEST;
290
        c.fill = GridBagConstraints.HORIZONTAL;
291
 
292
        c.weightx = 1;
293
        c.gridwidth = GridBagConstraints.REMAINDER;
294
        c.weighty = 1;
295
        c.gridy++;
296
        final JPanel comp = new JPanel();
297
        comp.setOpaque(false);
298
        this.add(comp, c);
299
    }
300
 
94 ilm 301
 
83 ilm 302
    private void addArticleFournisseur(DBRoot root) {
303
        if (!root.contains("ARTICLE_FOURNISSEUR")) {
304
 
305
            SQLCreateTable createBaseFamille = new SQLCreateTable(root, "FAMILLE_ARTICLE_FOURNISSEUR");
306
            createBaseFamille.addVarCharColumn("CODE", 45);
307
            createBaseFamille.addVarCharColumn("NOM", 2048);
308
            createBaseFamille.addForeignColumn("ID_FAMILLE_ARTICLE_FOURNISSEUR_PERE", createBaseFamille);
309
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
310
 
311
            try {
312
                ds.execute(createBaseFamille.asString());
313
 
314
                insertUndef(createBaseFamille);
315
                root.refetchTable("FAMILLE_ARTICLE_FOURNISSEUR");
316
                root.getSchema().updateVersion();
317
            } catch (SQLException ex) {
318
                throw new IllegalStateException("Erreur lors de la création de la table FAMILLE_ARTICLE_FOURNISSEUR", ex);
319
            }
320
 
321
            SQLCreateTable createBase = new SQLCreateTable(root, "ARTICLE_FOURNISSEUR");
322
            createBase.addVarCharColumn("CODE", 45);
323
            createBase.addVarCharColumn("CODE_BARRE", 45);
324
            createBase.addVarCharColumn("CODE_DOUANIER", 45);
325
            createBase.addVarCharColumn("NOM", 2048);
326
            createBase.addVarCharColumn("DESCRIPTIF", 2048);
327
            createBase.addVarCharColumn("INFOS", 2048);
328
 
329
            createBase.addColumn("PRIX_METRIQUE_HA_1", "numeric (16,6) DEFAULT 0");
330
            createBase.addColumn("PRIX_METRIQUE_HA_2", "numeric (16,8) DEFAULT 0");
331
            createBase.addColumn("PRIX_METRIQUE_HA_3", "numeric (16,8) DEFAULT 0");
332
 
333
            createBase.addColumn("PRIX_METRIQUE_VT_1", "numeric (16,8) DEFAULT 0");
334
            createBase.addColumn("PRIX_METRIQUE_VT_2", "numeric (16,8) DEFAULT 0");
335
            createBase.addColumn("PRIX_METRIQUE_VT_3", "numeric (16,8) DEFAULT 0");
336
 
337
            createBase.addForeignColumn("ID_METRIQUE_1", root.findTable("METRIQUE", true));
338
            createBase.addForeignColumn("ID_METRIQUE_2", root.findTable("METRIQUE", true));
339
            createBase.addForeignColumn("ID_METRIQUE_3", root.findTable("METRIQUE", true));
340
 
341
            createBase.addColumn("PA_DEVISE", "numeric (16,8) DEFAULT 0");
342
            createBase.addColumn("PV_U_DEVISE", "numeric (16,8) DEFAULT 0");
343
            createBase.addColumn("PA_HT", "numeric (16,8) DEFAULT 0");
344
            createBase.addColumn("PV_HT", "numeric (16,8) DEFAULT 0");
345
            createBase.addColumn("PV_TTC", "numeric (16,2) DEFAULT 0");
346
 
347
            createBase.addForeignColumn("ID_TAXE", root.findTable("TAXE", true));
348
            createBase.addForeignColumn("ID_FAMILLE_ARTICLE_FOURNISSEUR", root.findTable("FAMILLE_ARTICLE_FOURNISSEUR", true));
349
            createBase.addForeignColumn("ID_MODE_VENTE_ARTICLE", root.findTable("MODE_VENTE_ARTICLE", true));
350
            createBase.addForeignColumn("ID_FOURNISSEUR", root.findTable("FOURNISSEUR", true));
351
            createBase.addForeignColumn("ID_PAYS", root.findTable("PAYS", true));
352
            createBase.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
353
            createBase.addForeignColumn("ID_DEVISE_HA", root.findTable("DEVISE", true));
354
            createBase.addForeignColumn("ID_UNITE_VENTE", root.findTable("UNITE_VENTE", true));
355
            createBase.addForeignColumn("ID_COMPTE_PCE", root.findTable("COMPTE_PCE", true));
356
            createBase.addForeignColumn("ID_COMPTE_PCE_ACHAT", root.findTable("COMPTE_PCE", true));
357
            createBase.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
358
 
359
            createBase.addColumn("POIDS", "real DEFAULT 0");
360
            createBase.addColumn("VALEUR_METRIQUE_1", "real DEFAULT 0");
361
            createBase.addColumn("VALEUR_METRIQUE_2", "real DEFAULT 0");
362
            createBase.addColumn("VALEUR_METRIQUE_3", "real DEFAULT 0");
363
            createBase.addBooleanColumn("SERVICE", Boolean.FALSE, false);
364
            createBase.addBooleanColumn("OBSOLETE", Boolean.FALSE, false);
365
            createBase.addBooleanColumn("GESTION_STOCK", Boolean.FALSE, false);
366
            createBase.addIntegerColumn("QTE_ACHAT", 1);
367
            createBase.addIntegerColumn("QTE_MIN", 1);
368
 
369
            try {
370
                ds.execute(createBase.asString());
371
 
372
                insertUndef(createBase);
373
                root.refetchTable("ARTICLE_FOURNISSEUR");
374
                root.getSchema().updateVersion();
375
            } catch (SQLException ex) {
376
                throw new IllegalStateException("Erreur lors de la création de la table ARTICLE_FOURNISSEUR", ex);
377
            }
378
        }
379
    }
380
 
381
    private void addContact(DBRoot root) throws SQLException {
382
 
383
        List<String> tables = Arrays.asList("AVOIR_CLIENT", "DEVIS", "BON_DE_LIVRAISON", "COMMANDE_CLIENT", "SAISIE_VENTE_FACTURE");
93 ilm 384
        final SQLTable tableContact = root.findTable("CONTACT");
385
        final SQLTable tableDpt = root.findTable("CLIENT_DEPARTEMENT");
386
        final SQLDataSource dataSource = root.getDBSystemRoot().getDataSource();
83 ilm 387
        for (String tableName : tables) {
93 ilm 388
            boolean update = false;
389
            final SQLTable table = root.getTable(tableName);
390
            final AlterTable alterEcheance = new AlterTable(table);
83 ilm 391
 
392
            if (!table.contains("ID_CONTACT")) {
93 ilm 393
                alterEcheance.addForeignColumn("ID_CONTACT", tableContact);
394
                update = true;
395
            }
83 ilm 396
 
93 ilm 397
            if (!table.contains("ID_CLIENT_DEPARTEMENT")) {
398
                alterEcheance.addForeignColumn("ID_CLIENT_DEPARTEMENT", tableDpt);
399
                update = true;
400
            }
401
            if (update) {
83 ilm 402
                dataSource.execute(alterEcheance.asString());
403
                table.getSchema().updateVersion();
404
            }
93 ilm 405
 
83 ilm 406
        }
407
    }
408
 
73 ilm 409
    private void addForeignKeyFactureOnEcheance(DBRoot root) {
410
 
411
        final SQLTable tableEch = root.getTable("ECHEANCE_CLIENT");
412
        if (!tableEch.contains("ID_SAISIE_VENTE_FACTURE")) {
413
            final SQLTable tableFacture = root.getTable("SAISIE_VENTE_FACTURE");
414
            final SQLTable tableMvt = root.getTable("MOUVEMENT");
415
            String query = "no query";
416
            try {
417
                final SQLDataSource dataSource = root.getDBSystemRoot().getDataSource();
418
                final AlterTable alterEcheance = new AlterTable(tableEch);
419
                alterEcheance.addForeignColumn("ID_SAISIE_VENTE_FACTURE", tableFacture);
420
                dataSource.execute(alterEcheance.asString());
421
                tableEch.getSchema().updateVersion();
422
                tableEch.fetchFields();
81 ilm 423
 
424
                // select MOUVEMENT whose parent has a source FACTURE
425
                final SQLSelect selMvt = new SQLSelect();
426
                final AliasedTable refChild = new AliasedTable(tableMvt, "m1");
427
                final AliasedTable refParent = new AliasedTable(tableMvt, "m2");
428
                selMvt.addSelect(refParent.getField("IDSOURCE"));
429
                selMvt.addBackwardJoin("INNER", refChild.getField("ID_MOUVEMENT_PERE"), refParent.getAlias());
430
                selMvt.addSelect(refChild.getKey());
431
                selMvt.setWhere(new Where(refParent.getField("SOURCE"), "=", tableFacture.getName()));
432
 
433
                final UpdateBuilder build = new UpdateBuilder(tableEch);
434
                build.addVirtualJoin("( " + selMvt.asString() + " )", "mvt", false, tableMvt.getKey().getName(), "ID_MOUVEMENT");
435
                build.setFromVirtualJoinField("ID_SAISIE_VENTE_FACTURE", "mvt", "IDSOURCE");
436
                query = build.asString();
437
                dataSource.execute(query);
73 ilm 438
            } catch (SQLException ex) {
439
                Log.get().severe("Error on query :" + query);
440
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table ECHEANCE_CLIENT", ex);
441
            }
442
        }
443
    }
444
 
80 ilm 445
    private void addFieldForPartialInvoice(DBRoot root) throws SQLException {
446
        final SQLTable tableVF = root.getTable("SAISIE_VENTE_FACTURE");
447
        AlterTable alter = new AlterTable(tableVF);
448
        boolean doAlter = false;
449
        if (!tableVF.contains("POURCENT_FACTURABLE")) {
450
            alter.addColumn("POURCENT_FACTURABLE", "numeric (16,8)");
451
            doAlter = true;
452
        }
453
        if (!tableVF.contains("MONTANT_FACTURABLE")) {
454
            alter.addColumn("MONTANT_FACTURABLE", "numeric (16,8)");
455
            doAlter = true;
456
        }
457
 
458
        if (!tableVF.contains("SOLDE")) {
459
            alter.addColumn("SOLDE", "boolean DEFAULT false");
460
            doAlter = true;
461
        }
462
 
463
        if (!tableVF.contains("PARTIAL")) {
464
            alter.addColumn("PARTIAL", "boolean DEFAULT false");
465
            doAlter = true;
466
        }
467
 
468
        if (doAlter) {
469
            root.getDBSystemRoot().getDataSource().execute(alter.asString());
470
            root.refetchTable(tableVF.getName());
471
        }
472
 
473
        // ELT
474
        final SQLTable tableVFElt = root.getTable("SAISIE_VENTE_FACTURE_ELEMENT");
475
        AlterTable alterElt = new AlterTable(tableVFElt);
476
        boolean doAlterElt = false;
477
        if (!tableVFElt.contains("MONTANT_FACTURABLE")) {
478
            alterElt.addColumn("MONTANT_FACTURABLE", "numeric (16,8)");
479
            doAlterElt = true;
480
        }
481
 
482
        if (!tableVFElt.contains("POURCENT_FACTURABLE")) {
483
            alterElt.addColumn("POURCENT_FACTURABLE", "numeric (16,8)");
484
            doAlterElt = true;
485
        }
486
 
487
        if (doAlterElt) {
488
            root.getDBSystemRoot().getDataSource().execute(alterElt.asString());
489
            root.refetchTable(tableVFElt.getName());
490
        }
491
 
492
    }
493
 
93 ilm 494
    private void createAssocAnalytique(DBRoot root, ComptaPropsConfiguration conf) {
83 ilm 495
 
496
        if (!root.contains("ASSOCIATION_ANALYTIQUE")) {
497
 
498
            SQLCreateTable createAssoc = new SQLCreateTable(root, "ASSOCIATION_ANALYTIQUE");
499
            createAssoc.addForeignColumn("ID_ECRITURE", root.findTable("ECRITURE", true));
500
            createAssoc.addForeignColumn("ID_SAISIE_KM_ELEMENT", root.findTable("SAISIE_KM_ELEMENT", true));
501
            createAssoc.addForeignColumn("ID_POSTE_ANALYTIQUE", root.findTable("POSTE_ANALYTIQUE", true));
502
            createAssoc.addColumn("POURCENT", "numeric (16,8) DEFAULT 100");
503
            createAssoc.addColumn("MONTANT", "bigInt DEFAULT 0");
504
            createAssoc.addBooleanColumn("GESTION_AUTO", false, false);
505
 
506
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
507
 
508
            try {
509
                ds.execute(createAssoc.asString());
510
 
511
                insertUndef(createAssoc);
512
                root.refetchTable("ASSOCIATION_ANALYTIQUE");
513
                root.getSchema().updateVersion();
514
            } catch (SQLException ex) {
515
                throw new IllegalStateException("Erreur lors de la création de la table ASSOCIATION_ANALYTIQUE", ex);
516
            }
517
 
518
        }
93 ilm 519
        SQLTable tablePoste = root.getTable("POSTE_ANALYTIQUE");
520
        if (!tablePoste.contains("DEFAULT")) {
521
            AlterTable a = new AlterTable(tablePoste);
522
            a.addBooleanColumn("DEFAULT", Boolean.FALSE, false);
523
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
524
            try {
525
                ds.execute(a.asString());
526
                root.refetchTable("POSTE_ANALYTIQUE");
527
                root.getSchema().updateVersion();
528
            } catch (SQLException ex) {
529
                throw new IllegalStateException("Erreur lors de la création du DEFAULT sur la table POSTE_ANALYTIQUE", ex);
530
            }
531
        }
83 ilm 532
    }
533
 
534
    private void updateStock(DBRoot root) throws SQLException {
535
 
536
        final SQLTable tableStock = root.getTable("STOCK");
537
        final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
538
        if (!tableStock.contains("QTE_RECEPT_ATTENTE")) {
539
 
540
            try {
541
 
542
                AlterTable alterElt = new AlterTable(root.getTable("STOCK"));
543
                alterElt.addColumn("QTE_RECEPT_ATTENTE", "real DEFAULT 0");
544
                alterElt.addColumn("QTE_LIV_ATTENTE", "real DEFAULT 0");
545
                ds.execute(alterElt.asString());
546
 
547
                AlterTable alterMvt = new AlterTable(root.getTable("MOUVEMENT_STOCK"));
548
                alterMvt.addBooleanColumn("REEL", Boolean.TRUE, false);
549
 
550
                ds.execute(alterMvt.asString());
551
 
552
                root.getSchema().updateVersion();
553
 
554
            } catch (SQLException ex) {
555
                throw new IllegalStateException("Erreur lors de la mise à jour des tables de stock", ex);
556
            }
557
 
558
        }
559
        // if (!root.contains("ARTICLE_ELEMENT")) {
560
        // final SQLCreateTable createTable = new SQLCreateTable(root, "ARTICLE_ELEMENT");
561
        // createTable.addForeignColumn("ARTICLE");
562
        // createTable.addForeignColumn("ID_ARTICLE_PARENT", root.getTable("ARTICLE"));
563
        // createTable.addIntegerColumn("QTE", 1);
564
        // createTable.addDecimalColumn("QTE_UNITAIRE", 16, 6, BigDecimal.valueOf(1), false);
565
        // createTable.addForeignColumn("UNITE_VENTE");
566
        // insertUndef(createTable);
567
        // ds.execute(createTable.asString());
568
        //
569
        // root.getSchema().updateVersion();
570
        // root.refetchTable("ARTICLE_ELEMENT");
571
        //
572
        // }
573
        //
574
        // if (!root.getTable("ARTICLE").contains("COMPOSED")) {
575
        // AlterTable alterMvt = new AlterTable(root.getTable("ARTICLE"));
576
        // alterMvt.addBooleanColumn("COMPOSED", Boolean.FALSE, false);
577
        //
578
        // ds.execute(alterMvt.asString());
579
        //
580
        // root.getSchema().updateVersion();
581
        // }
582
 
583
    }
584
 
585
    private void createBanque(DBRoot root) throws SQLException {
586
 
93 ilm 587
        // Création de la table
83 ilm 588
        if (!root.contains("BANQUE") && !root.contains("BANQUE_POLE_PRODUIT")) {
589
 
590
            SQLCreateTable createBanque = new SQLCreateTable(root, "BANQUE");
591
            createBanque.addForeignColumn("ID_JOURNAL", root.findTable("JOURNAL", true));
592
            createBanque.addVarCharColumn("INFOS", 2048);
593
            createBanque.addVarCharColumn("NUMERO_RUE", 45);
594
            createBanque.addVarCharColumn("RUE", 256);
595
            createBanque.addVarCharColumn("IBAN", 256);
596
            createBanque.addVarCharColumn("BIC", 256);
597
            createBanque.addVarCharColumn("VOIE", 256);
598
            createBanque.addVarCharColumn("VILLE", 256);
599
            createBanque.addVarCharColumn("NOM", 256);
600
            createBanque.addVarCharColumn("DOMICILIATION", 256);
601
            createBanque.addVarCharColumn("CODE", 256);
602
            createBanque.addBooleanColumn("AFFACTURAGE", Boolean.FALSE, false);
603
            createBanque.addForeignColumn("ID_COMPTE_PCE", root.findTable("COMPTE_PCE", true));
604
 
605
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
606
 
607
            try {
608
                ds.execute(createBanque.asString());
609
 
610
                insertUndef(createBanque);
611
                root.refetchTable("BANQUE");
93 ilm 612
                root.getSchema().updateVersion();
83 ilm 613
 
93 ilm 614
            } catch (SQLException ex) {
615
                throw new IllegalStateException("Erreur lors de la création de la table BANQUE", ex);
616
            }
617
        }
83 ilm 618
 
93 ilm 619
        // Création des foreignkeys
620
        {
621
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
622
            List<String> tablesWithBanque = Arrays.asList("MODE_REGLEMENT", "CHEQUE_A_ENCAISSER", "CHEQUE_FOURNISSEUR");
83 ilm 623
 
93 ilm 624
            for (String string : tablesWithBanque) {
625
 
626
                final SQLTable table = root.getTable(string);
627
                if (!table.contains("ID_BANQUE") && !table.contains("ID_BANQUE_POLE_PRODUIT")) {
628
                    String tableName = (table.contains("ID_BANQUE_PRODUIT")) ? "BANQUE_POLE_PRODUIT" : "BANQUE";
629
                    AlterTable alterElt = new AlterTable(table);
630
                    alterElt.addForeignColumn("ID_" + tableName, root.getTable(tableName));
83 ilm 631
                    ds.execute(alterElt.asString());
93 ilm 632
                    root.refetchTable(string);
633
                    root.getSchema().updateVersion();
83 ilm 634
                }
635
            }
93 ilm 636
        }
83 ilm 637
 
638
    }
639
 
80 ilm 640
    private void createFactureFournisseur(DBRoot root) throws SQLException {
641
        boolean refetchRoot = false;
642
        if (!root.contains("FACTURE_FOURNISSEUR")) {
643
 
644
            SQLCreateTable createFactureF = new SQLCreateTable(root, "FACTURE_FOURNISSEUR");
645
            createFactureF.addVarCharColumn("NOM", 256);
646
            createFactureF.addVarCharColumn("NUMERO", 45);
647
            createFactureF.addVarCharColumn("INFOS", 2048);
648
            createFactureF.addColumn("DATE", "date");
649
            createFactureF.addForeignColumn("FOURNISSEUR");
650
            createFactureF.addForeignColumn("AVOIR_FOURNISSEUR");
651
            createFactureF.addForeignColumn("COMPTE_PCE");
652
            createFactureF.addForeignColumn("COMMERCIAL");
653
            createFactureF.addForeignColumn("MODE_REGLEMENT");
654
            createFactureF.addForeignColumn("MOUVEMENT");
655
            createFactureF.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
656
            createFactureF.addColumn("T_HT", "bigint DEFAULT 0");
657
            createFactureF.addColumn("T_TVA", "bigint DEFAULT 0");
658
            createFactureF.addColumn("T_TTC", "bigint DEFAULT 0");
659
            createFactureF.addColumn("T_SERVICE", "bigint DEFAULT 0");
660
            createFactureF.addColumn("T_DEVISE", "bigint DEFAULT 0");
661
            createFactureF.addColumn("T_POIDS", "real DEFAULT 0");
662
 
663
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
664
 
665
            try {
666
                ds.execute(createFactureF.asString());
667
                insertUndef(createFactureF);
668
                root.getSchema().updateVersion();
669
                root.refetchTable("FACTURE_FOURNISSEUR");
670
                refetchRoot = true;
671
            } catch (SQLException ex) {
672
                throw new IllegalStateException("Erreur lors de la création de la table FACTURE_FOURNISSEUR", ex);
673
            }
674
 
675
        }
676
 
677
        if (!root.contains("FACTURE_FOURNISSEUR_ELEMENT")) {
678
 
679
            SQLCreateTable createFactureF = new SQLCreateTable(root, "FACTURE_FOURNISSEUR_ELEMENT");
680
 
681
            createFactureF.addDecimalColumn("PRIX_METRIQUE_HA_1", 16, 6, BigDecimal.ZERO, false);
682
            createFactureF.addDecimalColumn("PRIX_METRIQUE_HA_2", 16, 6, BigDecimal.ZERO, false);
683
            createFactureF.addDecimalColumn("PRIX_METRIQUE_HA_3", 16, 6, BigDecimal.ZERO, false);
684
            createFactureF.addDecimalColumn("PRIX_METRIQUE_VT_1", 16, 6, BigDecimal.ZERO, false);
685
            createFactureF.addDecimalColumn("PRIX_METRIQUE_VT_2", 16, 6, BigDecimal.ZERO, false);
686
            createFactureF.addDecimalColumn("PRIX_METRIQUE_VT_3", 16, 6, BigDecimal.ZERO, false);
687
            createFactureF.addDecimalColumn("T_PV_HT", 16, 6, BigDecimal.ZERO, false);
688
            createFactureF.addDecimalColumn("T_PA_HT", 16, 6, BigDecimal.ZERO, false);
689
            createFactureF.addDecimalColumn("PV_HT", 16, 6, BigDecimal.ZERO, false);
690
            createFactureF.addDecimalColumn("PA_HT", 16, 6, BigDecimal.ZERO, false);
691
            createFactureF.addDecimalColumn("T_PV_TTC", 16, 6, BigDecimal.ZERO, false);
692
            createFactureF.addDecimalColumn("T_PA_TTC", 16, 6, BigDecimal.ZERO, false);
693
            createFactureF.addDecimalColumn("QTE_UNITAIRE", 16, 6, BigDecimal.ZERO, false);
694
            createFactureF.addDecimalColumn("PA_DEVISE_T", 16, 6, BigDecimal.ZERO, false);
695
            createFactureF.addDecimalColumn("PA_DEVISE", 16, 6, BigDecimal.ZERO, false);
696
            createFactureF.addIntegerColumn("QTE", 1);
697
            createFactureF.addIntegerColumn("QTE_ACHAT", 1);
698
 
699
            createFactureF.addColumn("VALEUR_METRIQUE_1", "real DEFAULT 0");
700
            createFactureF.addColumn("VALEUR_METRIQUE_2", "real DEFAULT 0");
701
            createFactureF.addColumn("VALEUR_METRIQUE_3", "real DEFAULT 0");
702
            createFactureF.addColumn("T_POIDS", "real DEFAULT 0");
703
            createFactureF.addColumn("POIDS", "real DEFAULT 0");
704
            createFactureF.addBooleanColumn("SERVICE", Boolean.FALSE, true);
705
            createFactureF.addVarCharColumn("CODE", 45);
706
            createFactureF.addVarCharColumn("NOM", 256);
707
            createFactureF.addColumn("DATE", "date");
708
            createFactureF.addForeignColumn("STYLE");
709
            createFactureF.addForeignColumn("METRIQUE", "3");
710
            createFactureF.addForeignColumn("METRIQUE", "2");
711
            createFactureF.addForeignColumn("METRIQUE", "1");
712
            createFactureF.addForeignColumn("FACTURE_FOURNISSEUR");
713
            createFactureF.addForeignColumn("TAXE");
714
            createFactureF.addForeignColumn("ID_MODE_VENTE_ARTICLE", root.findTable("MODE_VENTE_ARTICLE").getSQLName(), "ID", "5");
715
            createFactureF.addForeignColumn("UNITE_VENTE");
716
            createFactureF.addForeignColumn("ARTICLE");
717
            createFactureF.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
718
            createFactureF.addForeignColumn("CODE_FOURNISSEUR");
719
 
720
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
721
 
722
            try {
723
                ds.execute(createFactureF.asString());
724
                insertUndef(createFactureF);
725
                root.getSchema().updateVersion();
726
                refetchRoot = true;
727
            } catch (SQLException ex) {
728
                throw new IllegalStateException("Erreur lors de la création de la table FACTURE_FOURNISSEUR_ELEMENT", ex);
729
            }
730
 
731
        }
732
 
132 ilm 733
        if (root.contains("FACTURE_FOURNISSEUR_ELEMENT")) {
734
            addHAElementField(root.getTable("FACTURE_FOURNISSEUR_ELEMENT"), root);
735
        }
736
 
80 ilm 737
        if (!root.contains("REGLER_MONTANT_ELEMENT")) {
738
 
739
            SQLCreateTable createReglerElt = new SQLCreateTable(root, "REGLER_MONTANT_ELEMENT");
740
 
741
            createReglerElt.addForeignColumn("ECHEANCE_FOURNISSEUR");
742
            createReglerElt.addForeignColumn("REGLER_MONTANT");
743
            createReglerElt.addForeignColumn("MOUVEMENT", "ECHEANCE");
744
            createReglerElt.addColumn("DATE", "date");
745
            createReglerElt.addColumn("MONTANT_REGLE", "bigint DEFAULT 0");
746
            createReglerElt.addColumn("MONTANT_A_REGLER", "bigint DEFAULT 0");
747
 
748
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
749
 
750
            try {
751
                ds.execute(createReglerElt.asString());
752
                insertUndef(createReglerElt);
753
                root.getSchema().updateVersion();
754
                root.refetchTable("REGLER_MONTANT_ELEMENT");
755
                refetchRoot = true;
756
            } catch (SQLException ex) {
757
                throw new IllegalStateException("Erreur lors de la création de la table REGLER_MONTANT_ELEMENT", ex);
758
            }
759
 
760
        }
761
 
762
        final SQLTable tableReglerMontant = root.getTable("REGLER_MONTANT");
763
 
764
        boolean updateRegler = false;
765
 
766
        AlterTable alterElt = new AlterTable(tableReglerMontant);
767
        if (!tableReglerMontant.contains("ID_FOURNISSEUR")) {
768
            alterElt.addForeignColumn("ID_FOURNISSEUR", root.getTable("FOURNISSEUR"));
769
            updateRegler = true;
770
        }
771
 
772
        if (!tableReglerMontant.contains("NOM")) {
773
            alterElt.addVarCharColumn("NOM", 256);
774
            updateRegler = true;
775
        }
776
 
777
        if (updateRegler) {
778
            root.getDBSystemRoot().getDataSource().execute(alterElt.asString());
779
            root.refetchTable(tableReglerMontant.getName());
780
        }
781
 
782
        if (refetchRoot) {
783
            root.refetch();
784
        }
785
    }
786
 
25 ilm 787
    private void fixUnboundedNumeric(DBRoot root) throws SQLException {
788
 
789
        final List<AlterTable> alters = new ArrayList<AlterTable>();
73 ilm 790
        final List<UpdateBuilder> builds = new ArrayList<UpdateBuilder>();
25 ilm 791
        {
792
            SQLTable tableAvoir = root.getTable("AVOIR_CLIENT_ELEMENT");
793
            final AlterTable alter = new AlterTable(tableAvoir);
93 ilm 794
            if (tableAvoir.contains("POURCENT_ACOMPTE")) {
795
                SQLField fieldAcompteAvoir = tableAvoir.getField("POURCENT_ACOMPTE");
796
                if (fieldAcompteAvoir.getType().getSize() > 500) {
797
                    final String fName = fieldAcompteAvoir.getName();
798
                    alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "100", false);
73 ilm 799
 
93 ilm 800
                    UpdateBuilder build = new UpdateBuilder(tableAvoir);
801
                    build.set(fieldAcompteAvoir.getName(), "100");
802
                    build.setWhere(new Where(fieldAcompteAvoir, "=", (Object) null));
803
                    builds.add(build);
804
                }
25 ilm 805
            }
83 ilm 806
            if (tableAvoir.contains("POURCENT_REMISE")) {
807
                SQLField fieldRemiseAvoir = tableAvoir.getField("POURCENT_REMISE");
808
                if (fieldRemiseAvoir.getType().getSize() > 500) {
809
                    final String fName = fieldRemiseAvoir.getName();
810
                    alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "0", false);
73 ilm 811
 
83 ilm 812
                    UpdateBuilder build = new UpdateBuilder(tableAvoir);
813
                    build.set(fieldRemiseAvoir.getName(), "0");
814
                    build.setWhere(new Where(fieldRemiseAvoir, "=", (Object) null));
815
                    builds.add(build);
816
                }
25 ilm 817
            }
818
            if (!alter.isEmpty())
819
                alters.add(alter);
820
        }
821
 
822
        {
823
            SQLTable tableFacture = root.getTable("SAISIE_VENTE_FACTURE_ELEMENT");
824
            final AlterTable alter = new AlterTable(tableFacture);
93 ilm 825
            if (tableFacture.contains("POURCENT_ACOMPTE")) {
826
                SQLField fieldAcompteFacture = tableFacture.getField("POURCENT_ACOMPTE");
827
                if (fieldAcompteFacture.getType().getSize() > 500) {
828
                    final String fName = fieldAcompteFacture.getName();
829
                    alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "100", false);
73 ilm 830
 
93 ilm 831
                    UpdateBuilder build = new UpdateBuilder(tableFacture);
832
                    build.set(fieldAcompteFacture.getName(), "100");
833
                    build.setWhere(new Where(fieldAcompteFacture, "=", (Object) null));
834
                    builds.add(build);
835
                }
25 ilm 836
            }
837
 
93 ilm 838
            if (tableFacture.contains("POURCENT_REMISE")) {
839
                SQLField fieldRemiseFacture = tableFacture.getField("POURCENT_REMISE");
840
                if (fieldRemiseFacture.getType().getSize() > 500) {
841
                    final String fName = fieldRemiseFacture.getName();
842
                    alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "0", false);
73 ilm 843
 
93 ilm 844
                    UpdateBuilder build = new UpdateBuilder(tableFacture);
845
                    build.set(fieldRemiseFacture.getName(), "0");
846
                    build.setWhere(new Where(fieldRemiseFacture, "=", (Object) null));
847
                    builds.add(build);
848
                }
25 ilm 849
            }
850
            if (tableFacture.getFieldsName().contains("REPARTITION_POURCENT")) {
851
                SQLField fieldRepFacture = tableFacture.getField("REPARTITION_POURCENT");
852
                if (fieldRepFacture.getType().getSize() > 500) {
853
                    final String fName = fieldRepFacture.getName();
854
                    alter.alterColumn(fName, EnumSet.allOf(Properties.class), "numeric(6,2)", "0", false);
73 ilm 855
 
856
                    UpdateBuilder build = new UpdateBuilder(tableFacture);
857
                    build.set(fieldRepFacture.getName(), "0");
858
                    build.setWhere(new Where(fieldRepFacture, "=", (Object) null));
859
                    builds.add(build);
25 ilm 860
                }
861
            }
862
 
863
            if (!alter.isEmpty())
864
                alters.add(alter);
865
 
866
        }
867
        if (alters.size() > 0) {
868
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
73 ilm 869
 
870
            for (UpdateBuilder updateBuilder : builds) {
871
                ds.execute(updateBuilder.asString());
872
            }
873
 
25 ilm 874
            for (final String sql : ChangeTable.cat(alters, root.getName())) {
875
                ds.execute(sql);
876
            }
877
            root.refetch();
878
        }
879
    }
880
 
20 ilm 881
    private void fixUnboundedVarchar(DBRoot root) throws SQLException {
882
        final Set<String> namesSet = CollectionUtils.createSet("NOM", "PRENOM", "SURNOM", "LOGIN", "PASSWORD");
883
        final List<AlterTable> alters = new ArrayList<AlterTable>();
73 ilm 884
        final List<UpdateBuilder> builds = new ArrayList<UpdateBuilder>();
20 ilm 885
        for (final SQLTable t : root.getTables()) {
886
            final AlterTable alter = new AlterTable(t);
887
            for (final SQLField f : t.getFields()) {
156 ilm 888
                // on PG, CLOB are text and the JDBC driver returns Types.VARCHAR, not CLOB. So test
889
                // if the type name contains "char", since we only want unbounded varchar, not
890
                // text/clob.
891
                if (f.getType().getType() == Types.VARCHAR && f.getType().getSize() == Integer.MAX_VALUE && f.getTypeDecl().contains("char")) {
73 ilm 892
 
893
                    UpdateBuilder build = new UpdateBuilder(t);
156 ilm 894
                    build.setObject(f.getName(), "");
895
                    build.setWhere(Where.isNull(f));
73 ilm 896
                    builds.add(build);
897
 
20 ilm 898
                    final String fName = f.getName();
899
                    final int size;
80 ilm 900
                    if (t.getName().contains("USER") && namesSet.contains(fName))
21 ilm 901
                        size = 128;
20 ilm 902
                    else if (fName.equals("TEL") || fName.startsWith("TEL_"))
21 ilm 903
                        size = 32;
904
                    else if (fName.contains("INFO"))
80 ilm 905
                        size = 4096;
21 ilm 906
                    else if (fName.contains("FORMULE"))
907
                        size = 1024;
908
                    else if (fName.equals("CONTENU"))
909
                        size = 2048;
20 ilm 910
                    else
80 ilm 911
                        // e.g. IDCC.NOM > 350
151 ilm 912
                        size = 512;
20 ilm 913
                    alter.alterColumn(fName, EnumSet.allOf(Properties.class), "varchar(" + size + ")", "''", false);
914
                }
915
            }
916
            if (!alter.isEmpty())
917
                alters.add(alter);
918
        }
919
        if (alters.size() > 0) {
920
            final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
73 ilm 921
 
922
            for (UpdateBuilder build : builds) {
923
                ds.execute(build.asString());
924
            }
925
 
20 ilm 926
            for (final String sql : ChangeTable.cat(alters, root.getName())) {
151 ilm 927
                ds.execute(sql);
20 ilm 928
            }
929
            root.refetch();
930
        }
67 ilm 931
 
20 ilm 932
    }
933
 
67 ilm 934
    private void updateToV1Dot3(final DBRoot root) throws SQLException {
935
        final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
73 ilm 936
 
937
        addForeignKeyFactureOnEcheance(root);
80 ilm 938
        addFieldForPartialInvoice(root);
73 ilm 939
 
940
        // Numérotation client
941
        {
942
            SQLTable tableNum = root.getTable("NUMEROTATION_AUTO");
943
            boolean alterNum = false;
944
            AlterTable t = new AlterTable(tableNum);
945
            if (!tableNum.getFieldsName().contains("CLIENT_START")) {
946
                t.addColumn("CLIENT_START", "integer DEFAULT 0");
947
                alterNum = true;
948
            }
949
            if (!tableNum.getFieldsName().contains("CLIENT_FORMAT")) {
950
                t.addVarCharColumn("CLIENT_FORMAT", 48);
951
                alterNum = true;
952
            }
953
 
954
            if (alterNum) {
955
                try {
956
                    ds.execute(t.asString());
957
                    tableNum.getSchema().updateVersion();
958
                    tableNum.fetchFields();
959
                } catch (SQLException ex) {
960
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table NUMEROTATION_AUTO", ex);
961
                }
962
            }
963
        }
964
 
80 ilm 965
        // Eecheance founisseur
966
        {
967
            SQLTable tableEchF = root.getTable("ECHEANCE_FOURNISSEUR");
968
            AlterTable t = new AlterTable(tableEchF);
969
            if (!tableEchF.getFieldsName().contains("REG_COMPTA")) {
970
                t.addColumn("REG_COMPTA", "boolean DEFAULT false");
971
                try {
972
                    ds.execute(t.asString());
973
                    tableEchF.getSchema().updateVersion();
974
                    tableEchF.fetchFields();
975
                } catch (SQLException ex) {
976
                    throw new IllegalStateException("Erreur lors de l'ajout du champ REG_COMPTA sur la table ECHEANCE_FOUNISSEUR", ex);
977
                }
978
            }
979
        }
980
 
981
        SQLTable tableTaxe = root.getTable("TAXE");
982
        boolean containsTaxeDefault = tableTaxe.contains("DEFAULT");
983
        if (!containsTaxeDefault) {
984
            AlterTable t = new AlterTable(tableTaxe);
985
            t.addColumn("DEFAULT", "boolean DEFAULT false");
986
 
987
            try {
988
                ds.execute(t.asString());
989
                tableTaxe.getSchema().updateVersion();
990
                tableTaxe.fetchFields();
991
            } catch (SQLException ex) {
992
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table TAXE", ex);
993
            }
994
 
995
        }
996
 
997
        // Ajout de la TVA à 20
998
        SQLSelect selTVA = new SQLSelect();
999
        selTVA.addSelect(tableTaxe.getKey(), "COUNT");
1000
        selTVA.setWhere(new Where(tableTaxe.getField("TAUX"), "=", 20));
1001
        Object result = root.getBase().getDataSource().executeScalar(selTVA.asString());
1002
        if (result == null || ((Number) result).longValue() == 0) {
1003
            SQLRowValues rowVals = new SQLRowValues(tableTaxe);
1004
            rowVals.put("NOM", "TVA 20%");
1005
            rowVals.put("TAUX", Float.valueOf(20));
1006
            rowVals.put("DEFAULT", Boolean.TRUE);
1007
            rowVals.commit();
1008
        } else if (!containsTaxeDefault) {
1009
            SQLSelect selTVA20 = new SQLSelect();
1010
            selTVA20.addSelectStar(tableTaxe);
1011
            selTVA20.setWhere(new Where(tableTaxe.getField("TAUX"), "=", 20));
1012
            List<SQLRow> lTVA = SQLRowListRSH.execute(selTVA20);
1013
            if (lTVA != null && lTVA.size() > 0) {
1014
                SQLRowValues rowVals = lTVA.get(0).asRowValues();
1015
                rowVals.put("DEFAULT", Boolean.TRUE);
1016
                rowVals.update();
1017
            }
1018
 
1019
        }
1020
 
67 ilm 1021
        // Article
1022
        {
1023
            SQLTable tableProduct = root.getTable("ARTICLE");
1024
            boolean alterTableProduct = false;
1025
            AlterTable t = new AlterTable(tableProduct);
1026
            if (!tableProduct.getFieldsName().contains("ID_COMPTE_PCE")) {
1027
                t.addForeignColumn("ID_COMPTE_PCE", root.getTable("COMPTE_PCE"));
1028
                alterTableProduct = true;
1029
            }
1030
            if (!tableProduct.getFieldsName().contains("ID_COMPTE_PCE_ACHAT")) {
1031
                t.addForeignColumn("ID_COMPTE_PCE_ACHAT", root.getTable("COMPTE_PCE"));
1032
                alterTableProduct = true;
1033
            }
1034
            if (alterTableProduct) {
1035
                try {
1036
                    ds.execute(t.asString());
1037
                    tableProduct.getSchema().updateVersion();
1038
                    tableProduct.fetchFields();
1039
                } catch (SQLException ex) {
1040
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table ARTICLE", ex);
1041
                }
1042
            }
1043
        }
1044
 
1045
        // Famille Article
1046
        {
1047
            SQLTable tableArticleFamily = root.getTable("FAMILLE_ARTICLE");
1048
            boolean alterArticleFamily = false;
1049
            AlterTable t = new AlterTable(tableArticleFamily);
1050
            if (!tableArticleFamily.getFieldsName().contains("ID_COMPTE_PCE")) {
1051
                t.addForeignColumn("ID_COMPTE_PCE", root.getTable("COMPTE_PCE"));
1052
                alterArticleFamily = true;
1053
            }
1054
            if (!tableArticleFamily.getFieldsName().contains("ID_COMPTE_PCE_ACHAT")) {
1055
                t.addForeignColumn("ID_COMPTE_PCE_ACHAT", root.getTable("COMPTE_PCE"));
1056
                alterArticleFamily = true;
1057
            }
1058
            if (alterArticleFamily) {
1059
                try {
1060
                    ds.execute(t.asString());
1061
                    tableArticleFamily.getSchema().updateVersion();
1062
                    tableArticleFamily.fetchFields();
1063
                } catch (SQLException ex) {
1064
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table FAMILLE_ARTICLE", ex);
1065
                }
1066
            }
1067
        }
1068
 
1069
        // ECRITURE
1070
        {
1071
            SQLTable tableRecords = root.getTable("ECRITURE");
1072
            boolean alterRecords = false;
1073
            AlterTable t = new AlterTable(tableRecords);
1074
            if (!tableRecords.getFieldsName().contains("DATE_EXPORT")) {
1075
                t.addColumn("DATE_EXPORT", "date");
1076
                alterRecords = true;
1077
            }
1078
 
1079
            if (!tableRecords.getFieldsName().contains("CODE_CLIENT")) {
1080
                t.addVarCharColumn("CODE_CLIENT", 256);
1081
                alterRecords = true;
1082
            }
1083
            if (alterRecords) {
1084
                try {
1085
                    ds.execute(t.asString());
1086
                    tableRecords.getSchema().updateVersion();
1087
                    tableRecords.fetchFields();
1088
                } catch (SQLException ex) {
1089
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table ECRITURE", ex);
1090
                }
1091
            }
1092
        }
1093
        addInfoField(root, ds, "AVOIR_FOURNISSEUR");
1094
        addInfoField(root, ds, "AVOIR_CLIENT");
1095
 
1096
        boolean refetchRoot = false;
1097
        if (!root.contains("CODE_FOURNISSEUR")) {
1098
 
1099
            SQLCreateTable createCode = new SQLCreateTable(root, "CODE_FOURNISSEUR");
1100
            createCode.addVarCharColumn("CODE", 256);
1101
            createCode.addForeignColumn("FOURNISSEUR");
1102
            createCode.addForeignColumn("ARTICLE");
1103
            try {
1104
                ds.execute(createCode.asString());
1105
                insertUndef(createCode);
1106
                root.getSchema().updateVersion();
1107
                refetchRoot = true;
1108
            } catch (SQLException ex) {
1109
                throw new IllegalStateException("Erreur lors de la création de la table CODE_FOURNISSEUR", ex);
1110
            }
1111
 
1112
        }
1113
 
1114
        // Chargement des tables fraichement créées
1115
        if (refetchRoot)
1116
            root.refetch();
1117
 
80 ilm 1118
        createFactureFournisseur(root);
1119
 
67 ilm 1120
        addSupplierCode(root, ds, "BON_RECEPTION_ELEMENT");
1121
        addSupplierCode(root, ds, "COMMANDE_ELEMENT");
1122
 
1123
        // Undefined
1124
        SQLTable.setUndefID(root.getSchema(), "ARTICLE_DESIGNATION", 1);
1125
        SQLTable.setUndefID(root.getSchema(), "ARTICLE_TARIF", 1);
1126
        SQLTable.setUndefID(root.getSchema(), "CODE_STATUT_CAT_CONV", 1);
1127
        SQLTable.setUndefID(root.getSchema(), "CONTACT_ADMINISTRATIF", 1);
1128
        SQLTable.setUndefID(root.getSchema(), "CONTACT_FOURNISSEUR", 1);
1129
 
1130
        SQLTable.setUndefID(root.getSchema(), "LANGUE", 1);
1131
        SQLTable.setUndefID(root.getSchema(), "MODELE", 1);
1132
        SQLTable.setUndefID(root.getSchema(), "OBJECTIF_COMMERCIAL", 1);
1133
        SQLTable.setUndefID(root.getSchema(), "TARIF", 1);
1134
 
1135
        SQLTable.setUndefID(root.getSchema(), "UNITE_VENTE", 1);
73 ilm 1136
 
1137
        // Create transfer tables
1138
        ComptaPropsConfiguration.setSocieteSQLInjector(root);
1139
        SQLInjector.createTransferTables(root);
1140
        // Move transfer info to SAISIE_VENTE_FACTURE
1141
        convertTransfer(root, Arrays.asList("COMMANDE_CLIENT", "DEVIS", "BON_DE_LIVRAISON"), "SAISIE_VENTE_FACTURE");
83 ilm 1142
        // Fix keys
1143
        if (root.getServer().getSQLSystem().equals(SQLSystem.H2)) {
1144
            final ChangeIDToInt c = new ChangeIDToInt(root.getDBSystemRoot());
1145
            c.changeAll(root);
1146
            root.getDBSystemRoot().reload(Collections.singleton(root.getName()));
1147
        }
67 ilm 1148
    }
1149
 
73 ilm 1150
    private void convertTransfer(DBRoot root, List<String> tablesSrc, String tableDest) throws SQLException {
1151
        final SQLTable tableDestination = root.getTable(tableDest);
1152
        if (tableDestination.contains("SOURCE") && tableDestination.contains("IDSOURCE")) {
1153
            for (String tableSrc : tablesSrc) {
1154
                convertTransfer(root.getTable(tableSrc), tableDestination);
1155
            }
1156
            final AlterTable alter = new AlterTable(tableDestination);
1157
            alter.dropColumn("SOURCE");
1158
            alter.dropColumn("IDSOURCE");
1159
            final String req = alter.asString();
1160
            root.getDBSystemRoot().getDataSource().execute(req);
1161
            root.refetchTable(tableDest);
1162
        }
1163
    }
1164
 
1165
    private void convertTransfer(final SQLTable tableSource, final SQLTable tableDest) throws SQLException {
1166
        SQLInjector inj = SQLInjector.getInjector(tableSource, tableDest);
1167
        final SQLRowValues vals = new SQLRowValues(tableDest);
1168
        vals.putNulls("SOURCE", "IDSOURCE");
1169
        final SQLRowValuesListFetcher fetcher = new SQLRowValuesListFetcher(vals);
1170
        fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
1171
 
1172
            @Override
1173
            public SQLSelect transformChecked(SQLSelect input) {
1174
                Where w = new Where(tableDest.getField("SOURCE"), "=", tableSource.getName());
1175
                w = w.and(new Where(tableDest.getField("IDSOURCE"), "!=", tableSource.getUndefinedIDNumber()));
1176
                // remove archive idsource
1177
                w = w.and(new Where(tableDest.getField("IDSOURCE"), "=", tableSource.getKey()));
1178
                input.setWhere(w);
1179
                return input;
1180
            }
1181
        });
1182
        List<SQLRowValues> rows = fetcher.fetch();
1183
        for (SQLRowValues sqlRowValues : rows) {
1184
            inj.addTransfert(sqlRowValues.getInt("IDSOURCE"), sqlRowValues.getID());
1185
        }
1186
    }
1187
 
67 ilm 1188
    private void addInfoField(final DBRoot root, final SQLDataSource ds, String tableName) {
1189
        SQLTable tableBL = root.getTable(tableName);
1190
        boolean alterBL = false;
1191
        AlterTable t = new AlterTable(tableBL);
1192
        if (!tableBL.getFieldsName().contains("INFOS")) {
1193
            t.addVarCharColumn("INFOS", 1024);
1194
            alterBL = true;
1195
        }
1196
        if (alterBL) {
1197
            try {
1198
                ds.execute(t.asString());
1199
                tableBL.getSchema().updateVersion();
1200
                tableBL.fetchFields();
1201
            } catch (SQLException ex) {
1202
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table AVOIR FOURNISSEUR", ex);
1203
            }
1204
        }
1205
    }
1206
 
1207
    private void addSupplierCode(final DBRoot root, final SQLDataSource ds, String tableName) {
1208
        SQLTable tableBL = root.getTable(tableName);
1209
        boolean alterBL = false;
1210
        AlterTable t = new AlterTable(tableBL);
1211
        if (!tableBL.contains("ID_CODE_FOURNISSEUR")) {
1212
            t.addForeignColumn("ID_CODE_FOURNISSEUR", root.getTable("CODE_FOURNISSEUR"));
1213
            alterBL = true;
1214
        }
1215
        if (alterBL) {
1216
            try {
1217
                ds.execute(t.asString());
1218
                tableBL.getSchema().updateVersion();
1219
                tableBL.fetchFields();
1220
            } catch (SQLException ex) {
1221
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table " + tableName, ex);
1222
            }
1223
        }
1224
    }
1225
 
132 ilm 1226
    private void checkDepartementExists(DBRoot root, String dpt, String chefLieu, String regionAdmin, String numero) throws SQLException {
1227
        SQLSelect sel = new SQLSelect();
1228
        final SQLTable tableDpt = root.getTable("DEPARTEMENT");
1229
        sel.addSelect(tableDpt.getKey());
1230
        sel.addSelect(tableDpt.getField("NOM"));
1231
        Where w = new Where(tableDpt.getField("NOM"), "=", dpt);
1232
        sel.setWhere(w);
1233
        int result = SQLRowListRSH.execute(sel).size();
1234
        if (result == 0) {
1235
            SQLRowValues rowVals = new SQLRowValues(tableDpt);
1236
            rowVals.put("NOM", dpt);
1237
            rowVals.put("CHEF_LIEU", chefLieu);
1238
            rowVals.put("REGION_ADMIN", regionAdmin);
1239
            rowVals.put("NUMERO", numero);
1240
            rowVals.commit();
1241
        }
1242
    }
1243
 
83 ilm 1244
    private void updateToV1Dot4(final DBRoot root) throws SQLException {
93 ilm 1245
 
94 ilm 1246
        checkPrefsComptable(root);
132 ilm 1247
        checkDepartementExists(root, "Aisne", "Laon", "Picardie", "02");
94 ilm 1248
 
132 ilm 1249
        if (root.contains("TARIF_AGENCE")) {
156 ilm 1250
            SQLTable tableCmdFA = root.getTable("COMMANDE");
1251
            if (!tableCmdFA.contains("INCOTERM")) {
1252
                AlterTable t = new AlterTable(tableCmdFA);
1253
                t.addVarCharColumn("INCOTERM", 256);
1254
                tableCmdFA.getBase().getDataSource().execute(t.asString());
1255
                tableCmdFA.getSchema().updateVersion();
1256
                tableCmdFA.fetchFields();
1257
            }
132 ilm 1258
 
156 ilm 1259
            SQLTable tableArticleA = root.getTable("ARTICLE");
1260
            if (!tableArticleA.contains("CLOSED_KIT")) {
1261
                AlterTable t = new AlterTable(tableArticleA);
1262
                t.addBooleanColumn("CLOSED_KIT", Boolean.FALSE, true);
1263
                tableArticleA.getBase().getDataSource().execute(t.asString());
1264
                tableArticleA.getSchema().updateVersion();
1265
                tableArticleA.fetchFields();
1266
            }
1267
 
1268
            if (!tableArticleA.contains("CLOSED_KIT_DESC")) {
1269
                AlterTable t = new AlterTable(tableArticleA);
1270
                t.addVarCharColumn("CLOSED_KIT_DESC", 4096);
1271
                tableArticleA.getBase().getDataSource().execute(t.asString());
1272
                tableArticleA.getSchema().updateVersion();
1273
                tableArticleA.fetchFields();
1274
            }
1275
 
1276
            SQLTable tableCmdFEltA = root.getTable("COMMANDE_ELEMENT");
1277
            if (!tableCmdFEltA.contains("INCOTERM")) {
1278
                AlterTable t = new AlterTable(tableCmdFEltA);
1279
                t.addVarCharColumn("INCOTERM", 256);
1280
                tableCmdFEltA.getBase().getDataSource().execute(t.asString());
1281
                tableCmdFEltA.getSchema().updateVersion();
1282
                tableCmdFEltA.fetchFields();
1283
            }
1284
 
1285
            if (root.getTable("VILLE") == null) {
1286
 
1287
                // INSERT INTO "OpenConcerto49"."VILLE" ("CODE_POSTAL","NOM") SELECT
1288
                // "CODE_POSTAL",
1289
                // "VILLE" FROM "OpenConcerto49"."ADRESSE" a WHERE a."ARCHIVE"=0
1290
                final SQLCreateTable createTableVille = new SQLCreateTable(root, "VILLE");
1291
                createTableVille.addVarCharColumn("NOM", 2048);
1292
                createTableVille.addVarCharColumn("CODE_POSTAL", 2048);
1293
                createTableVille.addLongColumn("X_LAMBERT", 0L, true);
1294
                createTableVille.addLongColumn("Y_LAMBERT", 0L, true);
1295
                createTableVille.addLongColumn("POPULATION", 0L, true);
1296
                try {
1297
                    root.getBase().getDataSource().execute(createTableVille.asString());
1298
                    insertUndef(createTableVille);
1299
                    root.refetchTable("VILLE");
1300
                    root.getSchema().updateVersion();
1301
                } catch (SQLException ex2) {
1302
                    throw new IllegalStateException("Erreur lors de la création de la table " + "VILLE", ex2);
1303
                }
1304
            }
1305
 
1306
            if (root.getTable("ARTICLE_PRIX_MIN_VENTE") == null) {
1307
                final SQLCreateTable createTablePrixMin = new SQLCreateTable(root, "ARTICLE_PRIX_MIN_VENTE");
1308
                createTablePrixMin.addForeignColumn("ARTICLE");
1309
                createTablePrixMin.addIntegerColumn("QTE", 1);
1310
                createTablePrixMin.addDecimalColumn("PRIX", 16, 8, BigDecimal.ZERO, true);
1311
                createTablePrixMin.addDateAndTimeColumn("DATE");
1312
                try {
1313
                    root.getBase().getDataSource().execute(createTablePrixMin.asString());
1314
                    insertUndef(createTablePrixMin);
1315
                    root.refetchTable("ARTICLE_PRIX_MIN_VENTE");
1316
                    root.getSchema().updateVersion();
1317
                } catch (SQLException ex2) {
1318
                    throw new IllegalStateException("Erreur lors de la création de la table " + "ARTICLE_PRIX_MIN_VENTE", ex2);
1319
                }
1320
            }
1321
 
1322
            {
1323
                final SQLTable tableTarifAgence = root.getTable("TARIF_AGENCE");
1324
                AlterTable tTarifAgence = new AlterTable(tableTarifAgence);
1325
                boolean updateTarifAgence = false;
1326
 
1327
                if (!tableTarifAgence.contains("PRC_AGENCE")) {
1328
                    updateTarifAgence = true;
1329
                    tTarifAgence.addDecimalColumn("PRC_AGENCE", 16, 8, BigDecimal.ZERO, true);
1330
                }
1331
                if (!tableTarifAgence.contains("CLOSED_KIT")) {
1332
                    updateTarifAgence = true;
1333
                    tTarifAgence.addBooleanColumn("CLOSED_KIT", false, true);
1334
                }
1335
                if (!tableTarifAgence.contains("PRIX_MIN_VENTE")) {
1336
                    updateTarifAgence = true;
1337
                    tTarifAgence.addDecimalColumn("PRIX_MIN_VENTE", 16, 8, BigDecimal.ZERO, true);
1338
                }
1339
 
1340
                if (updateTarifAgence) {
1341
                    tableTarifAgence.getBase().getDataSource().execute(tTarifAgence.asString());
1342
                    tableTarifAgence.getSchema().updateVersion();
1343
                    tableTarifAgence.fetchFields();
1344
                }
1345
            }
1346
            {
1347
                final SQLTable tableClient = root.getTable("CLIENT");
1348
                AlterTable tClient = new AlterTable(tableClient);
1349
                boolean updateClient = false;
1350
 
1351
                if (!tableClient.contains("ALG_REGISTRE")) {
1352
                    updateClient = true;
1353
                    tClient.addVarCharColumn("ALG_REGISTRE", 512);
1354
                }
1355
                if (!tableClient.contains("ALG_MATRICULE")) {
1356
                    updateClient = true;
1357
                    tClient.addVarCharColumn("ALG_MATRICULE", 512);
1358
                }
1359
                if (!tableClient.contains("ALG_ARTICLE")) {
1360
                    updateClient = true;
1361
                    tClient.addVarCharColumn("ALG_ARTICLE", 512);
1362
                }
1363
 
1364
                if (updateClient) {
1365
                    tableClient.getBase().getDataSource().execute(tClient.asString());
1366
                    tableClient.getSchema().updateVersion();
1367
                    tableClient.fetchFields();
1368
                }
1369
            }
1370
            final SQLTable tableMvtStock = root.getTable("MOUVEMENT_STOCK");
1371
 
1372
            if (!tableMvtStock.contains("PRICE")) {
1373
                AlterTable tMvt = new AlterTable(tableMvtStock);
1374
                tMvt.addDecimalColumn("PRICE", 16, 6, BigDecimal.ZERO, true);
1375
                tableMvtStock.getBase().getDataSource().execute(tMvt.asString());
1376
                tableMvtStock.getSchema().updateVersion();
1377
                tableMvtStock.fetchFields();
1378
            }
1379
 
1380
            final SQLTable tableArticle = root.getTable("ARTICLE");
1381
 
1382
            if (!tableArticle.contains("AUTO_PRIX_MIN_VENTE_NOMENCLATURE")) {
1383
                AlterTable tArt = new AlterTable(tableArticle);
1384
                tArt.addBooleanColumn("AUTO_PRIX_MIN_VENTE_NOMENCLATURE", false, true);
1385
                tableMvtStock.getBase().getDataSource().execute(tArt.asString());
1386
                tableMvtStock.getSchema().updateVersion();
1387
                tableMvtStock.fetchFields();
1388
            }
1389
            SQLTable tableContact = root.getTable("CONTACT");
1390
            if (!tableContact.contains("TYPE")) {
1391
                AlterTable t = new AlterTable(tableContact);
1392
                t.addVarCharColumn("TYPE", 256);
1393
                t.addVarCharColumn("SERVICE", 256);
1394
                t.addVarCharColumn("PAYS", 256);
1395
                t.addForeignColumn("ID_ADRESSE", root.getTable("ADRESSE"));
1396
                tableContact.getBase().getDataSource().execute(t.asString());
1397
                tableContact.getSchema().updateVersion();
1398
                tableContact.fetchFields();
1399
            }
1400
 
1401
            if (!root.contains("PERSONNEL_AFHYMAT")) {
1402
                final SQLCreateTable createTablePers = new SQLCreateTable(root, "PERSONNEL_AFHYMAT");
1403
                createTablePers.addVarCharColumn("NOM", 256);
1404
                createTablePers.addVarCharColumn("PRENOM", 256);
1405
                createTablePers.addVarCharColumn("FONCTION", 256);
1406
 
1407
                try {
1408
                    root.getBase().getDataSource().execute(createTablePers.asString());
1409
                    insertUndef(createTablePers);
1410
                    root.refetchTable("PERSONNEL_AFHYMAT");
1411
                    root.getSchema().updateVersion();
1412
                } catch (SQLException ex) {
1413
                    throw new IllegalStateException("Erreur lors de la création de la table " + "PERSONNEL_AFHYMAT", ex);
1414
                }
1415
 
1416
                final SQLCreateTable createTable = new SQLCreateTable(root, "PERSONNEL_AFHYMAT_COUT");
1417
                for (int i = 1; i <= 12; i++) {
1418
                    createTable.addDecimalColumn("SAL_MONTH_" + i, 16, 2, BigDecimal.ZERO, false);
1419
                    createTable.addDecimalColumn("COM_MONTH_" + i, 16, 2, BigDecimal.ZERO, false);
1420
                }
1421
                createTable.addIntegerColumn("ANNEE", 0);
1422
                createTable.addForeignColumn("ID_PERSONNEL_AFHYMAT", root.getTable("PERSONNEL_AFHYMAT"));
1423
 
1424
                try {
1425
                    root.getBase().getDataSource().execute(createTable.asString());
1426
                    insertUndef(createTable);
1427
                    root.refetchTable("PERSONNEL_AFHYMAT_COUT");
1428
                    root.getSchema().updateVersion();
1429
                } catch (SQLException ex) {
1430
                    throw new IllegalStateException("Erreur lors de la création de la table " + "PERSONNEL_AFHYMAT_COUT", ex);
1431
                }
1432
            }
1433
 
132 ilm 1434
            List<String> tablesUiLocked = Arrays.asList("BON_DE_LIVRAISON", "COMMANDE_CLIENT", "SAISIE_VENTE_FACTURE", "AVOIR_CLIENT", "COMMANDE", "BON_RECEPTION", "FACTURE_FOURNISSEUR");
1435
            for (String tableName : tablesUiLocked) {
1436
                final SQLTable table = root.getTable(tableName);
1437
                AlterTable t = new AlterTable(table);
1438
                if (!table.contains("UI_LOCK")) {
1439
                    t.addVarCharColumn("UI_LOCK", 512);
1440
                    t.addForeignColumn("ID_USER_UI_LOCK", root.findTable("USER_COMMON"));
1441
                    table.getBase().getDataSource().execute(t.asString());
1442
                    table.getSchema().updateVersion();
1443
                    table.fetchFields();
1444
                }
1445
 
1446
            }
1447
 
1448
            if (!root.contains("RELIQUAT_BL")) {
1449
                final SQLCreateTable createTable = new SQLCreateTable(root, "RELIQUAT_BL");
1450
                createTable.addForeignColumn("ARTICLE");
1451
                createTable.addForeignColumn("ID_BON_DE_LIVRAISON_ORIGINE", root.getTable("BON_DE_LIVRAISON"));
1452
                createTable.addForeignColumn("ID_BON_DE_LIVRAISON", root.getTable("BON_DE_LIVRAISON"));
1453
                createTable.addForeignColumn("ID_BON_DE_LIVRAISON_ELEMENT", root.getTable("BON_DE_LIVRAISON_ELEMENT"));
1454
                createTable.addIntegerColumn("QTE", 1);
1455
                createTable.addDecimalColumn("QTE_UNITAIRE", 16, 6, BigDecimal.valueOf(1), false);
1456
                createTable.addForeignColumn("UNITE_VENTE");
1457
 
1458
                try {
1459
                    root.getBase().getDataSource().execute(createTable.asString());
1460
                    insertUndef(createTable);
1461
                    root.refetchTable("RELIQUAT_BL");
1462
                    root.getSchema().updateVersion();
1463
                } catch (SQLException ex) {
1464
                    throw new IllegalStateException("Erreur lors de la création de la table " + "RELIQUAT_BL", ex);
1465
                }
1466
            }
1467
 
1468
            if (!root.getTable("ARTICLE").contains("TRANSPORT")) {
1469
                AlterTable alterArticle = new AlterTable(tableArticle);
1470
                alterArticle.addBooleanColumn("TRANSPORT", false, false);
1471
                tableArticle.getBase().getDataSource().execute(alterArticle.asString());
1472
                tableArticle.getSchema().updateVersion();
1473
                tableArticle.fetchFields();
1474
            }
1475
 
1476
            if (!root.contains("RELIQUAT_BR")) {
1477
                final SQLCreateTable createTable = new SQLCreateTable(root, "RELIQUAT_BR");
1478
                createTable.addForeignColumn("ARTICLE");
1479
                createTable.addForeignColumn("ID_BON_RECEPTION_ORIGINE", root.getTable("BON_RECEPTION"));
1480
                createTable.addForeignColumn("ID_BON_RECEPTION", root.getTable("BON_RECEPTION"));
1481
                createTable.addForeignColumn("ID_BON_RECEPTION_ELEMENT", root.getTable("BON_RECEPTION_ELEMENT"));
1482
                createTable.addIntegerColumn("QTE", 1);
1483
                createTable.addDecimalColumn("QTE_UNITAIRE", 16, 6, BigDecimal.valueOf(1), false);
1484
                createTable.addForeignColumn("UNITE_VENTE");
1485
 
1486
                try {
1487
                    root.getBase().getDataSource().execute(createTable.asString());
1488
                    insertUndef(createTable);
1489
                    root.refetchTable("RELIQUAT_BL");
1490
                    root.getSchema().updateVersion();
1491
                } catch (SQLException ex) {
1492
                    throw new IllegalStateException("Erreur lors de la création de la table " + "RELIQUAT_BR", ex);
1493
                }
1494
            }
1495
 
1496
            {
1497
                if (root.getName().endsWith("54")) {
1498
                    AlterTable tArt = new AlterTable(tableArticle);
1499
                    if (!tableArticle.contains("LABEL_DOUANE")) {
1500
                        tArt.addVarCharColumn("LABEL_DOUANE", 512);
1501
                        tableArticle.getBase().getDataSource().execute(tArt.asString());
1502
                        tableArticle.getSchema().updateVersion();
1503
                        tableArticle.fetchFields();
1504
                    }
1505
                }
1506
            }
1507
 
1508
            {
1509
                final SQLTable tableFour = root.getTable("FOURNISSEUR");
1510
                AlterTable tFour = new AlterTable(tableFour);
1511
                boolean updateFour = false;
1512
 
1513
                if (!tableFour.contains("ALG_REGISTRE")) {
1514
                    updateFour = true;
1515
                    tFour.addVarCharColumn("ALG_REGISTRE", 512);
1516
                }
1517
                if (!tableFour.contains("ALG_MATRICULE")) {
1518
                    updateFour = true;
1519
                    tFour.addVarCharColumn("ALG_MATRICULE", 512);
1520
                }
1521
                if (!tableFour.contains("ALG_ARTICLE")) {
1522
                    updateFour = true;
1523
                    tFour.addVarCharColumn("ALG_ARTICLE", 512);
1524
                }
1525
 
1526
                if (updateFour) {
1527
                    tableFour.getBase().getDataSource().execute(tFour.asString());
1528
                    tableFour.getSchema().updateVersion();
1529
                    tableFour.fetchFields();
1530
                }
1531
            }
1532
 
1533
        }
1534
 
1535
        if (root.getTable("COEFF_PRIME") == null) {
1536
            final SQLCreateTable createTable = new SQLCreateTable(root, "COEFF_PRIME");
1537
            // TODO numeric to real
1538
            createTable.addColumn("PRIME_PERSO", "real DEFAULT 0");
1539
            createTable.addColumn("PRIME_RECONSTRUCTION", "real DEFAULT 0");
1540
            createTable.addColumn("PRIME_ANCIENNETE", "real DEFAULT 0");
1541
            createTable.addColumn("PRIME_DEROULEMENT", "real DEFAULT 0");
1542
 
1543
            try {
1544
                root.getDBSystemRoot().getDataSource().execute(createTable.asString());
1545
                insertUndef(createTable);
1546
                root.refetchTable("COEFF_PRIME");
1547
                root.getSchema().updateVersion();
1548
            } catch (SQLException ex) {
1549
                throw new IllegalStateException("Erreur lors de la création de la table " + "COEFF_PRIME", ex);
1550
            }
1551
 
1552
            SQLTable tableInfosSal = root.getTable("INFOS_SALARIE_PAYE");
1553
            if (!tableInfosSal.contains("ID_COEFF_PRIME")) {
1554
                AlterTable t = new AlterTable(tableInfosSal);
1555
                t.addForeignColumn("ID_COEFF_PRIME", root.getTable("COEFF_PRIME"));
1556
 
1557
                try {
1558
 
1559
                    tableInfosSal.getBase().getDataSource().execute(t.asString());
1560
                    tableInfosSal.getSchema().updateVersion();
1561
                    tableInfosSal.fetchFields();
1562
                } catch (SQLException ex) {
1563
                    throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + tableInfosSal.getName(), ex);
1564
                }
1565
            }
1566
        }
1567
 
142 ilm 1568
        SQLTable tableInfosSal = root.getTable("INFOS_SALARIE_PAYE");
1569
        if (!tableInfosSal.contains("ID_SALARIE")) {
1570
            // Ajout INFOS_SALARIE_PAYE.ID_SALARIE
1571
            AlterTable t = new AlterTable(tableInfosSal);
1572
            t.addForeignColumn("ID_SALARIE", root.getTable("SALARIE"));
1573
 
1574
            try {
1575
 
1576
                tableInfosSal.getBase().getDataSource().execute(t.asString());
1577
                tableInfosSal.getSchema().updateVersion();
1578
                tableInfosSal.fetchFields();
1579
            } catch (SQLException ex) {
1580
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + tableInfosSal.getName(), ex);
1581
            }
1582
 
1583
            // Ajout CONTRAT.DEBUT_CONTRAT
1584
            SQLTable tableContrat = root.getTable("CONTRAT_SALARIE");
1585
            AlterTable tContrat = new AlterTable(tableContrat);
1586
            tContrat.addDateAndTimeColumn("DATE_DEBUT");
1587
            tContrat.addDateAndTimeColumn("DATE_MODIFICATION");
1588
            // tContrat.addForeignColumn("ID_INFOS_SALARIE_PAYE_MODIFIE", tableInfosSal);
1589
            try {
1590
                tableContrat.getBase().getDataSource().execute(tContrat.asString());
1591
                tableContrat.getSchema().updateVersion();
1592
                tableContrat.fetchFields();
1593
            } catch (SQLException ex) {
1594
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + tableContrat.getName(), ex);
1595
            }
1596
 
1597
            // Ajout FICHE_PAYE.INFOS_SALARIE_PAYE
1598
            SQLTable tableFichePaye = root.getTable("FICHE_PAYE");
1599
            AlterTable tFicheSal = new AlterTable(tableFichePaye);
1600
            tFicheSal.addForeignColumn("ID_INFOS_SALARIE_PAYE", root.getTable("INFOS_SALARIE_PAYE"));
1601
            try {
1602
 
1603
                tableFichePaye.getBase().getDataSource().execute(tFicheSal.asString());
1604
                tableFichePaye.getSchema().updateVersion();
1605
                tableFichePaye.fetchFields();
1606
            } catch (SQLException ex) {
1607
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + tableFichePaye.getName(), ex);
1608
            }
1609
 
1610
            {
1611
                // Mise à jour des dates de début de contrat
1612
                UpdateBuilder builderContrat = new UpdateBuilder(tableContrat);
1613
                builderContrat.addBackwardVirtualJoin(tableInfosSal, "ID_CONTRAT_SALARIE");
1614
                builderContrat.setFromVirtualJoinField("DATE_DEBUT", tableInfosSal.getAlias(), "DATE_ARRIVE");
1615
                tableInfosSal.getDBSystemRoot().getDataSource().execute(builderContrat.asString());
1616
            }
1617
            {
1618
                // Mise à jour des INFOS_SALARIE_PAYE dans les fiches
1619
                SQLTable tableSalarie = root.getTable("SALARIE");
1620
                UpdateBuilder builderFiche = new UpdateBuilder(tableFichePaye);
1621
                builderFiche.addForwardVirtualJoin(tableSalarie, "ID_SALARIE");
1622
                builderFiche.setFromVirtualJoinField("ID_INFOS_SALARIE_PAYE", tableSalarie.getAlias(), "ID_INFOS_SALARIE_PAYE");
1623
                tableInfosSal.getDBSystemRoot().getDataSource().execute(builderFiche.asString());
1624
            }
1625
        }
1626
 
132 ilm 1627
        // Cumuls paye
1628
        SQLTable tableCumulsPaye = root.getTable("CUMULS_PAYE");
1629
 
1630
        AlterTable tCumuls = new AlterTable(tableCumulsPaye);
1631
        tCumuls.alterColumn("NET_IMP_C", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1632
        tCumuls.alterColumn("COT_PAT_C", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1633
        tCumuls.alterColumn("COT_SAL_C", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1634
        tCumuls.alterColumn("SAL_BRUT_C", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1635
        tCumuls.alterColumn("NET_A_PAYER_C", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1636
        tCumuls.alterColumn("CSG_C", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
142 ilm 1637
        if (tableCumulsPaye.contains("HEURE_TRAV") && !tableCumulsPaye.contains("HEURE_TRAV_C")) {
1638
 
1639
            AlterTable tColumnNameCumuls = new AlterTable(tableCumulsPaye);
1640
 
1641
            tColumnNameCumuls.addClause(new DeferredClause() {
1642
                @Override
1643
                public String asString(ChangeTable<?> ct, SQLName tableName) {
1644
                    return (root.getServer().getSQLSystem() == SQLSystem.POSTGRESQL ? "RENAME COLUMN \"HEURE_TRAV\" TO \"HEURE_TRAV_C\"" : "ALTER COLUMN \"HEURE_TRAV\" RENAME TO \"HEURE_TRAV_C\"");
1645
                }
1646
 
1647
                @Override
1648
                public ClauseType getType() {
1649
                    return ClauseType.OTHER;
1650
                }
1651
            });
1652
            try {
1653
 
1654
                tableCumulsPaye.getBase().getDataSource().execute(tColumnNameCumuls.asString());
1655
                tableCumulsPaye.getSchema().updateVersion();
1656
                tableCumulsPaye.fetchFields();
1657
            } catch (SQLException ex) {
1658
                throw new IllegalStateException("Erreur lors de la modification du champ de la table " + tableCumulsPaye.getName(), ex);
1659
            }
1660
        } else if (!tableCumulsPaye.contains("HEURE_TRAV_C")) {
1661
            tCumuls.addDecimalColumn("HEURE_TRAV_C", 16, 2, BigDecimal.ZERO, false);
132 ilm 1662
        }
142 ilm 1663
 
132 ilm 1664
        try {
1665
 
1666
            tableCumulsPaye.getBase().getDataSource().execute(tCumuls.asString());
1667
            tableCumulsPaye.getSchema().updateVersion();
1668
            tableCumulsPaye.fetchFields();
1669
        } catch (SQLException ex) {
1670
            throw new IllegalStateException("Erreur lors de la modification des champs de la table " + tableCumulsPaye.getName(), ex);
1671
        }
1672
 
1673
        // element paye
1674
        SQLTable tableElementPaye = root.getTable("FICHE_PAYE_ELEMENT");
1675
 
1676
        AlterTable tEltPaye = new AlterTable(tableElementPaye);
1677
        tEltPaye.alterColumn("TAUX_PAT", EnumSet.allOf(Properties.class), "numeric(16,6)", "0", true);
1678
        tEltPaye.alterColumn("MONTANT_SAL_AJ", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1679
        tEltPaye.alterColumn("TAUX_SAL", EnumSet.allOf(Properties.class), "numeric(16,6)", "0", true);
1680
        tEltPaye.alterColumn("MONTANT_SAL_DED", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1681
        tEltPaye.alterColumn("MONTANT_PAT", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1682
        tEltPaye.alterColumn("NB_BASE", EnumSet.allOf(Properties.class), "numeric(16,6)", "0", true);
1683
 
1684
        try {
1685
 
1686
            tableElementPaye.getBase().getDataSource().execute(tEltPaye.asString());
1687
            tableElementPaye.getSchema().updateVersion();
1688
            tableElementPaye.fetchFields();
1689
        } catch (SQLException ex) {
1690
            throw new IllegalStateException("Erreur lors de la modification des champs de la table " + tableElementPaye.getName(), ex);
1691
        }
1692
 
1693
        // paye
1694
        SQLTable tablePaye = root.getTable("FICHE_PAYE");
1695
 
1696
        AlterTable tPaye = new AlterTable(tablePaye);
1697
        tPaye.alterColumn("ACOMPTE", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1698
        tPaye.alterColumn("NET_IMP", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1699
        tPaye.alterColumn("COT_PAT", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1700
        tPaye.alterColumn("NET_A_PAYER", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1701
        tPaye.alterColumn("SAL_BRUT", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1702
        tPaye.alterColumn("CSG", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1703
        tPaye.alterColumn("COT_SAL", EnumSet.allOf(Properties.class), "numeric(16,2)", "0", true);
1704
 
1705
        try {
1706
            tablePaye.getBase().getDataSource().execute(tPaye.asString());
1707
            tablePaye.getSchema().updateVersion();
1708
            tablePaye.fetchFields();
1709
        } catch (SQLException ex) {
1710
            throw new IllegalStateException("Erreur lors de la modification des champs de la table " + tablePaye.getName(), ex);
1711
        }
1712
 
1713
        if (root.getTable("ARTICLE_ELEMENT") == null) {
1714
            final SQLCreateTable createTable = new SQLCreateTable(root, "ARTICLE_ELEMENT");
1715
            createTable.addForeignColumn("ARTICLE");
1716
            createTable.addForeignColumn("ID_ARTICLE_PARENT", root.getTable("ARTICLE"));
1717
            createTable.addIntegerColumn("QTE", 1);
1718
            createTable.addDecimalColumn("QTE_UNITAIRE", 16, 6, BigDecimal.valueOf(1), false);
1719
            createTable.addForeignColumn("UNITE_VENTE");
1720
            try {
1721
                root.getBase().getDataSource().execute(createTable.asString());
1722
                insertUndef(createTable);
1723
                root.refetchTable("ARTICLE_ELEMENT");
1724
                root.getSchema().updateVersion();
1725
            } catch (SQLException ex) {
1726
                throw new IllegalStateException("Erreur lors de la création de la table " + "ARTICLE_ELEMENT", ex);
1727
            }
1728
        }
1729
 
1730
        if (root.getTable("VILLE") == null) {
1731
            final SQLCreateTable createTable = new SQLCreateTable(root, "VILLE");
1732
            createTable.addLongColumn("X_LAMBERT", 0L, true);
1733
            createTable.addLongColumn("Y_LAMBERT", 0L, true);
1734
            createTable.addLongColumn("POPULATION", 0L, true);
1735
            createTable.addVarCharColumn("NOM", 512);
1736
            createTable.addVarCharColumn("CODE_POSTAL", 256);
1737
            try {
1738
                root.getBase().getDataSource().execute(createTable.asString());
1739
                insertUndef(createTable);
1740
                root.refetchTable("VILLE");
1741
                root.getSchema().updateVersion();
1742
            } catch (SQLException ex) {
1743
                throw new IllegalStateException("Erreur lors de la création de la table " + "VILLE", ex);
1744
            }
1745
        }
1746
 
94 ilm 1747
        // Gestion des différentes numérotation
1748
        if (!root.getTable("NUMEROTATION_AUTO").contains("NOM")) {
132 ilm 1749
            final SQLTable tableNum = root.getTable("NUMEROTATION_AUTO");
1750
            AlterTable tNum = new AlterTable(tableNum);
94 ilm 1751
            tNum.addColumn("NOM", "varchar (256)", "'Standard'", true);
1752
 
1753
            root.getBase().getDataSource().execute(tNum.asString());
132 ilm 1754
            tableNum.fetchFields();
94 ilm 1755
            root.getSchema().updateVersion();
132 ilm 1756
 
94 ilm 1757
        }
1758
 
1759
        // Gestion du timbre fiscal
1760
        if (!root.getTable("CLIENT").contains("TIMBRE_FISCAL")) {
1761
            AlterTable tClient = new AlterTable(root.getTable("CLIENT"));
1762
            tClient.addBooleanColumn("TIMBRE_FISCAL", Boolean.FALSE, false);
1763
            root.getBase().getDataSource().execute(tClient.asString());
1764
            root.getSchema().updateVersion();
1765
        }
132 ilm 1766
        // Obsolete
1767
        if (!root.getTable("CLIENT").contains("OBSOLETE")) {
1768
            AlterTable tClient = new AlterTable(root.getTable("CLIENT"));
1769
            tClient.addBooleanColumn("OBSOLETE", Boolean.FALSE, false);
1770
            root.getBase().getDataSource().execute(tClient.asString());
1771
            root.getSchema().updateVersion();
1772
        }
94 ilm 1773
 
132 ilm 1774
        // Relance
1775
        if (!root.getTable("RELANCE").contains("ID_ECHEANCE_CLIENT")) {
1776
            AlterTable tRelance = new AlterTable(root.getTable("RELANCE"));
1777
            tRelance.addForeignColumn("ID_ECHEANCE_CLIENT", root.getTable("ECHEANCE_CLIENT"));
1778
            root.getBase().getDataSource().execute(tRelance.asString());
1779
            root.getSchema().updateVersion();
1780
        }
1781
 
1782
        if (!root.getTable("AVOIR_CLIENT_ELEMENT").contains("RETOUR_STOCK")) {
1783
            final SQLTable tableAvoirElt = root.getTable("AVOIR_CLIENT_ELEMENT");
1784
            AlterTable tAvoir = new AlterTable(tableAvoirElt);
1785
            tAvoir.addBooleanColumn("RETOUR_STOCK", Boolean.FALSE, false);
1786
            root.getBase().getDataSource().execute(tAvoir.asString());
1787
            root.getSchema().updateVersion();
1788
            tableAvoirElt.fetchFields();
1789
        }
1790
 
94 ilm 1791
        final SQLTable tableVenteFacture = root.getTable("SAISIE_VENTE_FACTURE");
1792
        AlterTable tFacture = new AlterTable(tableVenteFacture);
1793
        boolean alterFacture = false;
1794
        boolean upNET = false;
1795
        if (!tableVenteFacture.contains("SOUMIS_TIMBRE_FISCAL")) {
1796
            tFacture.addBooleanColumn("SOUMIS_TIMBRE_FISCAL", Boolean.FALSE, true);
1797
            alterFacture = true;
1798
        }
1799
        if (!tableVenteFacture.contains("TAUX_TIMBRE_FISCAL")) {
1800
            tFacture.addDecimalColumn("TAUX_TIMBRE_FISCAL", 16, 4, BigDecimal.ONE, true);
1801
            alterFacture = true;
1802
        }
1803
        if (!tableVenteFacture.contains("TOTAL_TIMBRE_FISCAL")) {
1804
            tFacture.addLongColumn("TOTAL_TIMBRE_FISCAL", 0L, true);
1805
            alterFacture = true;
1806
        }
1807
        if (!tableVenteFacture.contains("NET_A_PAYER")) {
1808
            tFacture.addLongColumn("NET_A_PAYER", 0L, true);
1809
            alterFacture = true;
1810
            upNET = true;
1811
        }
1812
        if (alterFacture) {
1813
            root.getBase().getDataSource().execute(tFacture.asString());
1814
            root.getSchema().updateVersion();
1815
            tableVenteFacture.fetchFields();
1816
            if (upNET) {
1817
                String req = "UPDATE " + tableVenteFacture.getSQLName().quote() + " SET \"NET_A_PAYER\"=(\"T_TTC\"-\"T_AVOIR_TTC\")";
1818
                root.getBase().getDataSource().execute(req);
1819
            }
1820
        }
1821
 
1822
        SQLTable tableTaxe = root.getTable("TAXE");
1823
        boolean updateTaxe = false;
1824
        AlterTable tTaxe = new AlterTable(tableTaxe);
1825
        if (!tableTaxe.contains("ID_COMPTE_PCE_VENTE")) {
1826
            tTaxe.addForeignColumn("ID_COMPTE_PCE_VENTE", root.getTable("COMPTE_PCE"));
1827
            updateTaxe = true;
1828
        }
1829
        if (!tableTaxe.contains("ID_COMPTE_PCE_VENTE_SERVICE")) {
1830
            tTaxe.addForeignColumn("ID_COMPTE_PCE_VENTE_SERVICE", root.getTable("COMPTE_PCE"));
1831
            updateTaxe = true;
1832
        }
1833
 
1834
        if (updateTaxe) {
1835
            try {
1836
                tableTaxe.getBase().getDataSource().execute(tTaxe.asString());
1837
                tableTaxe.getSchema().updateVersion();
1838
                tableTaxe.fetchFields();
1839
            } catch (SQLException ex) {
1840
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table TAXE", ex);
1841
            }
1842
 
1843
        }
1844
 
1845
        // Tarification par quantite
1846
        if (root.getTable("TARIF_QUANTITE") == null) {
1847
            final SQLCreateTable createTableQtyTarif = new SQLCreateTable(root, "TARIF_QUANTITE");
1848
            createTableQtyTarif.addForeignColumn("ID_ARTICLE", root.getTable("ARTICLE"));
1849
            createTableQtyTarif.addDecimalColumn("QUANTITE", 16, 3, BigDecimal.ONE, false);
1850
            createTableQtyTarif.addDecimalColumn("POURCENT_REMISE", 16, 3, null, true);
1851
            createTableQtyTarif.addDecimalColumn("PRIX_METRIQUE_VT_1", 16, 6, null, true);
1852
            try {
1853
                root.getBase().getDataSource().execute(createTableQtyTarif.asString());
1854
                insertUndef(createTableQtyTarif);
1855
                root.refetchTable("TARIF_QUANTITE");
1856
                root.getSchema().updateVersion();
1857
            } catch (SQLException ex) {
1858
                throw new IllegalStateException("Erreur lors de la création de la table " + "TARIF_QUANTITE", ex);
1859
            }
1860
        }
1861
        // Articles fournisseurs
1862
        addArticleFournisseur(root);
1863
 
1864
        SQLTable tableCmdF = root.getTable("COMMANDE");
1865
        if (!tableCmdF.contains("ID_MODELE")) {
1866
            AlterTable t = new AlterTable(tableCmdF);
1867
            t.addForeignColumn("ID_MODELE", root.getTable("MODELE"));
1868
            tableCmdF.getBase().getDataSource().execute(t.asString());
1869
            tableCmdF.getSchema().updateVersion();
1870
            tableCmdF.fetchFields();
1871
        }
1872
 
1873
        SQLTable tableArtF = root.getTable("ARTICLE_FOURNISSEUR");
1874
        if (!tableArtF.contains("ID_FAMILLE_ARTICLE")) {
1875
            AlterTable t = new AlterTable(tableArtF);
1876
            t.addForeignColumn("ID_FAMILLE_ARTICLE", root.getTable("FAMILLE_ARTICLE"));
1877
            tableArtF.getBase().getDataSource().execute(t.asString());
1878
            tableArtF.getSchema().updateVersion();
1879
            tableArtF.fetchFields();
1880
        }
1881
 
1882
        if (!tableCmdF.contains("DATE_RECEPTION_DEMANDEE")) {
1883
            AlterTable t = new AlterTable(tableCmdF);
1884
            t.addColumn("DATE_RECEPTION_DEMANDEE", "date");
1885
            t.addColumn("DATE_RECEPTION_CONFIRMEE", "date");
1886
            tableCmdF.getBase().getDataSource().execute(t.asString());
1887
            tableCmdF.getSchema().updateVersion();
1888
            tableCmdF.fetchFields();
1889
        }
1890
 
1891
        SQLTable tableEcr = root.getTable("ECRITURE");
1892
        if (!tableEcr.contains("NOM_PIECE")) {
1893
            AlterTable t = new AlterTable(tableEcr);
1894
            t.addVarCharColumn("NOM_PIECE", 1024);
1895
            tableEcr.getBase().getDataSource().execute(t.asString());
1896
            tableEcr.getSchema().updateVersion();
1897
            tableEcr.fetchFields();
1898
        }
1899
 
1900
        SQLTable tableKm = root.getTable("SAISIE_KM_ELEMENT");
1901
        if (!tableKm.contains("NOM_PIECE")) {
1902
            AlterTable t = new AlterTable(tableKm);
1903
            t.addVarCharColumn("NOM_PIECE", 1024);
1904
 
1905
            tableKm.getBase().getDataSource().execute(t.asString());
1906
            tableKm.getSchema().updateVersion();
1907
            tableKm.fetchFields();
1908
        }
1909
 
1910
        {
1911
            SQLSelect sel = new SQLSelect();
1912
            final SQLTable tableStyle = root.getTable("STYLE");
1913
            sel.addSelect(tableStyle.getKey());
1914
            sel.setWhere(new Where(tableStyle.getField("NOM"), "=", "Composant"));
1915
            String req = sel.asString();
1916
            List<Map<String, Object>> l = root.getDBSystemRoot().getDataSource().execute(req);
1917
 
1918
            if (l.size() == 0) {
1919
                SQLRowValues rowValsStyle = new SQLRowValues(tableStyle);
1920
                rowValsStyle.put("NOM", "Composant");
1921
                rowValsStyle.put("CODE", "COMP");
1922
                rowValsStyle.insert();
1923
            }
1924
        }
1925
 
1926
        {
1927
            // Fix qté et style
1928
            List<String> tableElt = Arrays.asList("AVOIR_CLIENT_ELEMENT", "BON_DE_LIVRAISON_ELEMENT", "BON_RECEPTION_ELEMENT", "COMMANDE_CLIENT_ELEMENT", "COMMANDE_ELEMENT", "DEVIS_ELEMENT",
1929
                    "SAISIE_VENTE_FACTURE_ELEMENT");
1930
            for (String string : tableElt) {
1931
                final SQLTable table = root.getTable(string);
1932
                Number undefined = table.getUndefinedIDNumber();
1933
                if (undefined != null && undefined.intValue() > 0) {
1934
                    UpdateBuilder build = new UpdateBuilder(table);
1935
                    build.setObject("ID_STYLE", 2);
1936
                    build.setObject("QTE", 1);
1937
                    build.setWhere(new Where(table.getKey(), "=", undefined.intValue()));
1938
                    table.getDBSystemRoot().getDataSource().execute(build.asString());
1939
                }
1940
            }
1941
        }
1942
 
93 ilm 1943
        // ADresse de livraison et remise
1944
        {
1945
            SQLTable tableDevis = root.getTable("DEVIS");
1946
            addAdresseField(tableDevis, root);
1947
            addRemiseField(tableDevis, root);
1948
 
1949
            SQLTable tableVF = root.getTable("SAISIE_VENTE_FACTURE");
1950
            addAdresseField(tableVF, root);
1951
            addRemiseField(tableVF, root);
1952
 
1953
            SQLTable tableCmd = root.getTable("COMMANDE_CLIENT");
1954
            addAdresseField(tableCmd, root);
1955
            addRemiseField(tableCmd, root);
1956
 
1957
            SQLTable tableBon = root.getTable("BON_DE_LIVRAISON");
1958
            addAdresseField(tableBon, root);
1959
            addRemiseField(tableBon, root);
1960
 
1961
            SQLTable tableAvoir = root.getTable("AVOIR_CLIENT");
1962
            addAdresseField(tableAvoir, root);
1963
            addRemiseField(tableAvoir, root);
1964
        }
1965
        // Service client
1966
        if (root.getTable("CLIENT_DEPARTEMENT") == null) {
1967
            final SQLCreateTable createTableDpt = new SQLCreateTable(root, "CLIENT_DEPARTEMENT");
1968
            createTableDpt.addForeignColumn("CLIENT");
1969
            if (root.contains("ADRESSE")) {
1970
                createTableDpt.addForeignColumn("ADRESSE");
1971
            } else {
1972
                createTableDpt.addForeignColumn("ID_ADRESSE", root.findTable("ADRESSE"));
1973
            }
1974
            createTableDpt.addVarCharColumn("INFOS", 2048);
1975
            createTableDpt.addVarCharColumn("NOM", 256);
1976
            try {
1977
                root.getBase().getDataSource().execute(createTableDpt.asString());
1978
                insertUndef(createTableDpt);
1979
                root.refetchTable("CLIENT_DEPARTEMENT");
1980
                root.getSchema().updateVersion();
1981
            } catch (SQLException ex2) {
1982
                throw new IllegalStateException("Erreur lors de la création de la table " + "CLIENT_DEPARTEMENT", ex2);
1983
            }
1984
        }
1985
 
83 ilm 1986
        SQLTable tableVFElt = root.getTable("SAISIE_VENTE_FACTURE_ELEMENT");
1987
        patchFieldElt1Dot4(tableVFElt, root);
1988
 
1989
        SQLTable tableDevisElt = root.getTable("DEVIS_ELEMENT");
1990
        patchFieldElt1Dot4(tableDevisElt, root);
1991
 
1992
        SQLTable tableCmdElt = root.getTable("COMMANDE_CLIENT_ELEMENT");
93 ilm 1993
 
83 ilm 1994
        patchFieldElt1Dot4(tableCmdElt, root);
1995
 
1996
        SQLTable tableBonElt = root.getTable("BON_DE_LIVRAISON_ELEMENT");
1997
        patchFieldElt1Dot4(tableBonElt, root);
1998
 
1999
        SQLTable tableAvoirElt = root.getTable("AVOIR_CLIENT_ELEMENT");
2000
        patchFieldElt1Dot4(tableAvoirElt, root);
2001
 
93 ilm 2002
        addNiveauElementField(root.getTable("COMMANDE_ELEMENT"));
2003
        addNiveauElementField(root.getTable("BON_RECEPTION_ELEMENT"));
2004
        addNiveauElementField(root.getTable("FACTURE_FOURNISSEUR_ELEMENT"));
2005
 
83 ilm 2006
        addContact(root);
2007
 
93 ilm 2008
        {
2009
            // Gestion des préparations de commandes
2010
            final SQLTable tableCommandeClient = root.getTable("COMMANDE_CLIENT");
2011
            AlterTable tCommandeClient = new AlterTable(tableCommandeClient);
2012
            boolean updateCmdCli = false;
2013
 
2014
            if (!tableCommandeClient.contains("ETAT_COMMANDE")) {
2015
                updateCmdCli = true;
2016
                tCommandeClient.addIntegerColumn("ETAT_COMMANDE", EtatCommandeClient.A_PREPARER.getId());
2017
            }
2018
            if (!tableCommandeClient.contains("EMBALLAGE")) {
2019
                updateCmdCli = true;
2020
                tCommandeClient.addVarCharColumn("EMBALLAGE", 256);
2021
            }
2022
            if (!tableCommandeClient.contains("NUMERO_EXPEDITION")) {
2023
                updateCmdCli = true;
2024
                tCommandeClient.addVarCharColumn("NUMERO_EXPEDITION", 256);
2025
            }
2026
 
2027
            if (!tableCommandeClient.contains("ID_TAXE_PORT")) {
2028
                updateCmdCli = true;
2029
                tCommandeClient.addForeignColumn("ID_TAXE_PORT", root.getTable("TAXE"));
2030
            }
2031
 
2032
            if (!tableCommandeClient.contains("PORT_HT")) {
2033
                updateCmdCli = true;
2034
                tCommandeClient.addLongColumn("PORT_HT", Long.valueOf(0), false);
2035
            }
2036
 
2037
            if (!tableCommandeClient.contains("REMISE_HT")) {
2038
                updateCmdCli = true;
2039
                tCommandeClient.addLongColumn("REMISE_HT", Long.valueOf(0), false);
2040
            }
2041
 
2042
            if (updateCmdCli) {
2043
                tableCommandeClient.getBase().getDataSource().execute(tCommandeClient.asString());
2044
                tableCommandeClient.getSchema().updateVersion();
2045
                tableCommandeClient.fetchFields();
2046
            }
2047
        }
2048
 
2049
        {
2050
            // Gestion des préparations de commandes
2051
            final SQLTable tableBonL = root.getTable("BON_DE_LIVRAISON");
2052
            AlterTable tBonL = new AlterTable(tableBonL);
2053
            boolean updateBonL = false;
2054
 
2055
            if (!tableBonL.contains("TOTAL_DEVISE")) {
2056
                updateBonL = true;
2057
                tBonL.addLongColumn("TOTAL_DEVISE", Long.valueOf(0), false);
2058
            }
2059
 
2060
            if (!tableBonL.contains("TOTAL_SERVICE")) {
2061
                updateBonL = true;
2062
                tBonL.addLongColumn("TOTAL_SERVICE", Long.valueOf(0), false);
2063
            }
2064
 
2065
            if (!tableBonL.contains("ID_TAXE_PORT")) {
2066
                updateBonL = true;
2067
                tBonL.addForeignColumn("ID_TAXE_PORT", root.getTable("TAXE"));
2068
            }
2069
 
2070
            if (!tableBonL.contains("PORT_HT")) {
2071
                updateBonL = true;
2072
                tBonL.addLongColumn("PORT_HT", Long.valueOf(0), false);
2073
            }
2074
 
2075
            if (!tableBonL.contains("REMISE_HT")) {
2076
                updateBonL = true;
2077
                tBonL.addLongColumn("REMISE_HT", Long.valueOf(0), false);
2078
            }
2079
 
2080
            if (updateBonL) {
2081
                tableBonL.getBase().getDataSource().execute(tBonL.asString());
2082
                tableBonL.getSchema().updateVersion();
2083
                tableBonL.fetchFields();
2084
            }
2085
        }
2086
 
2087
        final List<String> asList = Arrays.asList("SAISIE_VENTE_FACTURE", "BON_RECEPTION", "BON_DE_LIVRAISON");
2088
        for (String tableVirtualStockName : asList) {
2089
            SQLTable tableVirtualStock = root.getTable(tableVirtualStockName);
2090
            if (!tableVirtualStock.contains("CREATE_VIRTUAL_STOCK")) {
2091
                AlterTable t = new AlterTable(tableVirtualStock);
2092
                t.addBooleanColumn("CREATE_VIRTUAL_STOCK", Boolean.TRUE, false);
2093
                tableVirtualStock.getBase().getDataSource().execute(t.asString());
2094
                tableVirtualStock.getSchema().updateVersion();
2095
                tableVirtualStock.fetchFields();
2096
            }
2097
        }
2098
 
2099
        // Remise dans les devis
83 ilm 2100
        final SQLTable tableDevis = root.getTable("DEVIS");
90 ilm 2101
        AlterTable tDevis = new AlterTable(tableDevis);
2102
        boolean updateDevis = false;
93 ilm 2103
 
90 ilm 2104
        if (!tableDevis.contains("POURCENT_REMISE")) {
2105
            updateDevis = true;
2106
            tDevis.addColumn("POURCENT_REMISE", "numeric (12,8)");
2107
        }
83 ilm 2108
        if (!tableDevis.contains("MONTANT_REMISE")) {
90 ilm 2109
            updateDevis = true;
2110
            tDevis.addColumn("MONTANT_REMISE", "numeric (16,8)");
2111
        }
2112
        if (!tableDevis.contains("T_HA")) {
2113
            updateDevis = true;
2114
            tDevis.addColumn("T_HA", "bigint", "0", false);
2115
        }
93 ilm 2116
 
2117
        if (!tableDevis.contains("DUNNING_DATE")) {
2118
            updateDevis = true;
2119
            tDevis.addColumn("DUNNING_DATE", "date");
2120
        }
2121
 
90 ilm 2122
        if (updateDevis) {
2123
            tableDevis.getBase().getDataSource().execute(tDevis.asString());
83 ilm 2124
            tableDevis.getSchema().updateVersion();
2125
            tableDevis.fetchFields();
2126
        }
2127
 
2128
        final SQLTable tableKmElt = root.getTable("SAISIE_KM_ELEMENT");
2129
        if (!tableKmElt.contains("ANALYTIQUE")) {
2130
            AlterTable t = new AlterTable(tableKmElt);
2131
            t.addVarCharColumn("ANALYTIQUE", 256);
2132
            tableKmElt.getBase().getDataSource().execute(t.asString());
2133
            tableKmElt.getSchema().updateVersion();
2134
            tableKmElt.fetchFields();
2135
 
2136
        }
2137
 
132 ilm 2138
        final SQLTable tableClient = root.getTable("CLIENT");
2139
        final SQLTable tableAdresse = tableClient.getForeignTable("ID_ADRESSE");
90 ilm 2140
        if (tableAdresse != null) {
83 ilm 2141
            AlterTable t = new AlterTable(tableAdresse);
90 ilm 2142
            boolean updateADr = false;
2143
            if (!tableAdresse.contains("PROVINCE")) {
2144
                t.addVarCharColumn("PROVINCE", 256);
2145
                updateADr = true;
2146
            }
2147
            if (!tableAdresse.contains("LIBELLE")) {
2148
                t.addVarCharColumn("LIBELLE", 256);
2149
                updateADr = true;
2150
            }
2151
            if (!tableAdresse.contains("TYPE")) {
2152
                t.addVarCharColumn("TYPE", 256);
2153
                updateADr = true;
2154
            }
2155
            if (!tableAdresse.contains("EMAIL_CONTACT")) {
2156
                t.addVarCharColumn("EMAIL_CONTACT", 256);
2157
                updateADr = true;
2158
            }
2159
            if (updateADr) {
2160
                tableAdresse.getBase().getDataSource().execute(t.asString());
2161
                tableAdresse.getSchema().updateVersion();
2162
                tableAdresse.fetchFields();
2163
            }
83 ilm 2164
        }
132 ilm 2165
 
93 ilm 2166
        if (tableClient != null) {
83 ilm 2167
            AlterTable t = new AlterTable(tableClient);
93 ilm 2168
            boolean upClient = false;
142 ilm 2169
            if (!tableClient.contains("REMIND_DATE")) {
2170
                t.addDateAndTimeColumn("REMIND_DATE");
2171
                upClient = true;
2172
            }
93 ilm 2173
            if (!tableClient.contains("BLOQUE_LIVRAISON")) {
2174
                t.addBooleanColumn("BLOQUE_LIVRAISON", false, false);
2175
                upClient = true;
2176
            }
83 ilm 2177
            if (!tableClient.contains("BLOQUE")) {
93 ilm 2178
                upClient = true;
83 ilm 2179
                t.addBooleanColumn("BLOQUE", false, false);
2180
            }
93 ilm 2181
            if (!tableClient.contains("ID_COMPTE_PCE_SERVICE")) {
2182
                upClient = true;
2183
                t.addForeignColumn("ID_COMPTE_PCE_SERVICE", tableClient.getTable("COMPTE_PCE"));
2184
            }
2185
 
2186
            if (!tableClient.contains("ID_COMPTE_PCE_PRODUIT")) {
2187
                upClient = true;
2188
                t.addForeignColumn("ID_COMPTE_PCE_PRODUIT", tableClient.getTable("COMPTE_PCE"));
2189
            }
2190
 
2191
            if (!tableClient.contains("ENCOURS_MAX")) {
2192
                upClient = true;
2193
                t.addDecimalColumn("ENCOURS_MAX", 16, 2, BigDecimal.valueOf(0), false);
2194
            }
2195
            if (!tableClient.contains("CATEGORIES")) {
2196
                upClient = true;
2197
                t.addVarCharColumn("CATEGORIES", 2048);
2198
            }
2199
            if (!tableClient.contains("NOTE_FINANCIERE")) {
2200
                upClient = true;
2201
                t.addVarCharColumn("NOTE_FINANCIERE", 1024);
2202
            }
2203
            if (!tableClient.contains("CENTRE_GESTION")) {
2204
                upClient = true;
2205
                t.addVarCharColumn("CENTRE_GESTION", 1024);
2206
            }
2207
            if (!tableClient.contains("METHODE_RELANCE")) {
2208
                upClient = true;
2209
                t.addVarCharColumn("METHODE_RELANCE", 1024);
2210
            }
2211
            if (!tableClient.contains("SITE_INTERNET")) {
2212
                upClient = true;
2213
                t.addVarCharColumn("SITE_INTERNET", 2048);
2214
            }
2215
            if (!tableClient.contains("GROUPE")) {
2216
                upClient = true;
2217
                t.addVarCharColumn("GROUPE", 1024);
2218
            }
2219
            if (!tableClient.contains("ID_COMMERCIAL")) {
2220
                upClient = true;
2221
                t.addForeignColumn("ID_COMMERCIAL", tableClient.getTable("COMMERCIAL"));
2222
            }
2223
 
2224
            if (upClient) {
2225
                tableClient.getBase().getDataSource().execute(t.asString());
2226
                tableClient.getSchema().updateVersion();
2227
                tableClient.fetchFields();
2228
            }
83 ilm 2229
        }
93 ilm 2230
        if (!root.contains("CATEGORIE_CLIENT")) {
2231
            final SQLCreateTable createCategorieClientTable = new SQLCreateTable(root, "CATEGORIE_CLIENT");
2232
            createCategorieClientTable.addVarCharColumn("NOM", 1024);
2233
 
2234
            try {
2235
                root.getDBSystemRoot().getDataSource().execute(createCategorieClientTable.asString());
2236
                insertUndef(createCategorieClientTable);
2237
                tableDevis.getSchema().updateVersion();
2238
            } catch (SQLException ex) {
2239
                throw new IllegalStateException("Erreur lors de la création de la table CATEGORIE_CLIENT", ex);
2240
            }
2241
 
2242
        }
2243
 
83 ilm 2244
        final SQLTable tableAssoc = root.getTable("ASSOCIATION_ANALYTIQUE");
2245
        if (tableAssoc != null && !tableAssoc.contains("GESTION_AUTO")) {
2246
            AlterTable t = new AlterTable(tableAssoc);
2247
            t.addBooleanColumn("GESTION_AUTO", false, false);
2248
            tableAssoc.getBase().getDataSource().execute(t.asString());
2249
            tableAssoc.getSchema().updateVersion();
2250
            tableAssoc.fetchFields();
2251
        }
90 ilm 2252
        if (!root.contains("CALENDAR_ITEM")) {
2253
            final SQLCreateTable createTaskGroupTable = new SQLCreateTable(root, "CALENDAR_ITEM_GROUP");
2254
            createTaskGroupTable.addVarCharColumn("NAME", 1024);
2255
            createTaskGroupTable.addVarCharColumn("DESCRIPTION", 1024 * 8);
83 ilm 2256
 
90 ilm 2257
            final SQLCreateTable createTaskTable = new SQLCreateTable(root, "CALENDAR_ITEM");
2258
            createTaskTable.addDateAndTimeColumn("START");
2259
            createTaskTable.addDateAndTimeColumn("END");
2260
            createTaskTable.addLongColumn("DURATION_S", 0L, false);
2261
            createTaskTable.addVarCharColumn("SUMMARY", 1024);
2262
            createTaskTable.addVarCharColumn("DESCRIPTION", 1024 * 8);
2263
            createTaskTable.addVarCharColumn("FLAGS", 1024);
2264
            createTaskTable.addVarCharColumn("STATUS", 128);
2265
            createTaskTable.addForeignColumn(createTaskGroupTable);
2266
            createTaskTable.addLongColumn("SOURCE_ID", null, true);
2267
            createTaskTable.addVarCharColumn("SOURCE_TABLE", 256);
142 ilm 2268
            createTaskTable.addVarCharColumn("UID", 1024);
2269
            createTaskTable.addVarCharColumn("LOCATION", 4096);
90 ilm 2270
            try {
2271
                root.getDBSystemRoot().getDataSource().execute(createTaskGroupTable.asString());
2272
                insertUndef(createTaskGroupTable);
2273
                root.getDBSystemRoot().getDataSource().execute(createTaskTable.asString());
2274
                insertUndef(createTaskTable);
2275
                tableDevis.getSchema().updateVersion();
142 ilm 2276
                root.refetchTable("CALENDAR_ITEM_GROUP");
2277
                root.refetchTable("CALENDAR_ITEM");
2278
 
90 ilm 2279
            } catch (SQLException ex) {
2280
                throw new IllegalStateException("Erreur lors de la création de la table TASK", ex);
2281
            }
2282
 
2283
        }
93 ilm 2284
 
2285
        // Remise sur tarif client
94 ilm 2286
        if (root.contains("ARTICLE_TARIF")) {
2287
 
93 ilm 2288
            AlterTable t = new AlterTable(root.getTable("ARTICLE_TARIF"));
94 ilm 2289
            boolean alterTarif = false;
2290
            if (!root.getTable("ARTICLE_TARIF").contains("POURCENT_REMISE")) {
2291
                t.addDecimalColumn("POURCENT_REMISE", 16, 6, BigDecimal.valueOf(0), false);
2292
                alterTarif = true;
2293
            }
2294
 
2295
            if (!root.getTable("ARTICLE_TARIF").contains("QTE")) {
2296
                t.addIntegerColumn("QTE", 1);
2297
                alterTarif = true;
2298
            }
2299
            if (alterTarif) {
2300
                root.getTable("ARTICLE_TARIF").getBase().getDataSource().execute(t.asString());
2301
                root.getTable("ARTICLE_TARIF").fetchFields();
2302
                root.getTable("ARTICLE").getSchema().updateVersion();
2303
            }
93 ilm 2304
        }
2305
        // SKU et Type d'expedition
2306
        final SQLTable articleTable = root.getTable("ARTICLE");
2307
        if (!articleTable.contains("SKU")) {
2308
            AlterTable a = new AlterTable(articleTable);
2309
            a.addVarCharColumn("SKU", 256);
2310
            try {
2311
                articleTable.getBase().getDataSource().execute(a.asString());
2312
                articleTable.getSchema().updateVersion();
2313
                articleTable.fetchFields();
2314
            } catch (SQLException ex2) {
2315
                throw new IllegalStateException("Erreur lors de l'ajout du champs SKU sur la table ARTICLE", ex2);
2316
            }
2317
        }
2318
 
2319
        try {
2320
            final SQLTable cmdClientTable = root.getTable("COMMANDE_CLIENT");
2321
            if (!cmdClientTable.contains("TYPE_EXPEDITION")) {
2322
                final AlterTable a = new AlterTable(cmdClientTable);
2323
                a.addVarCharColumn("TYPE_EXPEDITION", 256);
2324
                cmdClientTable.getBase().getDataSource().execute(a.asString());
2325
                cmdClientTable.getSchema().updateVersion();
2326
                cmdClientTable.fetchFields();
2327
            }
2328
        } catch (SQLException ex2) {
2329
            throw new IllegalStateException("Erreur lors de l'ajout du champs TYPE_EXPEDITION sur la table COMMANDE_CLIENT", ex2);
2330
        }
2331
        try {
2332
            final SQLTable axeTable = root.getTable("AXE_ANALYTIQUE");
2333
            if (!axeTable.contains("TYPE")) {
2334
                final AlterTable a = new AlterTable(axeTable);
2335
                a.addVarCharColumn("TYPE", 256);
2336
                axeTable.getBase().getDataSource().execute(a.asString());
2337
                axeTable.getSchema().updateVersion();
2338
                axeTable.fetchFields();
2339
            }
2340
        } catch (SQLException ex2) {
2341
            throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table AXE_ANALYTIQUE", ex2);
2342
        }
2343
        // Historique des taux
2344
        if (!root.contains("DEVISE_HISTORIQUE")) {
2345
            final SQLCreateTable createTable = new SQLCreateTable(root, "DEVISE_HISTORIQUE");
2346
            createTable.addDateAndTimeColumn("DATE");
2347
            createTable.addVarCharColumn("SRC", 8);
2348
            createTable.addVarCharColumn("DST", 8);
2349
            createTable.addDecimalColumn("TAUX", 12, 6, new BigDecimal(1), false);
2350
            createTable.addDecimalColumn("TAUX_COMMERCIAL", 12, 6, new BigDecimal(1), false);
2351
            try {
2352
                root.getDBSystemRoot().getDataSource().execute(createTable.asString());
2353
                insertUndef(createTable);
2354
                tableDevis.getSchema().updateVersion();
156 ilm 2355
                root.refetchTable("DEVISE_HISTORIQUE");
93 ilm 2356
            } catch (SQLException ex) {
2357
                throw new IllegalStateException("Erreur lors de la création de la table TASK", ex);
2358
            }
2359
        }
2360
 
2361
        final SQLTable tableContact = root.getTable("CONTACT");
2362
        if (tableContact != null && !tableContact.contains("NO_MAILING")) {
2363
            AlterTable t = new AlterTable(tableContact);
2364
            t.addBooleanColumn("NO_MAILING", false, false);
2365
            tableContact.getBase().getDataSource().execute(t.asString());
2366
            tableContact.getSchema().updateVersion();
2367
            tableContact.fetchFields();
2368
        }
2369
 
94 ilm 2370
        SQLTable tableBonR = root.getTable("FACTURE_FOURNISSEUR");
2371
        if (!tableBonR.contains("TAUX_APPLIQUE")) {
2372
            AlterTable t = new AlterTable(tableBonR);
2373
            t.addDecimalColumn("TAUX_APPLIQUE", 12, 6, BigDecimal.ONE, true);
2374
            tableBonR.getBase().getDataSource().execute(t.asString());
2375
            tableBonR.getSchema().updateVersion();
2376
            tableBonR.fetchFields();
2377
        }
2378
        root.getTable("ARTICLE").getSchema().updateVersion();
132 ilm 2379
        // Valeur par défaut des numérotations
174 ilm 2380
        if (root.contains("NUMEROTATION_AUTO")) {
2381
            SQLRow rowNumerotation = root.getTable("NUMEROTATION_AUTO").getRow(2);
2382
            if (rowNumerotation != null) {
2383
                SQLRowValues rNumerotation = rowNumerotation.asRowValues();
2384
                boolean numerotationFixed = false;
2385
                if (StringUtils.isEmpty(rNumerotation.getString("AVOIR_F_FORMAT"), true)) {
2386
                    rNumerotation.put("AVOIR_F_FORMAT", "'AVOIR'yyMM-000");
2387
                    numerotationFixed = true;
2388
                }
2389
                if (StringUtils.isEmpty(rNumerotation.getString("CLIENT_FORMAT"), true)) {
2390
                    rNumerotation.put("CLIENT_FORMAT", "'CLI'00000");
2391
                    numerotationFixed = true;
2392
                }
2393
                if (numerotationFixed) {
2394
                    rNumerotation.commit();
2395
                }
2396
            }
132 ilm 2397
        }
142 ilm 2398
        //
2399
 
2400
        final SQLTable tableCalendarItem = root.getTable("CALENDAR_ITEM");
2401
        if (tableCalendarItem != null) {
2402
            final AlterTable tVF = new AlterTable(tableCalendarItem);
2403
            boolean needUpdate = false;
2404
            if (!tableCalendarItem.getFieldsName().contains("UID")) {
2405
                tVF.addVarCharColumn("UID", 1024);
2406
                needUpdate = true;
2407
            }
2408
            if (!tableCalendarItem.getFieldsName().contains("LOCATION")) {
2409
                tVF.addVarCharColumn("LOCATION", 4096);
2410
                needUpdate = true;
2411
            }
2412
            if (needUpdate) {
2413
                try {
2414
                    tableCalendarItem.getBase().getDataSource().execute(tVF.asString());
2415
                    tableCalendarItem.getSchema().updateVersion();
2416
                    tableCalendarItem.fetchFields();
2417
                } catch (SQLException ex) {
2418
                    throw new IllegalStateException("Erreur lors de l'ajout de UID sur la table CALENDAR_ITEM", ex);
2419
                }
2420
            }
2421
        }
2422
 
83 ilm 2423
    }
2424
 
2425
    private void updateStyle(final DBRoot root) throws SQLException {
2426
        SQLTable style = root.getTable("STYLE");
2427
        SQLRowValues rowVals = new SQLRowValues(style);
2428
        rowVals.put("NOM", null);
2429
        SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
2430
        List<SQLRowValues> list = fetcher.fetch();
2431
        boolean containsInvisible = false;
2432
        for (SQLRowValues sqlRowValues : list) {
2433
            if (sqlRowValues.getString("NOM").equals("Invisible")) {
2434
                containsInvisible = true;
2435
            }
2436
        }
2437
        if (!containsInvisible) {
2438
            SQLRowValues rowValsStyle = new SQLRowValues(style);
2439
            rowValsStyle.put("NOM", "Invisible");
2440
            rowValsStyle.put("CODE", "INV");
2441
            rowValsStyle.insert();
2442
        }
2443
 
2444
    }
2445
 
19 ilm 2446
    private void updateToV1Dot2(final DBRoot root) throws SQLException {
57 ilm 2447
        // bigint -> int ID_METRIQUE BON_DE_LIVRAISON_ELEMENT
2448
        final SQLTable tableLivraisonElement = root.getTable("BON_DE_LIVRAISON_ELEMENT");
2449
        AlterTable alter = new AlterTable(tableLivraisonElement);
2450
        alter.alterColumn("ID_METRIQUE_2", EnumSet.of(Properties.TYPE), "integer", null, null);
2451
        String req3 = alter.asString();
2452
        root.getDBSystemRoot().getDataSource().execute(req3);
2453
 
19 ilm 2454
        final SQLTable tableDevis = root.getTable("DEVIS");
2455
        final SQLDataSource ds = root.getDBSystemRoot().getDataSource();
2456
        if (!tableDevis.getFieldsName().contains("DATE_VALIDITE")) {
2457
            AlterTable t = new AlterTable(tableDevis);
2458
            t.addColumn("DATE_VALIDITE", "date");
2459
            try {
2460
                ds.execute(t.asString());
2461
                tableDevis.getSchema().updateVersion();
2462
            } catch (SQLException ex) {
2463
                throw new IllegalStateException("Erreur lors de l'ajout du champ DATE_VALIDITE à la table DEVIS", ex);
2464
            }
2465
        } else {
2466
            AlterTable t = new AlterTable(tableDevis);
2467
            t.alterColumn("DATE_VALIDITE", EnumSet.allOf(Properties.class), "date", null, true);
2468
            try {
2469
                ds.execute(t.asString());
2470
                tableDevis.getSchema().updateVersion();
2471
            } catch (SQLException ex) {
2472
                throw new IllegalStateException("Erreur lors de l'ajout du champ DATE_VALIDITE à la table DEVIS", ex);
2473
            }
2474
        }
18 ilm 2475
 
61 ilm 2476
        final SQLTable tableEtatDevis = root.getTable("ETAT_DEVIS");
2477
        if (tableEtatDevis.getRow(5) == null && tableEtatDevis.getRowCount() <= 4) {
2478
            SQLRowValues rowVals = new SQLRowValues(tableEtatDevis);
2479
            rowVals.put("NOM", "En cours de rédaction");
2480
            rowVals.commit();
67 ilm 2481
 
61 ilm 2482
        }
2483
 
67 ilm 2484
        SQLRowValues rowValsOrdre = new SQLRowValues(tableEtatDevis);
93 ilm 2485
        rowValsOrdre.put("ORDRE", new BigDecimal("1.505"));
67 ilm 2486
        rowValsOrdre.update(EtatDevisSQLElement.EN_ATTENTE);
2487
 
93 ilm 2488
        rowValsOrdre.put("ORDRE", new BigDecimal("2.505"));
67 ilm 2489
        rowValsOrdre.update(EtatDevisSQLElement.ACCEPTE);
2490
 
93 ilm 2491
        rowValsOrdre.put("ORDRE", new BigDecimal("3.505"));
67 ilm 2492
        rowValsOrdre.update(EtatDevisSQLElement.REFUSE);
2493
 
93 ilm 2494
        rowValsOrdre.put("ORDRE", new BigDecimal("4.505"));
67 ilm 2495
        rowValsOrdre.update(EtatDevisSQLElement.EN_COURS);
2496
 
63 ilm 2497
        // Ajout de la TVA à 0
67 ilm 2498
        SQLSelect selTVA = new SQLSelect();
63 ilm 2499
        SQLTable tableTaxe = root.getTable("TAXE");
2500
        selTVA.addSelect(tableTaxe.getKey(), "COUNT");
2501
        selTVA.setWhere(new Where(tableTaxe.getField("TAUX"), "=", 0));
2502
        Object result = root.getBase().getDataSource().executeScalar(selTVA.asString());
2503
        if (result == null || ((Number) result).longValue() == 0) {
2504
            SQLRowValues rowVals = new SQLRowValues(tableTaxe);
2505
            rowVals.put("NOM", "Non applicable");
2506
            rowVals.put("TAUX", Float.valueOf(0));
2507
            rowVals.commit();
2508
        }
2509
 
19 ilm 2510
        // Bon de livraison
2511
        {
2512
            SQLTable tableBL = root.getTable("BON_DE_LIVRAISON");
2513
            boolean alterBL = false;
2514
            AlterTable t = new AlterTable(tableBL);
2515
            if (!tableBL.getFieldsName().contains("SOURCE")) {
2516
                t.addVarCharColumn("SOURCE", 512);
2517
                alterBL = true;
2518
            }
2519
            if (!tableBL.getFieldsName().contains("IDSOURCE")) {
2520
                t.addColumn("IDSOURCE", "integer DEFAULT 1");
2521
                alterBL = true;
2522
            }
41 ilm 2523
 
2524
            if (!tableBL.getFieldsName().contains("DATE_LIVRAISON")) {
2525
                t.addColumn("DATE_LIVRAISON", "date");
2526
                alterBL = true;
2527
            }
19 ilm 2528
            if (alterBL) {
2529
                try {
2530
                    ds.execute(t.asString());
2531
                    tableBL.getSchema().updateVersion();
2532
                    tableBL.fetchFields();
2533
                } catch (SQLException ex) {
2534
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table BON_DE_LIVRAISON", ex);
2535
                }
2536
            }
2537
        }
61 ilm 2538
 
2539
        // Fournisseur
2540
        {
2541
            SQLTable tableBL = root.getTable("FOURNISSEUR");
2542
            boolean alterBL = false;
2543
            AlterTable t = new AlterTable(tableBL);
2544
            if (!tableBL.getFieldsName().contains("ID_COMPTE_PCE_CHARGE")) {
2545
                t.addForeignColumn("ID_COMPTE_PCE_CHARGE", root.getTable("COMPTE_PCE"));
2546
                alterBL = true;
2547
            }
2548
            if (alterBL) {
2549
                try {
2550
                    ds.execute(t.asString());
2551
                    tableBL.getSchema().updateVersion();
2552
                    tableBL.fetchFields();
2553
                } catch (SQLException ex) {
2554
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table FOURNISSEUR", ex);
2555
                }
2556
            }
2557
        }
2558
 
2559
        // Numérotation
2560
        {
2561
            SQLTable tableNum = root.getTable("NUMEROTATION_AUTO");
2562
            boolean alterNum = false;
2563
            AlterTable t = new AlterTable(tableNum);
2564
            if (!tableNum.getFieldsName().contains("AVOIR_F_START")) {
2565
                t.addColumn("AVOIR_F_START", "integer DEFAULT 0");
2566
                alterNum = true;
2567
            }
2568
            if (!tableNum.getFieldsName().contains("AVOIR_F_FORMAT")) {
2569
                t.addVarCharColumn("AVOIR_F_FORMAT", 48);
2570
                alterNum = true;
2571
            }
2572
 
2573
            if (alterNum) {
2574
                try {
2575
                    ds.execute(t.asString());
2576
                    tableNum.getSchema().updateVersion();
2577
                    tableNum.fetchFields();
2578
                } catch (SQLException ex) {
2579
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table NUMEROTATION_AUTO", ex);
2580
                }
2581
            }
2582
        }
2583
 
19 ilm 2584
        SQLTable tableArticle = root.getTable("ARTICLE");
2585
 
2586
        AlterTable t = new AlterTable(tableArticle);
2587
        boolean alterArticle = false;
2588
        if (!tableArticle.getFieldsName().contains("QTE_ACHAT")) {
2589
            t.addColumn("QTE_ACHAT", "integer DEFAULT 1");
2590
            alterArticle = true;
2591
        }
2592
        if (!tableArticle.getFieldsName().contains("DESCRIPTIF")) {
2593
            t.addVarCharColumn("DESCRIPTIF", 2048);
2594
            alterArticle = true;
2595
        }
2596
        if (!tableArticle.getFieldsName().contains("CODE_BARRE")) {
2597
            t.addVarCharColumn("CODE_BARRE", 256);
2598
            alterArticle = true;
2599
        }
2600
        if (!tableArticle.getFieldsName().contains("GESTION_STOCK")) {
2601
            t.addColumn("GESTION_STOCK", "boolean DEFAULT true");
2602
            alterArticle = true;
2603
        }
2604
        if (!tableArticle.getFieldsName().contains("CODE_DOUANIER")) {
2605
            t.addVarCharColumn("CODE_DOUANIER", 256);
2606
            alterArticle = true;
2607
        }
2608
        if (!tableArticle.getFieldsName().contains("QTE_MIN")) {
2609
            t.addColumn("QTE_MIN", "integer DEFAULT 1");
2610
            alterArticle = true;
2611
        }
2612
        if (!tableArticle.getFieldsName().contains("ID_DEVISE")) {
61 ilm 2613
            t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
19 ilm 2614
            alterArticle = true;
2615
        }
2616
        if (!tableArticle.getFieldsName().contains("ID_FOURNISSEUR")) {
61 ilm 2617
            t.addForeignColumn("ID_FOURNISSEUR", root.findTable("FOURNISSEUR", true));
19 ilm 2618
            alterArticle = true;
2619
        }
2620
        if (!tableArticle.getFieldsName().contains("PV_U_DEVISE")) {
2621
            t.addColumn("PV_U_DEVISE", "bigint default 0");
2622
            alterArticle = true;
2623
        }
2624
        if (!tableArticle.getFieldsName().contains("ID_DEVISE_HA")) {
61 ilm 2625
            t.addForeignColumn("ID_DEVISE_HA", root.findTable("DEVISE", true));
19 ilm 2626
            alterArticle = true;
2627
        }
2628
        if (!tableArticle.getFieldsName().contains("PA_DEVISE")) {
2629
            t.addColumn("PA_DEVISE", "bigint default 0");
2630
            alterArticle = true;
2631
        }
2632
        if (!tableArticle.getFieldsName().contains("ID_PAYS")) {
61 ilm 2633
            t.addForeignColumn("ID_PAYS", root.findTable("PAYS", true));
19 ilm 2634
            alterArticle = true;
2635
        }
2636
        if (alterArticle) {
18 ilm 2637
            try {
19 ilm 2638
                ds.execute(t.asString());
2639
                tableArticle.getSchema().updateVersion();
18 ilm 2640
                tableArticle.fetchFields();
2641
            } catch (SQLException ex) {
19 ilm 2642
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table ARTICLE", ex);
18 ilm 2643
            }
2644
        }
2645
 
19 ilm 2646
        // Création de la table Langue
2647
        boolean refetchRoot = false;
61 ilm 2648
        if (!root.contains("OBJECTIF_COMMERCIAL")) {
2649
 
2650
            SQLCreateTable createObjectif = new SQLCreateTable(root, "OBJECTIF_COMMERCIAL");
2651
            createObjectif.addVarCharColumn("MOIS", 32);
2652
            createObjectif.addColumn("ANNEE", "integer");
2653
            createObjectif.addColumn("MARGE_HT", "bigint DEFAULT 0");
2654
            createObjectif.addColumn("POURCENT_MARGE", "numeric (16,8)");
2655
            createObjectif.addColumn("CHIFFRE_AFFAIRE", "bigint DeFAULT 0");
2656
            createObjectif.addForeignColumn("COMMERCIAL");
2657
            try {
2658
                ds.execute(createObjectif.asString());
2659
                insertUndef(createObjectif);
2660
                tableDevis.getSchema().updateVersion();
2661
                refetchRoot = true;
2662
            } catch (SQLException ex) {
2663
                throw new IllegalStateException("Erreur lors de la création de la table OBJECTIF_COMMERCIAL", ex);
2664
            }
2665
 
2666
        }
2667
 
19 ilm 2668
        if (!root.contains("LANGUE")) {
18 ilm 2669
 
19 ilm 2670
            SQLCreateTable createLangue = new SQLCreateTable(root, "LANGUE");
2671
            createLangue.addVarCharColumn("CODE", 256);
2672
            createLangue.addVarCharColumn("NOM", 256);
2673
            createLangue.addVarCharColumn("CHEMIN", 256);
2674
            try {
2675
                ds.execute(createLangue.asString());
2676
                insertUndef(createLangue);
2677
                tableDevis.getSchema().updateVersion();
67 ilm 2678
                root.refetchTable(createLangue.getName());
19 ilm 2679
            } catch (SQLException ex) {
2680
                throw new IllegalStateException("Erreur lors de la création de la table LANGUE", ex);
2681
            }
2682
 
2683
            final String[] langs = new String[] { "FR", "Français", "EN", "Anglais", "SP", "Espagnol", "DE", "Allemand", "NL", "Néerlandais", "IT", "Italien" };
2684
            // ('FR', 'Français', 1.000), ('EN', 'Anglais', 2.000)
2685
            final List<String> values = new ArrayList<String>();
2686
            final SQLBase base = root.getBase();
2687
            for (int i = 0; i < langs.length; i += 2) {
2688
                final int order = values.size() + 1;
2689
                values.add("(" + base.quoteString(langs[i]) + ", " + base.quoteString(langs[i + 1]) + ", " + order + ")");
2690
            }
2691
            final String valuesStr = CollectionUtils.join(values, ", ");
2692
            final String insertVals = "INSERT INTO " + getTableName(createLangue).quote() + "(" + SQLBase.quoteIdentifier("CODE") + ", " + SQLBase.quoteIdentifier("NOM") + ", "
2693
                    + SQLBase.quoteIdentifier(SQLSyntax.ORDER_NAME) + ") VALUES" + valuesStr;
2694
            ds.execute(insertVals);
18 ilm 2695
        }
2696
 
21 ilm 2697
        // Création de la table Modéle
2698
        if (!root.contains("MODELE")) {
2699
 
2700
            SQLCreateTable createModele = new SQLCreateTable(root, "MODELE");
2701
            createModele.addVarCharColumn("NOM", 256);
61 ilm 2702
            createModele.addForeignColumn("ID_TYPE_MODELE", root.findTable("TYPE_MODELE", true));
21 ilm 2703
            try {
2704
                ds.execute(createModele.asString());
2705
                insertUndef(createModele);
2706
                tableDevis.getSchema().updateVersion();
2707
                refetchRoot = true;
2708
            } catch (SQLException ex) {
2709
                throw new IllegalStateException("Erreur lors de la création de la table MODELE", ex);
2710
            }
2711
        }
2712
 
2713
        // Création de la table Modéle
2714
        if (!root.contains("CONTACT_FOURNISSEUR")) {
2715
 
2716
            SQLCreateTable createModele = new SQLCreateTable(root, "CONTACT_FOURNISSEUR");
2717
            createModele.addVarCharColumn("NOM", 256);
2718
            createModele.addVarCharColumn("PRENOM", 256);
2719
            createModele.addVarCharColumn("TEL_DIRECT", 256);
2720
            createModele.addVarCharColumn("TEL_MOBILE", 256);
2721
            createModele.addVarCharColumn("EMAIL", 256);
2722
            createModele.addVarCharColumn("FAX", 256);
2723
            createModele.addVarCharColumn("FONCTION", 256);
2724
            createModele.addVarCharColumn("TEL_PERSONEL", 256);
2725
            createModele.addVarCharColumn("TEL_STANDARD", 256);
2726
            createModele.addForeignColumn("ID_TITRE_PERSONNEL", root.findTable("TITRE_PERSONNEL"));
2727
            createModele.addForeignColumn("ID_FOURNISSEUR", root.findTable("FOURNISSEUR"));
2728
 
2729
            try {
2730
                ds.execute(createModele.asString());
2731
                insertUndef(createModele);
2732
                tableDevis.getSchema().updateVersion();
2733
                refetchRoot = true;
2734
            } catch (SQLException ex) {
2735
                throw new IllegalStateException("Erreur lors de la création de la table MODELE", ex);
2736
            }
2737
        }
2738
 
19 ilm 2739
        // Création de la table Tarif
2740
        if (!root.contains("TARIF")) {
2741
 
2742
            SQLCreateTable createTarif = new SQLCreateTable(root, "TARIF");
2743
            createTarif.addVarCharColumn("NOM", 256);
61 ilm 2744
            createTarif.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
2745
            createTarif.addForeignColumn("ID_TAXE", root.findTable("TAXE", true));
19 ilm 2746
            createTarif.asString();
18 ilm 2747
            try {
19 ilm 2748
                ds.execute(createTarif.asString());
2749
                insertUndef(createTarif);
2750
                tableDevis.getSchema().updateVersion();
67 ilm 2751
                root.refetchTable(createTarif.getName());
18 ilm 2752
            } catch (SQLException ex) {
19 ilm 2753
                throw new IllegalStateException("Erreur lors de la création de la table TARIF", ex);
18 ilm 2754
            }
2755
        }
2756
 
19 ilm 2757
        // Création de la table article Tarif
2758
        if (!root.contains("ARTICLE_TARIF")) {
2759
 
2760
            SQLCreateTable createTarif = new SQLCreateTable(root, "ARTICLE_TARIF");
61 ilm 2761
            createTarif.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
2762
            createTarif.addForeignColumn("ID_TAXE", root.findTable("TAXE", true));
2763
            createTarif.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
2764
            createTarif.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
19 ilm 2765
            createTarif.addColumn("PV_HT", "bigint DEFAULT 0");
2766
            createTarif.addColumn("PV_TTC", "bigint DEFAULT 0");
2767
            createTarif.addColumn("PRIX_METRIQUE_VT_1", "bigint DEFAULT 0");
2768
            createTarif.addColumn("PRIX_METRIQUE_VT_2", "bigint DEFAULT 0");
2769
            createTarif.addColumn("PRIX_METRIQUE_VT_3", "bigint DEFAULT 0");
2770
            createTarif.asString();
18 ilm 2771
            try {
19 ilm 2772
                ds.execute(createTarif.asString());
2773
                insertUndef(createTarif);
2774
                tableDevis.getSchema().updateVersion();
61 ilm 2775
                refetchRoot = true;
19 ilm 2776
            } catch (SQLException ex) {
2777
                throw new IllegalStateException("Erreur lors de la création de la table ARTICLE_TARIF", ex);
18 ilm 2778
            }
2779
        }
2780
 
19 ilm 2781
        // Création de la table article Désignation
2782
        if (!root.contains("ARTICLE_DESIGNATION")) {
2783
 
2784
            SQLCreateTable createTarif = new SQLCreateTable(root, "ARTICLE_DESIGNATION");
61 ilm 2785
            createTarif.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
2786
            createTarif.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
19 ilm 2787
            createTarif.addVarCharColumn("NOM", 1024);
2788
            createTarif.asString();
18 ilm 2789
            try {
19 ilm 2790
                ds.execute(createTarif.asString());
2791
                insertUndef(createTarif);
2792
                tableDevis.getSchema().updateVersion();
61 ilm 2793
                refetchRoot = true;
19 ilm 2794
            } catch (SQLException ex) {
2795
                throw new IllegalStateException("Erreur lors de la création de la table ARTICLE_DESIGNATION", ex);
18 ilm 2796
            }
2797
        }
2798
 
61 ilm 2799
        if (!root.contains("UNITE_VENTE")) {
2800
 
2801
            SQLCreateTable createUnite = new SQLCreateTable(root, "UNITE_VENTE");
2802
            createUnite.addVarCharColumn("CODE", 32);
2803
            createUnite.addVarCharColumn("NOM", 256);
2804
            createUnite.addColumn("A_LA_PIECE", "boolean DEFAULT false");
2805
            createUnite.addVarCharColumn("INFOS", 256);
2806
            try {
2807
                ds.execute(createUnite.asString());
2808
                insertUndef(createUnite);
132 ilm 2809
                final String insert = "INSERT into " + getTableName(createUnite).quote()
61 ilm 2810
                        + "(\"CODE\",\"NOM\",\"A_LA_PIECE\",\"ORDRE\") VALUES('pièce','à la pièce',true,1),('m','mètres',false,2),('m²','mètres carré',false,3),('m3','mètres cube',false,4),('l','litres',false,5),('kg','kilos',false,6),('h','heures',false,7),('j','jours',false,8),('mois','mois',false,9)";
2811
                root.getDBSystemRoot().getDataSource().execute(insert);
2812
                tableDevis.getSchema().updateVersion();
2813
                refetchRoot = true;
2814
            } catch (SQLException ex) {
2815
                throw new IllegalStateException("Erreur lors de la création de la table UNITE_VENTE", ex);
2816
            }
2817
 
2818
        }
2819
 
2820
        // Chargement des tables fraichement créées
2821
        if (refetchRoot)
2822
            root.refetch();
2823
 
2824
        if (!tableArticle.getFieldsName().contains("ID_UNITE_VENTE")) {
2825
            AlterTable alterTableArticle = new AlterTable(tableArticle);
2826
            alterTableArticle.addForeignColumn("ID_UNITE_VENTE", root.findTable("UNITE_VENTE", true).getSQLName(), "ID", "2");
2827
            try {
2828
                ds.execute(alterTableArticle.asString());
2829
                tableArticle.getSchema().updateVersion();
2830
                tableArticle.fetchFields();
2831
            } catch (SQLException ex) {
2832
                throw new IllegalStateException("Erreur lors de l'ajout du champ UNITE_VENTE sur la table ARTICLE", ex);
2833
            }
2834
        }
2835
 
19 ilm 2836
        SQLTable tableVFElt = root.getTable("SAISIE_VENTE_FACTURE_ELEMENT");
41 ilm 2837
        addVenteEltField(tableVFElt, root);
18 ilm 2838
 
19 ilm 2839
        SQLTable tableDevisElt = root.getTable("DEVIS_ELEMENT");
41 ilm 2840
        addVenteEltField(tableDevisElt, root);
19 ilm 2841
 
2842
        SQLTable tableCmdElt = root.getTable("COMMANDE_CLIENT_ELEMENT");
41 ilm 2843
        addVenteEltField(tableCmdElt, root);
19 ilm 2844
 
2845
        SQLTable tableBonElt = root.getTable("BON_DE_LIVRAISON_ELEMENT");
41 ilm 2846
        addVenteEltField(tableBonElt, root);
19 ilm 2847
 
2848
        SQLTable tableAvoirElt = root.getTable("AVOIR_CLIENT_ELEMENT");
41 ilm 2849
        addVenteEltField(tableAvoirElt, root);
19 ilm 2850
 
2851
        SQLTable tableCmdFournElt = root.getTable("COMMANDE_ELEMENT");
41 ilm 2852
        addHAElementField(tableCmdFournElt, root);
90 ilm 2853
        if (root.contains("DEMANDE_PRIX_ELEMENT")) {
2854
            SQLTable tableDmdFournElt = root.getTable("DEMANDE_PRIX_ELEMENT");
2855
            addHAElementField(tableDmdFournElt, root);
2856
        }
19 ilm 2857
 
2858
        SQLTable tableBonRecptElt = root.getTable("BON_RECEPTION_ELEMENT");
41 ilm 2859
        addHAElementField(tableBonRecptElt, root);
19 ilm 2860
 
2861
        SQLTable tableBonRecpt = root.getTable("BON_RECEPTION");
2862
        addDeviseHAField(tableBonRecpt, root);
2863
 
2864
        SQLTable tableCommande = root.getTable("COMMANDE");
2865
        addDeviseHAField(tableCommande, root);
2866
 
67 ilm 2867
        patchFieldElt1Dot3(root.getTable("ARTICLE"), root);
2868
        patchFieldElt1Dot3(root.getTable("ARTICLE_TARIF"), root);
2869
 
41 ilm 2870
        if (!tableCommande.getFieldsName().contains("ID_ADRESSE")) {
2871
            AlterTable alterCmd = new AlterTable(tableCommande);
61 ilm 2872
            alterCmd.addForeignColumn("ID_ADRESSE", root.findTable("ADRESSE", true));
41 ilm 2873
            try {
2874
                ds.execute(alterCmd.asString());
2875
                tableCommande.getSchema().updateVersion();
2876
            } catch (SQLException ex) {
2877
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table COMMANDE", ex);
2878
            }
2879
 
2880
        }
61 ilm 2881
        if (!tableCommande.getFieldsName().contains("ID_CLIENT")) {
2882
            AlterTable alterCmd = new AlterTable(tableCommande);
2883
            alterCmd.addForeignColumn("ID_CLIENT", root.findTable("CLIENT"));
2884
            try {
2885
                ds.execute(alterCmd.asString());
2886
                tableCommande.getSchema().updateVersion();
2887
            } catch (SQLException ex) {
2888
                throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table COMMANDE", ex);
2889
            }
41 ilm 2890
 
61 ilm 2891
        }
2892
 
19 ilm 2893
        {
21 ilm 2894
            addTotalDeviseField(tableDevis, root);
2895
            addModeleField(tableDevis, root);
2896
 
19 ilm 2897
            SQLTable tableVF = root.getTable("SAISIE_VENTE_FACTURE");
2898
            addTotalDeviseField(tableVF, root);
21 ilm 2899
            addModeleField(tableVF, root);
19 ilm 2900
 
2901
            addTotalDeviseField(tableDevis, root);
21 ilm 2902
            addModeleField(tableDevis, root);
19 ilm 2903
 
2904
            SQLTable tableCmd = root.getTable("COMMANDE_CLIENT");
2905
            addTotalDeviseField(tableCmd, root);
21 ilm 2906
            addModeleField(tableCmd, root);
19 ilm 2907
 
2908
            SQLTable tableBon = root.getTable("BON_DE_LIVRAISON");
2909
            addTotalDeviseField(tableBon, root);
21 ilm 2910
            addModeleField(tableBon, root);
19 ilm 2911
 
2912
            SQLTable tableAvoir = root.getTable("AVOIR_CLIENT");
2913
            addTotalDeviseField(tableAvoir, root);
21 ilm 2914
            addModeleField(tableAvoir, root);
18 ilm 2915
        }
19 ilm 2916
        // Change client
2917
        {
2918
            SQLTable tableClient = root.getTable("CLIENT");
18 ilm 2919
 
19 ilm 2920
            AlterTable tClient = new AlterTable(tableClient);
2921
            boolean alterClient = false;
2922
 
2923
            if (!tableClient.getFieldsName().contains("ID_TARIF")) {
61 ilm 2924
                tClient.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
19 ilm 2925
                alterClient = true;
2926
            }
2927
            if (!tableClient.getFieldsName().contains("ID_PAYS")) {
61 ilm 2928
                tClient.addForeignColumn("ID_PAYS", root.findTable("PAYS", true));
19 ilm 2929
                alterClient = true;
2930
            }
2931
            if (!tableClient.getFieldsName().contains("ID_LANGUE")) {
61 ilm 2932
                tClient.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
19 ilm 2933
                alterClient = true;
2934
            }
2935
 
2936
            if (!tableClient.getFieldsName().contains("ID_DEVISE")) {
61 ilm 2937
                tClient.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
19 ilm 2938
                alterClient = true;
2939
            }
2940
            if (alterClient) {
2941
                try {
2942
                    ds.execute(tClient.asString());
2943
                    tableClient.getSchema().updateVersion();
2944
                } catch (SQLException ex) {
2945
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table CLIENT", ex);
2946
                }
2947
            }
18 ilm 2948
        }
2949
 
19 ilm 2950
        // Change Pays
2951
        {
2952
            SQLTable tablePays = root.getTable("PAYS");
2953
 
2954
            AlterTable tPays = new AlterTable(tablePays);
2955
            boolean alterPays = false;
2956
 
2957
            if (!tablePays.getFieldsName().contains("ID_TARIF")) {
61 ilm 2958
                tPays.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
19 ilm 2959
                alterPays = true;
2960
            }
2961
            if (!tablePays.getFieldsName().contains("ID_LANGUE")) {
61 ilm 2962
                tPays.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
19 ilm 2963
                alterPays = true;
2964
            }
2965
            if (alterPays) {
2966
                try {
2967
                    ds.execute(tPays.asString());
2968
                    tablePays.getSchema().updateVersion();
2969
                } catch (SQLException ex) {
2970
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table PAYS", ex);
2971
                }
2972
            }
2973
        }
2974
        // Change Commande
2975
        {
2976
            SQLTable tableCmd = root.getTable("COMMANDE");
2977
 
2978
            AlterTable tCmd = new AlterTable(tableCmd);
2979
            boolean alterCmd = false;
2980
 
2981
            if (!tableCmd.getFieldsName().contains("EN_COURS")) {
2982
                tCmd.addColumn("EN_COURS", "boolean default true");
2983
                alterCmd = true;
2984
            }
2985
            if (alterCmd) {
2986
                try {
2987
                    ds.execute(tCmd.asString());
2988
                    tableCmd.getSchema().updateVersion();
2989
                } catch (SQLException ex) {
2990
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table COMMANDE", ex);
2991
                }
2992
            }
2993
        }
65 ilm 2994
 
2995
        // Change VF
2996
        {
2997
            SQLTable tableVenteFacture = root.getTable("SAISIE_VENTE_FACTURE");
2998
 
2999
            AlterTable tVF = new AlterTable(tableVenteFacture);
3000
            boolean alterVF = false;
3001
 
3002
            if (!tableVenteFacture.getFieldsName().contains("ID_TAXE_PORT")) {
3003
                tVF.addForeignColumn("ID_TAXE_PORT", root.findTable("TAXE"));
3004
                alterVF = true;
3005
            }
3006
            if (alterVF) {
3007
                try {
3008
                    ds.execute(tVF.asString());
3009
                    tableVenteFacture.getSchema().updateVersion();
3010
                } catch (SQLException ex) {
3011
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table SAISIE_VENTE_FACTURE", ex);
3012
                }
3013
            }
3014
        }
3015
 
19 ilm 3016
        // Change Fournisseur
3017
        {
3018
            SQLTable tableFournisseur = root.getTable("FOURNISSEUR");
3019
 
3020
            AlterTable tFourn = new AlterTable(tableFournisseur);
3021
            boolean alterFourn = false;
3022
 
3023
            if (!tableFournisseur.getFieldsName().contains("ID_LANGUE")) {
61 ilm 3024
                tFourn.addForeignColumn("ID_LANGUE", root.findTable("LANGUE", true));
19 ilm 3025
                alterFourn = true;
3026
            }
3027
            if (!tableFournisseur.getFieldsName().contains("ID_DEVISE")) {
61 ilm 3028
                tFourn.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
19 ilm 3029
                alterFourn = true;
3030
            }
3031
            if (!tableFournisseur.getFieldsName().contains("RESPONSABLE")) {
3032
                tFourn.addVarCharColumn("RESPONSABLE", 256);
3033
                alterFourn = true;
3034
            }
3035
            if (!tableFournisseur.getFieldsName().contains("TEL_P")) {
3036
                tFourn.addVarCharColumn("TEL_P", 256);
3037
                alterFourn = true;
3038
            }
3039
            if (!tableFournisseur.getFieldsName().contains("MAIL")) {
3040
                tFourn.addVarCharColumn("MAIL", 256);
3041
                alterFourn = true;
3042
            }
3043
            if (!tableFournisseur.getFieldsName().contains("INFOS")) {
3044
                tFourn.addVarCharColumn("INFOS", 2048);
3045
                alterFourn = true;
3046
            }
3047
 
3048
            if (alterFourn) {
3049
                try {
3050
                    ds.execute(tFourn.asString());
3051
                    tableFournisseur.getSchema().updateVersion();
3052
                } catch (SQLException ex) {
3053
                    throw new IllegalStateException("Erreur lors de l'ajout des champs sur la table FOURNISSEUR", ex);
3054
                }
3055
            }
3056
        }
3057
 
41 ilm 3058
        updateN4DS(root);
3059
 
19 ilm 3060
        root.refetch();
18 ilm 3061
    }
3062
 
41 ilm 3063
    /**
3064
     * Mise à jour du schéma pour N4DS
3065
     *
3066
     * @param root
3067
     * @throws SQLException
3068
     */
3069
    private void updateN4DS(DBRoot root) throws SQLException {
3070
 
3071
        {
3072
            SQLTable table = root.findTable("INFOS_SALARIE_PAYE");
3073
            boolean alter = false;
3074
            AlterTable t = new AlterTable(table);
3075
            if (!table.getFieldsName().contains("CODE_AT")) {
3076
                t.addVarCharColumn("CODE_AT", 18);
3077
                alter = true;
3078
            }
3079
            if (!table.getFieldsName().contains("CODE_SECTION_AT")) {
3080
                t.addVarCharColumn("CODE_SECTION_AT", 18);
3081
                alter = true;
3082
            }
3083
 
3084
            if (alter) {
3085
                try {
3086
                    table.getBase().getDataSource().execute(t.asString());
3087
                    table.getSchema().updateVersion();
3088
                    table.fetchFields();
3089
                } catch (SQLException ex) {
3090
                    throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3091
                }
3092
            }
3093
 
3094
        }
3095
 
3096
        if (!root.contains("CODE_STATUT_CAT_CONV")) {
3097
 
3098
            SQLCreateTable createTarif = new SQLCreateTable(root, "CODE_STATUT_CAT_CONV");
3099
 
3100
            createTarif.addVarCharColumn("CODE", 6);
3101
            createTarif.addVarCharColumn("NOM", 256);
3102
            createTarif.asString();
3103
            try {
3104
                root.getBase().getDataSource().execute(createTarif.asString());
3105
                insertUndef(createTarif);
3106
 
3107
                String insert = "INSERT into " + getTableName(createTarif).quote() + "(\"CODE\",\"NOM\") VALUES ";
3108
                insert += " ('01','agriculteur salarié de son exploitation')";
3109
                insert += ", ('02','artisan ou commerçant salarié de son entreprise')";
3110
                insert += ", ('03','cadre dirigeant (votant au collège employeur des élections prud''''hommales)')";
3111
                insert += ", ('04','autres cadres au sens de la convention collective (ou du statut pour les régimes spéciaux)')";
3112
                insert += ", ('05','profession intermédiaire (technicien, contremaître, agent de maîtrise, clergé)')";
3113
                insert += ", ('06','employé administratif d''''entreprise, de commerce, agent de service')";
3114
                insert += ", ('07','ouvriers qualifiés et non qualifiés y compris ouvriers agricoles');";
3115
                createTarif.getRoot().getDBSystemRoot().getDataSource().execute(insert);
3116
 
3117
                root.getSchema().updateVersion();
3118
                root.refetch();
3119
            } catch (SQLException ex) {
3120
                throw new IllegalStateException("Erreur lors de la création de la table CODE_STATUT_CAT_CONV", ex);
3121
            }
3122
        }
3123
 
3124
        // Création de la table Modéle
3125
        if (!root.contains("CONTACT_ADMINISTRATIF")) {
3126
 
3127
            SQLCreateTable createModele = new SQLCreateTable(root, "CONTACT_ADMINISTRATIF");
3128
            createModele.addVarCharColumn("NOM", 256);
3129
            createModele.addVarCharColumn("PRENOM", 256);
3130
            createModele.addVarCharColumn("TEL_DIRECT", 256);
3131
            createModele.addVarCharColumn("TEL_MOBILE", 256);
3132
            createModele.addVarCharColumn("EMAIL", 256);
3133
            createModele.addVarCharColumn("FAX", 256);
3134
            createModele.addVarCharColumn("FONCTION", 256);
3135
            createModele.addVarCharColumn("TEL_PERSONEL", 256);
3136
            createModele.addVarCharColumn("TEL_STANDARD", 256);
3137
            createModele.addForeignColumn("ID_TITRE_PERSONNEL", root.findTable("TITRE_PERSONNEL"));
3138
            createModele.addColumn("N4DS", "boolean DEFAULT false");
3139
 
3140
            try {
3141
                root.getBase().getDataSource().execute(createModele.asString());
3142
                insertUndef(createModele);
3143
                root.getSchema().updateVersion();
3144
            } catch (SQLException ex) {
3145
                throw new IllegalStateException("Erreur lors de la création de la table MODELE", ex);
3146
            }
3147
        }
3148
 
3149
        {
61 ilm 3150
            SQLTable tableContrat = root.findTable("CONTRAT_SALARIE", true);
41 ilm 3151
            boolean alter2 = false;
3152
            AlterTable t2 = new AlterTable(tableContrat);
3153
            // UGRR
3154
            if (!tableContrat.getFieldsName().contains("CODE_IRC_UGRR")) {
3155
                t2.addVarCharColumn("CODE_IRC_UGRR", 18);
3156
                alter2 = true;
3157
            }
3158
            if (!tableContrat.getFieldsName().contains("NUMERO_RATTACHEMENT_UGRR")) {
3159
                t2.addVarCharColumn("NUMERO_RATTACHEMENT_UGRR", 64);
3160
                alter2 = true;
3161
            }
3162
            // UGRC
3163
            if (!tableContrat.getFieldsName().contains("CODE_IRC_UGRC")) {
3164
                t2.addVarCharColumn("CODE_IRC_UGRC", 18);
3165
                alter2 = true;
3166
            }
3167
            if (!tableContrat.getFieldsName().contains("NUMERO_RATTACHEMENT_UGRC")) {
3168
                t2.addVarCharColumn("NUMERO_RATTACHEMENT_UGRC", 64);
3169
                alter2 = true;
3170
            }
3171
 
3172
            // Retraite Compl
3173
            if (!tableContrat.getFieldsName().contains("CODE_IRC_RETRAITE")) {
3174
                t2.addVarCharColumn("CODE_IRC_RETRAITE", 18);
3175
                alter2 = true;
3176
            }
3177
            if (!tableContrat.getFieldsName().contains("NUMERO_RATTACHEMENT_RETRAITE")) {
3178
                t2.addVarCharColumn("NUMERO_RATTACHEMENT_RETRAITE", 64);
3179
                alter2 = true;
3180
            }
3181
 
3182
            if (!tableContrat.getFieldsName().contains("ID_CODE_STATUT_CAT_CONV")) {
61 ilm 3183
                t2.addForeignColumn("ID_CODE_STATUT_CAT_CONV", root.findTable("CODE_STATUT_CAT_CONV", true));
41 ilm 3184
                alter2 = true;
3185
            }
3186
 
3187
            if (alter2) {
3188
                try {
3189
                    tableContrat.getBase().getDataSource().execute(t2.asString());
3190
                    tableContrat.getSchema().updateVersion();
3191
                    tableContrat.fetchFields();
3192
                } catch (SQLException ex) {
3193
                    throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + tableContrat.getName(), ex);
3194
                }
3195
            }
3196
 
3197
        }
3198
    }
3199
 
19 ilm 3200
    private void addDeviseHAField(SQLTable table, DBRoot root) throws SQLException {
3201
        boolean alter = false;
3202
        AlterTable t = new AlterTable(table);
3203
        if (!table.getFieldsName().contains("ID_DEVISE")) {
61 ilm 3204
            t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
19 ilm 3205
            alter = true;
3206
        }
3207
 
3208
        if (!table.getFieldsName().contains("T_DEVISE")) {
3209
            t.addColumn("T_DEVISE", "bigint default 0");
3210
            alter = true;
3211
        }
3212
 
3213
        if (alter) {
3214
            try {
3215
                table.getBase().getDataSource().execute(t.asString());
3216
                table.getSchema().updateVersion();
3217
                table.fetchFields();
3218
            } catch (SQLException ex) {
3219
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3220
            }
3221
        }
3222
 
3223
    }
3224
 
67 ilm 3225
    private void patchFieldElt1Dot3(SQLTable table, DBRoot root) {
3226
 
3227
        List<String> cols = Arrays.asList("PV_HT", "PA_DEVISE_T", "T_PV_HT", "T_PA_TTC", "T_PA_HT", "PA_HT", "T_PV_TTC", "PRIX_METRIQUE_HA_2", "PRIX_METRIQUE_HA_1", "PRIX_METRIQUE_HA_3",
73 ilm 3228
                "PRIX_METRIQUE_VT_2", "PRIX_METRIQUE_VT_1", "MONTANT_HT", "MONTANT_INITIAL", "PRIX_METRIQUE_VT_3", "MARGE_HT", "PA_DEVISE", "PV_U_DEVISE", "PV_T_DEVISE", "PV_TTC", "TARIF_Q18_HT",
90 ilm 3229
                "T_PRIX_FINAL_TTC", "PRIX_FINAL_TTC", "PV_UNIT_HT", "PREBILAN", "MARGE_PREBILAN_HT");
177 ilm 3230
        if (table == null) {
3231
            return;
3232
        }
132 ilm 3233
        if ((table.contains("PV_HT") && table.getField("PV_HT").getType().getDecimalDigits() == 0)
3234
                || (table.contains("PV_UNIT_HT") && table.getField("PV_UNIT_HT").getType().getDecimalDigits() == 0)) {
67 ilm 3235
            AlterTable t = new AlterTable(table);
3236
            UpdateBuilder builder = new UpdateBuilder(table);
73 ilm 3237
            List<UpdateBuilder> builds = new ArrayList<UpdateBuilder>();
67 ilm 3238
            for (String field : cols) {
3239
                if (table.contains(field)) {
73 ilm 3240
                    UpdateBuilder builderNonNull = new UpdateBuilder(table);
3241
                    builderNonNull.set(field, "0");
3242
                    builderNonNull.setWhere(new Where(table.getField(field), "=", (Object) null));
3243
                    builds.add(builderNonNull);
3244
 
67 ilm 3245
                    builder.set(field, table.getField(field).getSQLName().getRest().quote() + "/100");
3246
                    if (field.contains("TTC")) {
3247
                        t.alterColumn(field, EnumSet.allOf(Properties.class), "numeric(16,2)", "0", false);
3248
                    } else {
3249
                        t.alterColumn(field, EnumSet.allOf(Properties.class), "numeric(16,6)", "0", false);
3250
                    }
3251
                }
3252
            }
3253
 
3254
            try {
73 ilm 3255
 
3256
                for (UpdateBuilder updateBuilder : builds) {
3257
                    table.getBase().getDataSource().execute(updateBuilder.asString());
3258
                }
3259
 
67 ilm 3260
                table.getBase().getDataSource().execute(t.asString());
3261
                table.getSchema().updateVersion();
3262
                table.fetchFields();
3263
            } catch (SQLException ex) {
3264
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3265
            }
3266
 
3267
            String req2 = builder.asString();
3268
            root.getDBSystemRoot().getDataSource().execute(req2);
3269
        }
3270
 
3271
    }
3272
 
93 ilm 3273
    private void patchFieldElt1Dot4(SQLTable table, DBRoot root) throws SQLException {
83 ilm 3274
 
3275
        if (!table.contains("MONTANT_REMISE")) {
3276
            AlterTable t = new AlterTable(table);
3277
            t.alterColumn("POURCENT_REMISE", EnumSet.allOf(Properties.class), "numeric(12,8)", "0", true);
3278
            t.addColumn("MONTANT_REMISE", "numeric (16,8)");
3279
 
3280
            try {
3281
 
3282
                table.getBase().getDataSource().execute(t.asString());
3283
                table.getSchema().updateVersion();
3284
                table.fetchFields();
3285
            } catch (SQLException ex) {
3286
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3287
            }
3288
        }
93 ilm 3289
 
3290
        if (!table.contains("ID_FAMILLE_ARTICLE")) {
3291
            AlterTable t = new AlterTable(table);
3292
            t.addForeignColumn("ID_FAMILLE_ARTICLE", root.getTable("FAMILLE_ARTICLE"));
3293
 
3294
            try {
3295
 
3296
                table.getBase().getDataSource().execute(t.asString());
3297
                table.getSchema().updateVersion();
3298
                table.fetchFields();
3299
            } catch (SQLException ex) {
3300
                throw new IllegalStateException("Erreur lors de l'ajout du champs ID_FAMILLE_ARTICLE à la table " + table.getName(), ex);
3301
            }
3302
        }
3303
 
3304
        addNiveauElementField(table);
3305
    }
3306
 
3307
    private void addNiveauElementField(SQLTable table) throws SQLException {
3308
 
83 ilm 3309
        if (!table.contains("NIVEAU")) {
3310
            AlterTable t = new AlterTable(table);
3311
            t.addIntegerColumn("NIVEAU", 1);
3312
            try {
3313
                table.getBase().getDataSource().execute(t.asString());
3314
                table.getSchema().updateVersion();
3315
                table.fetchFields();
3316
            } catch (SQLException ex) {
3317
                throw new IllegalStateException("Erreur lors de l'ajout du niveau à la table " + table.getName(), ex);
3318
            }
3319
        }
3320
 
3321
    }
3322
 
41 ilm 3323
    private void addHAElementField(SQLTable table, DBRoot root) throws SQLException {
67 ilm 3324
 
19 ilm 3325
        boolean alter = false;
3326
        AlterTable t = new AlterTable(table);
3327
        if (!table.getFieldsName().contains("QTE_ACHAT")) {
3328
            t.addColumn("QTE_ACHAT", "integer DEFAULT 1");
3329
            alter = true;
3330
        }
61 ilm 3331
        if (!table.getFieldsName().contains("QTE_UNITAIRE")) {
3332
            t.addColumn("QTE_UNITAIRE", "numeric(16,6) DEFAULT 1");
3333
            alter = true;
3334
        }
3335
        if (!table.getFieldsName().contains("ID_UNITE_VENTE")) {
3336
            t.addForeignColumn("ID_UNITE_VENTE", root.findTable("UNITE_VENTE", true).getSQLName(), "ID", "2");
3337
            alter = true;
3338
        }
3339
        if (!table.getFieldsName().contains("ID_ARTICLE")) {
3340
            t.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
3341
            alter = true;
3342
        }
19 ilm 3343
        if (!table.getFieldsName().contains("PA_DEVISE")) {
3344
            t.addColumn("PA_DEVISE", "bigint default 0");
3345
            alter = true;
3346
        }
3347
        if (!table.getFieldsName().contains("ID_DEVISE")) {
61 ilm 3348
            t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
19 ilm 3349
            alter = true;
3350
        }
3351
 
3352
        if (!table.getFieldsName().contains("PA_DEVISE_T")) {
3353
            t.addColumn("PA_DEVISE_T", "bigint default 0");
3354
            alter = true;
3355
        }
93 ilm 3356
        if (!table.getFieldsName().contains("DESCRIPTIF")) {
3357
            t.addVarCharColumn("DESCRIPTIF", 2048);
3358
            alter = true;
3359
        }
19 ilm 3360
 
67 ilm 3361
        // if (!table.getFieldsName().contains("POURCENT_REMISE")) {
3362
        // t.addColumn("POURCENT_REMISE", "numeric(16,2) DEFAULT 0");
3363
        // alter = true;
3364
        // }
3365
 
19 ilm 3366
        if (alter) {
3367
            try {
3368
                table.getBase().getDataSource().execute(t.asString());
3369
                table.getSchema().updateVersion();
3370
                table.fetchFields();
3371
            } catch (SQLException ex) {
3372
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3373
            }
3374
        }
67 ilm 3375
        patchFieldElt1Dot3(table, root);
19 ilm 3376
    }
3377
 
93 ilm 3378
    private void addRemiseField(SQLTable table, DBRoot root) throws SQLException {
3379
 
3380
        AlterTable t = new AlterTable(table);
3381
        boolean alter = false;
3382
        if (!table.contains("POURCENT_REMISE")) {
3383
            t.addColumn("POURCENT_REMISE", "numeric (12,8)");
3384
            alter = true;
3385
        }
3386
        if (!table.contains("MONTANT_REMISE")) {
3387
            t.addColumn("MONTANT_REMISE", "numeric (16,8)");
3388
            alter = true;
3389
        }
3390
        if (alter) {
3391
            try {
3392
 
3393
                table.getBase().getDataSource().execute(t.asString());
3394
                table.getSchema().updateVersion();
3395
                table.fetchFields();
3396
            } catch (SQLException ex) {
3397
                throw new IllegalStateException("Erreur lors de l'ajout des champs remise à la table " + table.getName(), ex);
3398
            }
3399
        }
3400
    }
3401
 
3402
    private void addAdresseField(SQLTable table, DBRoot root) throws SQLException {
3403
        boolean alter = false;
3404
        AlterTable t = new AlterTable(table);
3405
        if (!table.getFieldsName().contains("ID_ADRESSE")) {
3406
            t.addForeignColumn("ID_ADRESSE", root.findTable("ADRESSE"));
3407
            alter = true;
3408
        }
3409
 
3410
        if (!table.getFieldsName().contains("ID_ADRESSE_LIVRAISON")) {
3411
            t.addForeignColumn("ID_ADRESSE_LIVRAISON", root.findTable("ADRESSE"));
3412
            alter = true;
3413
        }
3414
 
3415
        if (alter) {
3416
            try {
3417
                table.getBase().getDataSource().execute(t.asString());
3418
                table.getSchema().updateVersion();
3419
                table.fetchFields();
3420
            } catch (SQLException ex) {
3421
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3422
            }
3423
        }
3424
    }
3425
 
21 ilm 3426
    private void addModeleField(SQLTable table, DBRoot root) throws SQLException {
3427
        boolean alter = false;
3428
        AlterTable t = new AlterTable(table);
3429
        if (!table.getFieldsName().contains("ID_MODELE")) {
3430
            t.addForeignColumn("ID_MODELE", root.findTable("MODELE"));
3431
            alter = true;
3432
        }
3433
 
3434
        if (alter) {
3435
            try {
3436
                table.getBase().getDataSource().execute(t.asString());
3437
                table.getSchema().updateVersion();
3438
                table.fetchFields();
3439
            } catch (SQLException ex) {
3440
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3441
            }
3442
        }
3443
    }
3444
 
19 ilm 3445
    private void addTotalDeviseField(SQLTable table, DBRoot root) throws SQLException {
3446
        boolean alter = false;
3447
        AlterTable t = new AlterTable(table);
3448
        if (!table.getFieldsName().contains("T_DEVISE")) {
3449
            t.addColumn("T_DEVISE", "bigint default 0");
3450
            alter = true;
3451
        } else {
3452
            table.getBase().getDataSource().execute("UPDATE " + table.getSQLName().quote() + " SET \"T_DEVISE\"=0 WHERE \"T_DEVISE\" IS NULL");
3453
            t.alterColumn("T_DEVISE", EnumSet.allOf(Properties.class), "bigint", "0", false);
3454
        }
3455
        if (!table.getFieldsName().contains("T_POIDS")) {
3456
            t.addColumn("T_POIDS", "real default 0");
3457
            alter = true;
3458
        }
3459
        if (!table.getFieldsName().contains("ID_TARIF")) {
61 ilm 3460
            t.addForeignColumn("ID_TARIF", root.findTable("TARIF", true));
19 ilm 3461
            alter = true;
3462
        }
3463
 
3464
        if (alter) {
3465
            try {
3466
                table.getBase().getDataSource().execute(t.asString());
3467
                table.getSchema().updateVersion();
3468
                table.fetchFields();
3469
            } catch (SQLException ex) {
3470
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3471
            }
3472
        }
3473
    }
3474
 
41 ilm 3475
    private void addVenteEltField(SQLTable table, DBRoot root) throws SQLException {
19 ilm 3476
 
3477
        boolean alter = false;
3478
        AlterTable t = new AlterTable(table);
3479
        if (!table.getFieldsName().contains("QTE_ACHAT")) {
3480
            t.addColumn("QTE_ACHAT", "integer DEFAULT 1");
3481
            alter = true;
3482
        }
61 ilm 3483
        if (!table.getFieldsName().contains("QTE_UNITAIRE")) {
3484
            t.addColumn("QTE_UNITAIRE", "numeric(16,6) DEFAULT 1");
3485
            alter = true;
3486
        }
3487
        if (!table.getFieldsName().contains("ID_UNITE_VENTE")) {
3488
            t.addForeignColumn("ID_UNITE_VENTE", root.findTable("UNITE_VENTE", true).getSQLName(), "ID", "2");
3489
            alter = true;
3490
        }
3491
        if (!table.getFieldsName().contains("ID_ARTICLE")) {
3492
            t.addForeignColumn("ID_ARTICLE", root.findTable("ARTICLE", true));
3493
            alter = true;
3494
        }
19 ilm 3495
        if (!table.getFieldsName().contains("CODE_DOUANIER")) {
3496
            t.addVarCharColumn("CODE_DOUANIER", 256);
3497
            alter = true;
3498
        }
21 ilm 3499
        if (!table.getFieldsName().contains("DESCRIPTIF")) {
3500
            t.addVarCharColumn("DESCRIPTIF", 2048);
3501
            alter = true;
3502
        }
19 ilm 3503
        if (!table.getFieldsName().contains("ID_PAYS")) {
61 ilm 3504
            t.addForeignColumn("ID_PAYS", root.findTable("PAYS", true));
19 ilm 3505
            alter = true;
3506
        }
21 ilm 3507
        if (!table.getFieldsName().contains("MARGE_HT")) {
3508
            t.addColumn("MARGE_HT", "bigint default 0");
3509
            alter = true;
3510
        }
19 ilm 3511
 
3512
        if (!table.getFieldsName().contains("ID_DEVISE")) {
61 ilm 3513
            t.addForeignColumn("ID_DEVISE", root.findTable("DEVISE", true));
19 ilm 3514
            alter = true;
3515
        }
3516
        if (!table.getFieldsName().contains("PV_U_DEVISE")) {
3517
            t.addColumn("PV_U_DEVISE", "bigint default 0");
3518
            alter = true;
3519
        }
3520
        if (!table.getFieldsName().contains("POURCENT_REMISE")) {
3521
            t.addColumn("POURCENT_REMISE", "numeric(6,2) default 0");
3522
            alter = true;
3523
        }
3524
        if (!table.getFieldsName().contains("PV_T_DEVISE")) {
3525
            t.addColumn("PV_T_DEVISE", "bigint default 0");
3526
            alter = true;
3527
        }
3528
        if (!table.getFieldsName().contains("TAUX_DEVISE")) {
3529
            t.addColumn("TAUX_DEVISE", "numeric (16,8) DEFAULT 1");
3530
            alter = true;
3531
        }
80 ilm 3532
 
3533
        if (!table.getFieldsName().contains("POIDS_COLIS_NET")) {
3534
            t.addColumn("POIDS_COLIS_NET", "numeric (16,8) DEFAULT 1");
3535
            alter = true;
3536
        }
3537
 
3538
        if (!table.getFieldsName().contains("T_POIDS_COLIS_NET")) {
3539
            t.addColumn("T_POIDS_COLIS_NET", "numeric (16,8) DEFAULT 1");
3540
            alter = true;
3541
        }
3542
 
3543
        if (!table.getFieldsName().contains("NB_COLIS")) {
3544
            t.addColumn("NB_COLIS", "integer DEFAULT 0");
3545
            alter = true;
3546
        }
19 ilm 3547
        if (alter) {
3548
            try {
3549
                root.getDBSystemRoot().getDataSource().execute(t.asString());
3550
                table.getSchema().updateVersion();
3551
                table.fetchFields();
3552
            } catch (SQLException ex) {
3553
                throw new IllegalStateException("Erreur lors de l'ajout des champs à la table " + table.getName(), ex);
3554
            }
3555
        }
67 ilm 3556
        patchFieldElt1Dot3(table, root);
19 ilm 3557
    }
3558
 
182 ilm 3559
    private void updateSocieteSchema(final DBRoot root) throws IOException, Exception {
19 ilm 3560
        final DBSystemRoot sysRoot = root.getDBSystemRoot();
3561
        final SQLDataSource ds = sysRoot.getDataSource();
3562
        System.out.println("InstallationPanel.InstallationPanel() UPDATE COMMERCIAL " + root);
3563
        // Fix commercial Ordre
57 ilm 3564
 
19 ilm 3565
        SQLTable tableCommercial = root.getTable("COMMERCIAL");
3566
        CorrectOrder orderCorrect = new CorrectOrder(sysRoot);
3567
        orderCorrect.change(tableCommercial);
3568
 
80 ilm 3569
        sysRoot.reload(Collections.singleton(root.getName()));
19 ilm 3570
 
3571
        try {
3572
            // Add article
3573
            final SQLTable tableArticle = root.getTable("ARTICLE");
3574
            if (!tableArticle.getFieldsName().contains("INFOS")) {
3575
                AlterTable t = new AlterTable(tableArticle);
3576
                t.addVarCharColumn("INFOS", 2048);
3577
                try {
3578
                    ds.execute(t.asString());
3579
                } catch (Exception ex) {
3580
                    throw new IllegalStateException("Erreur lors de l'ajout du champ INFO à la table ARTICLE", ex);
3581
                }
3582
            }
3583
 
3584
            if (sysRoot.getServer().getSQLSystem().equals(SQLSystem.POSTGRESQL)) {
3585
                // Fix Caisse serial
3586
                SQLTable tableCaisse = root.getTable("CAISSE");
3587
 
3588
                FixSerial f = new FixSerial(sysRoot);
3589
                try {
3590
                    f.change(tableCaisse);
3591
                } catch (SQLException e2) {
3592
                    throw new IllegalStateException("Erreur lors la mise à jours des sequences de la table CAISSE", e2);
3593
                }
3594
            }
3595
            System.out.println("InstallationPanel.InstallationPanel() UPDATE TICKET_CAISSE " + root);
3596
            // add Mvt on Ticket
3597
            SQLTable tableTicket = root.getTable("TICKET_CAISSE");
3598
            if (!tableTicket.getFieldsName().contains("ID_MOUVEMENT")) {
3599
                AlterTable t = new AlterTable(tableTicket);
3600
                t.addForeignColumn("ID_MOUVEMENT", root.getTable("MOUVEMENT"));
3601
                try {
3602
                    ds.execute(t.asString());
3603
                } catch (Exception ex) {
3604
                    throw new IllegalStateException("Erreur lors de l'ajout du champ ID_MOUVEMENT à la table TICKET_CAISSE", ex);
3605
                }
3606
            }
3607
 
3608
            // Check type de reglement
3609
 
3610
            System.out.println("InstallationPanel.InstallationPanel() UPDATE TYPE_REGLEMENT " + root);
3611
            SQLTable tableReglmt = root.getTable("TYPE_REGLEMENT");
3612
            SQLSelect sel = new SQLSelect(tableReglmt.getBase());
3613
            sel.addSelect(tableReglmt.getKey());
3614
            sel.setWhere(new Where(tableReglmt.getField("NOM"), "=", "Virement"));
3615
            List<Number> l = (List<Number>) ds.executeCol(sel.asString());
3616
            if (l.size() == 0) {
3617
                SQLRowValues rowVals = new SQLRowValues(tableReglmt);
3618
                rowVals.put("NOM", "Virement");
3619
                rowVals.put("COMPTANT", Boolean.FALSE);
3620
                rowVals.put("ECHEANCE", Boolean.FALSE);
3621
                try {
3622
                    rowVals.commit();
3623
                } catch (SQLException e) {
3624
                    throw new IllegalStateException("Erreur lors de l'ajout du type de paiement par virement", e);
3625
                }
3626
            }
3627
 
67 ilm 3628
            SQLSelect sel2 = new SQLSelect();
19 ilm 3629
            sel2.addSelect(tableReglmt.getKey());
3630
            sel2.setWhere(new Where(tableReglmt.getField("NOM"), "=", "CESU"));
67 ilm 3631
            @SuppressWarnings("unchecked")
19 ilm 3632
            List<Number> l2 = (List<Number>) ds.executeCol(sel2.asString());
3633
            if (l2.size() == 0) {
3634
                SQLRowValues rowVals = new SQLRowValues(tableReglmt);
3635
                rowVals.put("NOM", "CESU");
3636
                rowVals.put("COMPTANT", Boolean.FALSE);
3637
                rowVals.put("ECHEANCE", Boolean.FALSE);
3638
                try {
3639
                    rowVals.commit();
3640
                } catch (SQLException e) {
3641
                    throw new IllegalStateException("Erreur lors de l'ajout du type CESU", e);
3642
                }
3643
            }
3644
            System.out.println("InstallationPanel.InstallationPanel() UPDATE FAMILLE_ARTICLE " + root);
3645
            //
3646
            final SQLTable tableFam = root.getTable("FAMILLE_ARTICLE");
3647
            final int nomSize = 256;
3648
            if (tableFam.getField("NOM").getType().getSize() < nomSize) {
3649
                final AlterTable t = new AlterTable(tableFam);
3650
                t.alterColumn("NOM", EnumSet.allOf(Properties.class), "varchar(" + nomSize + ")", "''", false);
3651
                try {
3652
                    ds.execute(t.asString());
3653
                } catch (Exception ex) {
3654
                    throw new IllegalStateException("Erreur lors de la modification du champs NOM sur la table FAMILLE_ARTICLE", ex);
3655
                }
3656
            }
3657
 
3658
            // Suppression des champs 1.0
3659
            System.out.println("InstallationPanel.InstallationPanel() UPDATE FROM 1.0 " + root);
3660
            final List<ChangeTable<?>> changes = new ArrayList<ChangeTable<?>>();
3661
 
61 ilm 3662
            final ModuleManager instance = new ModuleManager();
182 ilm 3663
            instance.setRoot(root);
80 ilm 3664
            final Collection<ModuleReference> refs = instance.getModulesInstalledRemotely();
61 ilm 3665
            final Set<String> allUsedTable = new HashSet<String>();
67 ilm 3666
            for (ModuleReference ref : refs) {
80 ilm 3667
                Set<String> tableNames = instance.getCreatedItems(ref.getID()).get0();
61 ilm 3668
                allUsedTable.addAll(tableNames);
3669
            }
80 ilm 3670
            System.out.println("Tables created by modules:" + allUsedTable);
19 ilm 3671
 
3672
            final List<String> alterRequests = ChangeTable.cat(changes, root.getName());
3673
            try {
3674
                for (final String req : alterRequests) {
3675
                    ds.execute(req);
3676
                }
3677
            } catch (Exception e1) {
3678
                throw new IllegalStateException("Erreur lors de la mise à jour des tables v1.0", e1);
3679
            }
3680
            System.out.println("InstallationPanel.InstallationPanel() UPDATE CAISSE " + root);
3681
            // Undefined
3682
            try {
3683
                SQLTable.setUndefID(tableTicket.getSchema(), tableTicket.getName(), 1);
3684
                SQLTable.setUndefID(tableTicket.getSchema(), "CAISSE", 1);
3685
            } catch (SQLException e1) {
3686
                throw new IllegalStateException("Erreur lors de la mise à jour des indéfinis de la table CAISSE", e1);
3687
            }
83 ilm 3688
        } catch (Exception e) {
3689
            ExceptionHandler.handle("updateSocieteSchema on root " + root + " failed", e);
19 ilm 3690
        } finally {
3691
            // Mise à jour du schéma
3692
            root.getSchema().updateVersion();
3693
            root.refetch();
3694
        }
3695
    }
3696
 
73 ilm 3697
    private void checkRights(DBRoot root) throws SQLException {
80 ilm 3698
        SQLTable table = root.findTable("RIGHT");
73 ilm 3699
        SQLSelect sel = new SQLSelect();
3700
        sel.addSelect(table.getKey());
3701
        sel.addSelect(table.getField("CODE"));
3702
        List<SQLRow> rows = SQLRowListRSH.execute(sel);
3703
        Set<String> codes = new HashSet<String>();
3704
        for (SQLRow row : rows) {
3705
            codes.add(row.getString("CODE"));
3706
        }
3707
 
3708
        if (!codes.contains("UPDATE_ROW")) {
3709
            SQLRowValues rowVals = new SQLRowValues(table);
3710
            rowVals.put("CODE", "UPDATE_ROW");
3711
            rowVals.put("NOM", "Modification d'une ligne");
3712
            String desc = "Autorise un utilisateur à modifier les éléments de la table spécifiée en objet.";
3713
            rowVals.put("DESCRIPTION", desc);
3714
            rowVals.commit();
3715
        }
3716
        if (!codes.contains("DELETE_ROW")) {
3717
            SQLRowValues rowVals = new SQLRowValues(table);
3718
            rowVals.put("CODE", "DELETE_ROW");
3719
            rowVals.put("NOM", "Suppression d'une ligne");
3720
            String desc = "Autorise un utilisateur à supprimer les éléments de la table spécifiée en objet.";
3721
            rowVals.put("DESCRIPTION", desc);
3722
            rowVals.commit();
3723
        }
3724
        if (!codes.contains("INSERT_ROW")) {
3725
            SQLRowValues rowVals = new SQLRowValues(table);
3726
            rowVals.put("CODE", "INSERT_ROW");
3727
            rowVals.put("NOM", "Ajout d'une ligne");
3728
            String desc = "Autorise un utilisateur à ajouter un élément dans la table spécifiée en objet.";
3729
            rowVals.put("DESCRIPTION", desc);
3730
            rowVals.commit();
3731
        }
93 ilm 3732
        if (!codes.contains("SAVE_ROW")) {
3733
            SQLRowValues rowVals = new SQLRowValues(table);
3734
            rowVals.put("CODE", "SAVE_ROW");
3735
            rowVals.put("NOM", "Export des listes");
3736
            String desc = "Autorise un utilisateur à exporter le contenu des listes via le bouton représentant une disquette.";
3737
            rowVals.put("DESCRIPTION", desc);
3738
            SQLRow row = rowVals.commit();
3739
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3740
            rowValsUserRight.put("ID_RIGHT", row.getID());
3741
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3742
            rowValsUserRight.commit();
3743
        }
3744
 
182 ilm 3745
        if (!codes.contains(DepotStockViewRightEditor.ID_RIGHT)) {
3746
            SQLRowValues rowVals = new SQLRowValues(table);
3747
            rowVals.put("CODE", DepotStockViewRightEditor.ID_RIGHT);
3748
            rowVals.put("NOM", "Voir le stock d'un dépôt");
3749
            String desc = "Autorise un utilisateur à visualiser le stock d'un dépôt.";
3750
            rowVals.put("DESCRIPTION", desc);
3751
            SQLRow row = rowVals.commit();
3752
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3753
            rowValsUserRight.put("ID_RIGHT", row.getID());
3754
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3755
            rowValsUserRight.commit();
3756
        }
3757
 
93 ilm 3758
        if (!codes.contains("MENU_ACCESS")) {
3759
            SQLRowValues rowVals = new SQLRowValues(table);
3760
            rowVals.put("CODE", "MENU_ACCESS");
3761
            rowVals.put("NOM", "Autoriser l'accés à un menu");
3762
            String desc = "Autorise un utilisateur à visualiser le menu spécifié en objet.";
3763
            rowVals.put("DESCRIPTION", desc);
3764
            SQLRow row = rowVals.commit();
3765
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3766
            rowValsUserRight.put("ID_RIGHT", row.getID());
3767
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3768
            rowValsUserRight.commit();
3769
        }
142 ilm 3770
        if (!codes.contains(GroupSQLComponent.ITEM_RIGHT_CODE)) {
93 ilm 3771
            SQLRowValues rowVals = new SQLRowValues(table);
142 ilm 3772
            rowVals.put("CODE", GroupSQLComponent.ITEM_RIGHT_CODE);
93 ilm 3773
            rowVals.put("NOM", "Autoriser à visualiser un champ");
3774
            String desc = "Autorise un utilisateur à visualiser le champ spécifié en objet dans une interface.";
3775
            rowVals.put("DESCRIPTION", desc);
3776
            SQLRow row = rowVals.commit();
3777
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3778
            rowValsUserRight.put("ID_RIGHT", row.getID());
3779
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3780
            rowValsUserRight.commit();
3781
        }
94 ilm 3782
        if (!codes.contains("CORPS_EDITER_PRIX_VENTE")) {
3783
            SQLRowValues rowVals = new SQLRowValues(table);
3784
            rowVals.put("CODE", "CORPS_EDITER_PRIX_VENTE");
3785
            rowVals.put("NOM", "Autoriser à éditer les prix de vente dans les pièces commerciales.");
3786
            String desc = "Autorise un utilisateur à éditer les prix de vente dans les pièces commerciales.";
3787
            rowVals.put("DESCRIPTION", desc);
3788
            SQLRow row = rowVals.commit();
3789
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3790
            rowValsUserRight.put("ID_RIGHT", row.getID());
3791
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3792
            rowValsUserRight.commit();
3793
        }
3794
        if (!codes.contains("CORPS_VOIR_PRIX_ACHAT")) {
3795
            SQLRowValues rowVals = new SQLRowValues(table);
3796
            rowVals.put("CODE", "CORPS_VOIR_PRIX_ACHAT");
3797
            rowVals.put("NOM", "Autoriser à voir les prix d'achat dans les pièces commerciales.");
3798
            String desc = "Autorise un utilisateur à voir les prix d'achat dans les pièces commerciales.";
3799
            rowVals.put("DESCRIPTION", desc);
3800
            SQLRow row = rowVals.commit();
3801
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3802
            rowValsUserRight.put("ID_RIGHT", row.getID());
3803
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3804
            rowValsUserRight.commit();
3805
        }
3806
        if (!codes.contains("CORPS_VERROU_PRIX_MIN_VENTE")) {
3807
            SQLRowValues rowVals = new SQLRowValues(table);
3808
            rowVals.put("CODE", "CORPS_VERROU_PRIX_MIN_VENTE");
3809
            rowVals.put("NOM", "Autoriser à mettre un prix de vente inférieur au prix minimum dans les pièces commerciales.");
3810
            String desc = "Autorise un utilisateur à mettre un prix de vente inférieur au prix minimum dans les pièces commerciales.";
3811
            rowVals.put("DESCRIPTION", desc);
3812
            SQLRow row = rowVals.commit();
3813
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3814
            rowValsUserRight.put("ID_RIGHT", row.getID());
3815
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3816
            rowValsUserRight.commit();
3817
        }
182 ilm 3818
 
94 ilm 3819
        // if (!codes.contains("MODIF_PRODUCT_KIT")) {
3820
        // SQLRowValues rowVals = new SQLRowValues(table);
3821
        // rowVals.put("CODE", "MODIF_PRODUCT_KIT");
3822
        // rowVals.put("NOM", "Autoriser à modifier les kits créer par autres utilisateurs.");
3823
        // String desc =
3824
        // "Autorise un utilisateur à modifier les kits créer par autres utilisateurs.";
3825
        // rowVals.put("DESCRIPTION", desc);
3826
        // SQLRow row = rowVals.commit();
3827
        // SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3828
        // rowValsUserRight.put("ID_RIGHT", row.getID());
3829
        // rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3830
        // rowValsUserRight.commit();
3831
        // }
3832
 
132 ilm 3833
        if (!codes.contains("SYNC_TEMPLATE")) {
3834
            SQLRowValues rowVals = new SQLRowValues(table);
3835
            rowVals.put("CODE", "SYNC_TEMPLATE");
3836
            rowVals.put("NOM", "Synchroniser les modèles vers le serveur");
3837
            String desc = "Autorise un utilisateur à synchroniser les modèles.";
3838
            rowVals.put("DESCRIPTION", desc);
3839
            SQLRow row = rowVals.commit();
3840
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3841
            rowValsUserRight.put("ID_RIGHT", row.getID());
3842
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3843
            rowValsUserRight.commit();
3844
        }
3845
 
174 ilm 3846
        if (!codes.contains(TableAllRights.USER_UI_LOCK_ROW)) {
3847
            SQLRowValues rowVals = new SQLRowValues(table);
3848
            rowVals.put("CODE", TableAllRights.USER_UI_LOCK_ROW);
3849
            rowVals.put("NOM", "Autoriser à verrouiller une ligne dans une liste.");
3850
            String desc = "Autorise un utilisateur à verrouiller une ou plusieurs dans les listes où cette fonctionnalité est active.";
3851
            rowVals.put("DESCRIPTION", desc);
3852
            SQLRow row = rowVals.commit();
3853
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3854
            rowValsUserRight.put("ID_RIGHT", row.getID());
3855
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3856
            rowValsUserRight.commit();
3857
        }
3858
 
3859
        if (!codes.contains(TableAllRights.USER_UI_UNLOCK_ROW)) {
3860
            SQLRowValues rowVals = new SQLRowValues(table);
3861
            rowVals.put("CODE", TableAllRights.USER_UI_UNLOCK_ROW);
3862
            rowVals.put("NOM", "Autoriser à déverrouiller une ligne dans une liste.");
3863
            String desc = "Autorise un utilisateur à déverrouiller une ou plusieurs dans les listes où cette fonctionnalité est active.";
3864
            rowVals.put("DESCRIPTION", desc);
3865
            SQLRow row = rowVals.commit();
3866
            SQLRowValues rowValsUserRight = new SQLRowValues(table.getTable("USER_RIGHT"));
3867
            rowValsUserRight.put("ID_RIGHT", row.getID());
3868
            rowValsUserRight.put("HAVE_RIGHT", Boolean.TRUE);
3869
            rowValsUserRight.commit();
3870
        }
3871
 
73 ilm 3872
    }
3873
 
57 ilm 3874
    private void findBadForeignKey(DBRoot root) {
3875
        Set<SQLTable> tables = root.getTables();
3876
        for (SQLTable table : tables) {
3877
            findBadForeignKey(root, table);
3878
        }
3879
 
3880
    }
3881
 
3882
    private void findBadForeignKey(DBRoot root, SQLTable table) {
3883
        System.out.println("====================================== " + table.getName());
3884
        Set<SQLField> ffields = table.getForeignKeys();
3885
 
3886
        Set<String> keysString = SQLKey.foreignKeys(table);
3887
        for (String string : keysString) {
3888
            ffields.add(table.getField(string));
3889
        }
3890
 
3891
        if (ffields.size() == 0) {
3892
            System.out.println("No foreign fields");
3893
        }
3894
        System.out.println("Foreign field for table " + table.getName() + ":" + ffields);
3895
        // Map Champs-> Table sur lequel il pointe
3896
        Map<SQLField, SQLTable> map = new HashMap<SQLField, SQLTable>();
3897
        Set<SQLTable> extTables = new HashSet<SQLTable>();
3898
        for (SQLField sqlField : ffields) {
3899
            SQLTable t = null;
3900
            try {
3901
                t = SQLKey.keyToTable(sqlField);
3902
            } catch (Exception e) {
3903
                System.out.println("Ignoring field:" + sqlField.getName());
3904
            }
3905
            if (t == null) {
3906
                System.out.println("Unable to find table for ff " + sqlField.getName());
3907
            } else {
3908
                extTables.add(t);
3909
                map.put(sqlField, t);
3910
            }
3911
        }
3912
        // Verification des datas
3913
        System.out.println("Foreign table for table " + table.getName() + ":" + extTables);
3914
        // Recupere les ids de toutes les tables
3915
        Map<SQLTable, Set<Number>> ids = getIdsForTables(extTables);
3916
 
3917
        //
67 ilm 3918
        SQLSelect s = new SQLSelect(true);
57 ilm 3919
        if (table.getPrimaryKeys().size() != 1) {
3920
            return;
3921
        }
3922
        s.addSelect(table.getKey());
3923
        for (SQLField sqlField : map.keySet()) {