OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | Details | Compare with Previous | Last modification | View Log | RSS feed

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