OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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