OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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