OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
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.action;
15
 
16
import static org.openconcerto.task.config.ComptaBasePropsConfiguration.getStreamStatic;
144 ilm 17
 
18 ilm 18
import org.openconcerto.erp.config.ComptaPropsConfiguration;
67 ilm 19
import org.openconcerto.erp.config.DefaultMenuConfiguration;
20 ilm 20
import org.openconcerto.erp.config.Gestion;
73 ilm 21
import org.openconcerto.erp.config.Log;
18 ilm 22
import org.openconcerto.erp.config.MainFrame;
80 ilm 23
import org.openconcerto.erp.config.MenuManager;
24
import org.openconcerto.erp.config.MinimalMenuConfiguration;
18 ilm 25
import org.openconcerto.erp.core.common.ui.PanelFrame;
26
import org.openconcerto.erp.core.common.ui.StatusPanel;
27
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
28
import org.openconcerto.erp.core.humanresources.payroll.element.CaisseCotisationSQLElement;
29
import org.openconcerto.erp.element.objet.ClasseCompte;
67 ilm 30
import org.openconcerto.erp.modules.ModuleFrame;
25 ilm 31
import org.openconcerto.erp.modules.ModuleManager;
18 ilm 32
import org.openconcerto.erp.panel.ComptaTipsFrame;
94 ilm 33
import org.openconcerto.erp.preferences.GestionClientPreferencePanel;
93 ilm 34
import org.openconcerto.erp.rights.GroupUIComboRightEditor;
35
import org.openconcerto.erp.rights.MenuComboRightEditor;
18 ilm 36
import org.openconcerto.erp.utils.NXDatabaseAccessor;
37
import org.openconcerto.map.model.Ville;
180 ilm 38
import org.openconcerto.sql.Configuration;
39
import org.openconcerto.sql.PropsConfiguration;
40
import org.openconcerto.sql.TM;
18 ilm 41
import org.openconcerto.sql.element.SQLElement;
42
import org.openconcerto.sql.model.SQLBackgroundTableCache;
43
import org.openconcerto.sql.model.SQLBase;
44
import org.openconcerto.sql.model.SQLRow;
45
import org.openconcerto.sql.model.SQLRowListRSH;
46
import org.openconcerto.sql.model.SQLSelect;
47
import org.openconcerto.sql.model.SQLTable;
48
import org.openconcerto.sql.model.UndefinedRowValuesCache;
49
import org.openconcerto.sql.model.Where;
26 ilm 50
import org.openconcerto.sql.preferences.SQLPreferences;
18 ilm 51
import org.openconcerto.sql.preferences.UserProps;
20 ilm 52
import org.openconcerto.sql.sqlobject.IComboSelectionItem;
18 ilm 53
import org.openconcerto.sql.ui.ConnexionPanel;
54
import org.openconcerto.sql.users.User;
55
import org.openconcerto.sql.users.UserManager;
93 ilm 56
import org.openconcerto.sql.users.rights.SQLTableRightEditor;
18 ilm 57
import org.openconcerto.sql.users.rights.TableAllRights;
144 ilm 58
import org.openconcerto.sql.users.rights.UserRights;
18 ilm 59
import org.openconcerto.sql.users.rights.UserRightsManager;
60
import org.openconcerto.sql.users.rights.UserRightsManager.RightTuple;
83 ilm 61
import org.openconcerto.sql.utils.BackupPanel;
18 ilm 62
import org.openconcerto.task.config.ComptaBasePropsConfiguration;
63
import org.openconcerto.ui.DefaultGridBagConstraints;
64
import org.openconcerto.ui.FrameUtil;
83 ilm 65
import org.openconcerto.ui.component.MutableListComboPopupListener;
156 ilm 66
import org.openconcerto.ui.preferences.EmailProps;
18 ilm 67
import org.openconcerto.utils.ExceptionHandler;
68
import org.openconcerto.utils.JImage;
65 ilm 69
import org.openconcerto.utils.cc.IClosure;
180 ilm 70
import org.openconcerto.utils.i18n.TranslationManager;
18 ilm 71
 
72
import java.awt.Color;
73
import java.awt.GridBagConstraints;
74
import java.awt.GridBagLayout;
61 ilm 75
import java.awt.Image;
18 ilm 76
import java.awt.Insets;
156 ilm 77
import java.io.File;
18 ilm 78
import java.io.InputStream;
79
import java.util.ArrayList;
67 ilm 80
import java.util.Arrays;
18 ilm 81
import java.util.List;
67 ilm 82
import java.util.Locale;
18 ilm 83
import java.util.concurrent.CountDownLatch;
65 ilm 84
import java.util.concurrent.FutureTask;
73 ilm 85
import java.util.logging.Level;
18 ilm 86
 
