OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

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