OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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