87
import javax.swing.Action;
180 ilm 88
import javax.swing.JComponent;
18 ilm 89
import javax.swing.JFrame;
90
import javax.swing.JOptionPane;
91
import javax.swing.JPanel;
92
import javax.swing.JTextArea;
93
import javax.swing.SwingUtilities;
94
import javax.swing.SwingWorker;
95
import javax.swing.UIManager;
96
 
97
public class NouvelleConnexionAction extends CreateFrameAbstractAction {
156 ilm 98
    private final ComptaPropsConfiguration conf;
67 ilm 99
    private ConnexionPanel connexionPanel;
100
 
156 ilm 101
    public NouvelleConnexionAction(ComptaPropsConfiguration conf) {
18 ilm 102
        super();
156 ilm 103
        this.conf = conf;
18 ilm 104
        this.putValue(Action.NAME, "Changer d'utilisateur");
105
    }
106
 
107
    public JFrame createFrame() {
108
        // needed as done() must come after us
109
        assert SwingUtilities.isEventDispatchThread();
94 ilm 110
 
156 ilm 111
        final ComptaPropsConfiguration comptaPropsConfiguration = this.conf;
18 ilm 112
 
113
        Runnable r = new Runnable() {
114
 
115
            public void run() {
116
                try {
19 ilm 117
                    final Boolean booleanValue = UserProps.getInstance().getBooleanValue("HideTips");
118
                    if (!booleanValue) {
119
                        SwingUtilities.invokeLater(new Runnable() {
120
                            @Override
121
                            public void run() {
122
                                ComptaTipsFrame.getFrame(true).setVisible(true);
123
                            }
124
                        });
18 ilm 125
                    }
20 ilm 126
                    int selectedSociete;
127
                    if (NouvelleConnexionAction.this.connexionPanel != null && !Gestion.isMinimalMode()) {
128
                        selectedSociete = NouvelleConnexionAction.this.connexionPanel.getSelectedSociete();
129
                    } else {
130
                        selectedSociete = UserProps.getInstance().getLastSocieteID();
131
                        if (selectedSociete < SQLRow.MIN_VALID_ID) {
132
                            final SQLElement elem = comptaPropsConfiguration.getDirectory().getElement(comptaPropsConfiguration.getRoot().getTable("SOCIETE_COMMON"));
133
                            final List<IComboSelectionItem> comboItems = elem.getComboRequest().getComboItems();
134
                            if (comboItems.size() > 0)
135
                                selectedSociete = comboItems.get(0).getId();
136
                            else
137
                                throw new IllegalStateException("No " + elem + " found");
138
                        }
139
                    }
19 ilm 140
                    comptaPropsConfiguration.setUpSocieteDataBaseConnexion(selectedSociete);
144 ilm 141
                    comptaPropsConfiguration.setupBarCodeIfNeeded();
156 ilm 142
                    File fMail2 = new File(comptaPropsConfiguration.getConfDir(), "Email" + selectedSociete + ".properties");
143
                    EmailProps.getInstance().setPropsFileName(fMail2.toString());
80 ilm 144
                    // needed by openEmergencyModuleManager()
145
                    UserRightsManager.getInstance().addRightForAdmins(new RightTuple(ModuleManager.MODULE_DB_RIGHT, true));
83 ilm 146
                    UserRightsManager.getInstance().addRightForAdmins(new RightTuple(BackupPanel.RIGHT_CODE, true));
67 ilm 147
                    // finish filling the configuration before going any further, otherwise the
148
                    // SQLElementDirectory is not coherent
156 ilm 149
                    final ModuleManager moduleMngr = comptaPropsConfiguration.getModuleManager();
67 ilm 150
                    try {
156 ilm 151
                        moduleMngr.init();
67 ilm 152
                    } catch (Throwable e) {
153
                        // not OK to continue without required elements
156 ilm 154
                        openEmergencyModuleManager(moduleMngr, "Impossible de configurer les modules requis", e);
73 ilm 155
                        return;
67 ilm 156
                    }
156 ilm 157
 
180 ilm 158
                                      MenuManager.setInstance(
144 ilm 159
                            (Gestion.isMinimalMode() ? new MinimalMenuConfiguration(comptaPropsConfiguration) : new DefaultMenuConfiguration(comptaPropsConfiguration)).createMenuAndActions());
25 ilm 160
 
83 ilm 161
                    final User user = UserManager.getInstance().getCurrentUser();
144 ilm 162
                    final UserRights rights = UserRightsManager.getCurrentUserRights();
80 ilm 163
                    // Si l'utilisateur n'est pas superUser ou si il n'a pas de droit d'accéder
164
                    // à toutes les société
165
                    final int userId = user.getId();
144 ilm 166
                    if (!rights.haveRight("ACCES_ALL_SOCIETE")) {
26 ilm 167
 
80 ilm 168
                        final SQLTable tableAcces = comptaPropsConfiguration.getRoot().findTable("ACCES_SOCIETE");
169
                        SQLSelect sel = new SQLSelect();
170
                        sel.addSelectStar(tableAcces);
171
                        sel.setWhere(new Where(tableAcces.getField("ID_USER_COMMON"), "=", userId));
172
 
173
                        final List<SQLRow> accessRows = SQLRowListRSH.execute(sel);
174
                        final boolean accessGranted;
93 ilm 175
                        if (accessRows.size() == 0) {
176
                            accessGranted = true;
80 ilm 177
                        } else {
93 ilm 178
                            boolean tmp = false;
179
                            for (final SQLRow r : accessRows) {
180
                                if (r.getInt("ID_SOCIETE_COMMON") == selectedSociete) {
181
                                    tmp = true;
182
                                    break;
80 ilm 183
                                }
184
                            }
93 ilm 185
                            accessGranted = tmp;
80 ilm 186
                        }
187
 
188
                        if (!accessGranted) {
189
                            JOptionPane.showMessageDialog(null, "Vous n'avez pas les droits suffisants, pour accéder à cette société!");
190
                            return;
191
                        }
192
                    }
193
 
19 ilm 194
                    SwingUtilities.invokeLater(new Runnable() {
195
                        @Override
196
                        public void run() {
93 ilm 197
                            MenuComboRightEditor.register();
198
                            GroupUIComboRightEditor.register();
199
                            SQLTableRightEditor.register();
19 ilm 200
                            // even for quick login, check the license before displaying the main
201
                            // frame
18 ilm 202
 
144 ilm 203
                            MutableListComboPopupListener.setLockOverridable(rights.isSuperUser());
83 ilm 204
 
19 ilm 205
                            StatusPanel.getInstance().fireStatusChanged();
156 ilm 206
                            final MainFrame f = new MainFrame(comptaPropsConfiguration);
19 ilm 207
                            String version = comptaPropsConfiguration.getVersion();
20 ilm 208
                            final String socTitle = comptaPropsConfiguration.getRowSociete() == null ? "" : ", [Société " + comptaPropsConfiguration.getRowSociete().getString("NOM") + "]";
209
                            f.setTitle(comptaPropsConfiguration.getAppName() + " " + version + socTitle);
19 ilm 210
                            f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
180 ilm 211
 
65 ilm 212
                        }
213
                    });
214
                    final FutureTask<?> showMainFrame = new FutureTask<Object>(new Runnable() {
215
                        @Override
216
                        public void run() {
80 ilm 217
                            // make sure the application is started with all required and mandatory
218
                            // modules
156 ilm 219
                            if (moduleMngr.isInited()) {
67 ilm 220
                                final MainFrame mainFrame = MainFrame.getInstance();
73 ilm 221
                                mainFrame.initMenuBar();
67 ilm 222
                                FrameUtil.show(mainFrame);
223
                            }
65 ilm 224
                        }
225
                    }, null);
156 ilm 226
                    moduleMngr.invoke(new IClosure<ModuleManager>() {
65 ilm 227
                        @Override
228
                        public void executeChecked(ModuleManager input) {
25 ilm 229
                            // start modules before displaying the frame (e.g. avoid modifying a
230
                            // visible menu bar)
231
                            try {
65 ilm 232
                                input.startRequiredModules();
80 ilm 233
                                try {
234
                                    input.startPreviouslyRunningModules();
235
                                } catch (Exception exn) {
236
                                    // OK to start the application without all modules started
237
                                    // but don't continue right away otherwise connexion panel will
238
                                    // be closed and the popup with it
239
                                    try {
156 ilm 240
                                        ExceptionHandler.handle(NouvelleConnexionAction.this.connexionPanel, "Impossible de démarrer les modules", exn).get();
80 ilm 241
                                    } catch (Exception e) {
242
                                        e.printStackTrace();
243
                                    }
244
                                }
67 ilm 245
                                SwingUtilities.invokeLater(showMainFrame);
25 ilm 246
                            } catch (Exception exn) {
156 ilm 247
                                openEmergencyModuleManager(input, "Impossible de démarrer les modules requis", exn);
25 ilm 248
                            }
18 ilm 249
                        }
19 ilm 250
                    });
80 ilm 251
                    initCache(comptaPropsConfiguration);
65 ilm 252
                    // don't close ConnexionPanel until the main frame is shown
253
                    showMainFrame.get();
19 ilm 254
                } catch (Throwable e) {
142 ilm 255
                    if (e.getMessage() != null && ((e.getMessage().contains("table") && e.getMessage().contains("not found")) || e.getMessage().contains("unknown field")
156 ilm 256
                            || e.getMessage().contains("Couldn't add showAs") || e.getMessage().contains("Base de données non à jour"))) {
257
                        e.printStackTrace();
142 ilm 258
                        JOptionPane.showMessageDialog(new JFrame(),
259
                                "Votre base de données n'est pas à jour.\nUtilisez l'outil de configuration et pensez à l'achat du manuel !\n(" + e.getMessage() + ")");
83 ilm 260
                        return;
261
                    }
19 ilm 262
                    ExceptionHandler.handle("Erreur de connexion", e);
263
                }
18 ilm 264
            }
265
 
266
        };
267
 
268
        final JImage image = new JImage(ComptaBasePropsConfiguration.class.getResource("logo.png"));
61 ilm 269
        Image customImage = ComptaPropsConfiguration.getInstanceCompta().getCustomLogo();
270
        if (customImage != null) {
271
            image.setImage(customImage);
272
        }
18 ilm 273
        image.setBackground(Color.WHITE);
274
        JPanel p = new JPanel();
275
 
276
        p.setLayout(new GridBagLayout());
277
        GridBagConstraints c = new DefaultGridBagConstraints();
278
        c.weightx = 1;
279
        c.weighty = 1;
280
        c.insets = new Insets(0, 0, 0, 0);
281
        c.fill = GridBagConstraints.BOTH;
282
 
20 ilm 283
        this.connexionPanel = ConnexionPanel.create(r, image, !Gestion.isMinimalMode());
180 ilm 284
        final List<Locale> langs = Arrays.asList(Locale.FRANCE, Locale.CANADA_FRENCH, new Locale("fr", "CH"), new Locale("fr", "BE"), Locale.UK, Locale.CANADA, Locale.US, Locale.GERMANY,
285
                new Locale("de", "CH"), new Locale("es", "ES"), new Locale("pl", "PL"));
286
        if (this.connexionPanel == null) {
287
            final Locale locale = UserProps.getInstance().getLocale();
288
            // for next launch
289
            UserProps.getInstance().setLocale(locale);
290
            // for current run
291
            ((PropsConfiguration) Configuration.getInstance()).setLocale(locale);
292
            // for code that will never need more than one Locale concurrently
293
            // (e.g. used by TM singletons in various packages)
294
            Locale.setDefault(locale);
295
            // as explained in Locale.setDefault() javadoc : "be prepared to reinitialize
296
            // locale-sensitive code"
297
            JComponent.setDefaultLocale(locale);
298
            // throw RuntimeException like ResourceBundle.getBundle() at the beginning of this
299
            // method
300
            TranslationManager.createDefaultInstance();
301
            TM.getInstance();
18 ilm 302
            return null;
180 ilm 303
        }
18 ilm 304
 
180 ilm 305
        this.connexionPanel.initLocalization(getClass().getName(), langs);
306
 
18 ilm 307
        p.add(this.connexionPanel, c);
308
        final PanelFrame panelFrame = new PanelFrame(p, "Connexion");
309
        panelFrame.setLocationRelativeTo(null);
310
        panelFrame.pack();
311
        panelFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
312
        return panelFrame;
313
    }
314
 
144 ilm 315
    static public void initCache(final ComptaPropsConfiguration comptaConf) {
174 ilm 316
        initCache(comptaConf, 600);
317
    }
318
 
319
    static public void initCache(final ComptaPropsConfiguration comptaConf, final int timeout) {
320
 
80 ilm 321
        final SQLBase baseSociete = comptaConf.getSQLBaseSociete();
18 ilm 322
        Thread t = new Thread() {
323
            @Override
324
            public void run() {
325
                // laisse le temps au logiciel de demarrer
180 ilm 326
                ClasseCompte.loadClasseCompte(comptaConf);
18 ilm 327
                try {
177 ilm 328
                    Thread.sleep(1000);
18 ilm 329
                } catch (InterruptedException e) {
330
                    e.printStackTrace();
331
                }
332
                CaisseCotisationSQLElement.getCaisseCotisation();
333
 
94 ilm 334
                SQLPreferences prefs = SQLPreferences.getMemCached(comptaConf.getRootSociete());
335
 
336
                Ville.init(new NXDatabaseAccessor(comptaConf), prefs.getBoolean(GestionClientPreferencePanel.LOAD_CITIES, true));
337
 
174 ilm 338
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("TAXE"), timeout);
339
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("ETAT_DEVIS"), timeout);
340
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("PREFS_COMPTE"), timeout);
341
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("COMPTE_PCE"), timeout);
342
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("JOURNAL"), timeout);
18 ilm 343
 
174 ilm 344
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("COMMERCIAL"), timeout);
345
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("PERIODE_VALIDITE"), timeout);
18 ilm 346
 
156 ilm 347
                if (comptaConf.getRootSociete().contains("DEPOT_STOCK")) {
174 ilm 348
                    SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("DEPOT_STOCK"), timeout);
156 ilm 349
                }
174 ilm 350
                SQLBackgroundTableCache.getInstance().add(baseSociete.getTable("TYPE_REGLEMENT"), timeout);
67 ilm 351
                SQLBackgroundTableCache.getInstance().startCacheWatcher();
352
 
18 ilm 353
                TaxeCache.getCache();
354
 
67 ilm 355
                final UndefinedRowValuesCache undefCache = UndefinedRowValuesCache.getInstance();
356
                final List<SQLTable> tablesToCache = new ArrayList<SQLTable>();
357
                tablesToCache.add(baseSociete.getTable("DEVIS"));
358
                tablesToCache.add(baseSociete.getTable("ETAT_DEVIS"));
359
                tablesToCache.add(baseSociete.getTable("FAMILLE_ARTICLE"));
360
                tablesToCache.add(baseSociete.getTable("ADRESSE"));
361
                tablesToCache.add(baseSociete.getTable("DEVIS_ELEMENT"));
362
                tablesToCache.add(baseSociete.getTable("CONTACT"));
363
                tablesToCache.add(baseSociete.getTable("SAISIE_VENTE_FACTURE_ELEMENT"));
364
                tablesToCache.add(baseSociete.getTable("SAISIE_KM_ELEMENT"));
365
                tablesToCache.add(baseSociete.getTable("BON_DE_LIVRAISON_ELEMENT"));
366
                tablesToCache.add(baseSociete.getTable("COMMANDE_CLIENT_ELEMENT"));
367
                tablesToCache.add(baseSociete.getTable("AVOIR_CLIENT_ELEMENT"));
368
                tablesToCache.add(baseSociete.getTable("BON_RECEPTION_ELEMENT"));
93 ilm 369
                tablesToCache.add(baseSociete.getTable("ASSOCIATION_ANALYTIQUE"));
67 ilm 370
                undefCache.preload(tablesToCache);
18 ilm 371
            }
372
 
373
        };
374
        t.setName("Cache preload");
375
        t.setDaemon(true);
376
        t.setPriority(Thread.MIN_PRIORITY);
377
        t.start();
378
    }
379
 
380
    private String checkLicense(final SwingWorker<String, Object> w) {
381
        try {
382
            return w.get();
383
        } catch (Exception e) {
384
            throw ExceptionHandler.die("Impossible de charger la licence.", e);
385
        }
386
    }
387
 
156 ilm 388
    private void openEmergencyModuleManager(ModuleManager mngr, final String str, final Throwable e) {
73 ilm 389
        Log.get().log(Level.SEVERE, "Normal startup impossible, opening the module manager in order to resolve the issue.", e);
67 ilm 390
        SwingUtilities.invokeLater(new Runnable() {
391
            @Override
392
            public void run() {
73 ilm 393
                ExceptionHandler.handle(str, e);
80 ilm 394
                // can't start since there's no main frame (and obviously no modules can be stopped
395
                // since none are running)
156 ilm 396
                final ModuleFrame fMod = new ModuleFrame(mngr, true);
73 ilm 397
                fMod.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
398
                fMod.setTitle(str);
80 ilm 399
                FrameUtil.show(fMod);
67 ilm 400
            }
401
        });
402
    }
18 ilm 403
}