OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 151 | 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.core.finance.accounting.element;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18
import org.openconcerto.sql.Configuration;
19
import org.openconcerto.sql.element.BaseSQLComponent;
20
import org.openconcerto.sql.element.SQLComponent;
132 ilm 21
import org.openconcerto.sql.element.TreesOfSQLRows;
149 ilm 22
import org.openconcerto.sql.model.DBRoot;
67 ilm 23
import org.openconcerto.sql.model.DBSystemRoot;
24
import org.openconcerto.sql.model.SQLBackgroundTableCache;
25
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
18 ilm 26
import org.openconcerto.sql.model.SQLBase;
144 ilm 27
import org.openconcerto.sql.model.SQLField;
18 ilm 28
import org.openconcerto.sql.model.SQLRow;
142 ilm 29
import org.openconcerto.sql.model.SQLRowAccessor;
151 ilm 30
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 31
import org.openconcerto.sql.model.SQLRowValues;
32
import org.openconcerto.sql.model.SQLSelect;
33
import org.openconcerto.sql.model.SQLTable;
34
import org.openconcerto.sql.model.Where;
142 ilm 35
import org.openconcerto.sql.request.ComboSQLRequest;
67 ilm 36
import org.openconcerto.sql.request.UpdateBuilder;
18 ilm 37
import org.openconcerto.sql.sqlobject.JUniqueTextField;
142 ilm 38
import org.openconcerto.sql.view.list.IListe;
39
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
40
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
18 ilm 41
import org.openconcerto.ui.DefaultGridBagConstraints;
42
import org.openconcerto.ui.component.ITextArea;
43
import org.openconcerto.utils.ExceptionHandler;
21 ilm 44
import org.openconcerto.utils.checks.ValidState;
18 ilm 45
import org.openconcerto.utils.text.SimpleDocumentListener;
46
 
47
import java.awt.GridBagConstraints;
48
import java.awt.GridBagLayout;
142 ilm 49
import java.awt.event.ActionEvent;
18 ilm 50
import java.sql.SQLException;
51
import java.util.ArrayList;
144 ilm 52
import java.util.HashMap;
18 ilm 53
import java.util.List;
144 ilm 54
import java.util.Map;
65 ilm 55
import java.util.regex.Pattern;
18 ilm 56
 
142 ilm 57
import javax.swing.AbstractAction;
18 ilm 58
import javax.swing.JCheckBox;
59
import javax.swing.JLabel;
156 ilm 60
import javax.swing.JOptionPane;
18 ilm 61
import javax.swing.JTextField;
62
import javax.swing.event.DocumentEvent;
63
 
64
import org.apache.commons.dbutils.handlers.ArrayListHandler;
65
 
66
public class ComptePCESQLElement extends ComptaSQLConfElement {
67
 
144 ilm 68
    private static Map<String, String> mapCompteDefault = new HashMap<String, String>();
69
 
70
    static {
71
        // "Fournisseurs"
72
        // "Achats"
73
        // "Clients"
74
        // "VentesProduits"
75
        // "VentesServices"
76
        // "TVACollectee"
77
        // "TVADeductible"
78
        // "PayeAcompte"
79
        // "PayeReglementAcompte"
80
        // "PayeRemunerationPersonnel"
81
        // "PayeReglement"
82
        // "AchatCheque"
83
        // "AchatCB"
84
        // "AchatTraite"
85
        // "AchatEspece"
86
        // "VenteCheque"
87
        // "VenteCB"
88
        // "VenteTraite"
89
        // "VenteEspece"
90
        // "TVAIntraComm"
91
        // "TVAImmo"
92
        // "BilanOuverture"
93
        // "BilanFermeture"
94
        // "Resultat"
95
        // "AchatsIntra"
96
        // "ResultatPerte"
97
        // "Factor"
98
        // "PortVenteSoumisTVA"
99
        // "PortVenteNonSoumisTVA"
100
        // "AvanceClients"
101
        // "ValeurEncaissement"
102
 
103
        mapCompteDefault.put("FOURNISSEURS", "40");
104
        mapCompteDefault.put("ACHATS", "60");
105
        mapCompteDefault.put("CLIENTS", "41");
106
        mapCompteDefault.put("VENTESPRODUITS", "701");
107
        mapCompteDefault.put("VENTESSERVICES", "706");
108
        mapCompteDefault.put("TVACOLLECTEE", "4457");
109
        mapCompteDefault.put("TVADEDUCTIBLE", "4456");
110
        mapCompteDefault.put("PAYEACOMPTE", "425");
111
        mapCompteDefault.put("PAYEREGLEMENTACOMPTE", "511");
112
        mapCompteDefault.put("PAYEREMUNERATIONPERSONNEL", "641");
113
        mapCompteDefault.put("PAYEREGLEMENT", "421");
114
        mapCompteDefault.put("ACHATCHEQUE", "512");
115
        mapCompteDefault.put("ACHATCB", "512");
116
        mapCompteDefault.put("ACHATTRAITE", "512");
117
        mapCompteDefault.put("ACHATESPECE", "53");
118
        mapCompteDefault.put("VENTECHEQUE", "512");
119
        mapCompteDefault.put("VENTECB", "512");
120
        mapCompteDefault.put("VENTETRAITE", "512");
121
        mapCompteDefault.put("VENTEESPECE", "53");
122
        mapCompteDefault.put("TVAINTRACOMM", "4452");
123
        mapCompteDefault.put("TVAIMMO", "445620");
124
        mapCompteDefault.put("BILANOUVERTURE", "890");
125
        mapCompteDefault.put("BILANFERMETURE", "891");
126
        mapCompteDefault.put("RESULTAT", "120");
127
        mapCompteDefault.put("ACHATSINTRA", "607120");
128
        mapCompteDefault.put("RESULTATPERTE", "129");
129
        mapCompteDefault.put("FACTOR", "467000");
130
        mapCompteDefault.put("PORTVENTESOUMISTVA", "708510");
131
        mapCompteDefault.put("PORTVENTENONSOUMISTVA", "708520");
132
        mapCompteDefault.put("AVANCECLIENTS", "4191");
133
        mapCompteDefault.put("VALEURENCAISSEMENT", "511");
134
 
135
    }
136
 
18 ilm 137
    public ComptePCESQLElement() {
138
        super("COMPTE_PCE", "un compte", "comptes");
142 ilm 139
 
140
        PredicateRowAction action = new PredicateRowAction(new AbstractAction("Consulter le compte") {
141
 
142
            public void actionPerformed(ActionEvent e) {
143
                final SQLRowAccessor row = IListe.get(e).getSelectedRow();
144
                ((EcritureSQLElement) getDirectory().getElement("ECRITURE")).consultationCompte(row);
145
                // ConsultationCompteFrame f = new ConsultationCompteFrame(table.getValueAt(row,
146
                // 0).toString());
147
 
148
            }
149
        }, true);
150
        action.setPredicate(IListeEvent.getSingleSelectionPredicate());
151
        getRowActions().add(action);
18 ilm 152
    }
153
 
142 ilm 154
    @Override
155
    protected void _initComboRequest(ComboSQLRequest req) {
156
        super._initComboRequest(req);
157
        req.setWhere(new Where(getTable().getField("OBSOLETE"), "=", Boolean.FALSE));
149 ilm 158
        // Ne pas écraser l'ordre de la base (equals, startwith, etc..)
159
        req.setItemsOrder(null);
142 ilm 160
    }
161
 
18 ilm 162
    protected List<String> getListFields() {
163
        final List<String> list = new ArrayList<String>(3);
164
        list.add("NUMERO");
165
        list.add("NOM");
166
        list.add("INFOS");
142 ilm 167
        list.add("OBSOLETE");
18 ilm 168
        return list;
169
    }
170
 
171
    protected List<String> getComboFields() {
172
        final List<String> list = new ArrayList<String>(2);
173
        list.add("NUMERO");
174
        list.add("NOM");
175
        return list;
176
    }
177
 
178
    public SQLComponent createComponent() {
179
        return new BaseSQLComponent(this) {
180
 
65 ilm 181
            // private boolean isCompteValid = false;
182
            private ValidState compteNumeroValidState = ValidState.getTrueInstance();
18 ilm 183
            private JUniqueTextField textNumero = new JUniqueTextField(7);
184
 
21 ilm 185
            @Override
186
            public void update() {
67 ilm 187
                final int id = getSelectedID();
21 ilm 188
                super.update();
67 ilm 189
                final DBSystemRoot sysRoot = getTable().getDBSystemRoot();
190
                final SQLTable ecrT = sysRoot.getGraph().findReferentTable(getTable(), "ECRITURE");
191
                final UpdateBuilder updateBuilder = new UpdateBuilder(ecrT);
81 ilm 192
                updateBuilder.addForwardVirtualJoin(getTable(), "ID_COMPTE_PCE");
193
                updateBuilder.setFromVirtualJoinField("COMPTE_NUMERO", getTable().getAlias(), "NUMERO");
194
                updateBuilder.setFromVirtualJoinField("COMPTE_NOM", getTable().getAlias(), "NOM");
195
                updateBuilder.setWhere(new Where(ecrT.getField("ID_COMPTE_PCE"), "=", id));
67 ilm 196
                sysRoot.getDataSource().execute(updateBuilder.asString());
21 ilm 197
            }
198
 
18 ilm 199
            public void addViews() {
200
                this.setLayout(new GridBagLayout());
201
                final GridBagConstraints c = new DefaultGridBagConstraints();
202
 
203
                // Numero
204
                JLabel labelNumero = new JLabel("Numéro ");
205
 
206
                this.add(labelNumero, c);
207
 
208
                c.gridx++;
209
                c.weightx = 0;
210
                c.weightx = 0.5;
211
                this.add(this.textNumero, c);
212
                this.textNumero.getTextField().getDocument().addDocumentListener(new SimpleDocumentListener() {
213
 
214
                    @Override
215
                    public void update(DocumentEvent e) {
216
 
65 ilm 217
                        // On verifie que le numero est correct
218
                        compteNumeroValidState = getCompteNumeroValidState(textNumero.getText());
18 ilm 219
 
220
                        fireValidChange();
221
                    }
222
                });
223
 
224
                /*
225
                 * textNumero.addKeyListener(new KeyAdapter(){
226
                 *
227
                 * public void keyPressed(KeyEvent e) { } });
228
                 */
229
 
230
                // Libellé
231
                JLabel labelNom = new JLabel("Libellé ");
232
                c.gridx++;
233
                c.weightx = 0;
234
                this.add(labelNom, c);
235
 
236
                JTextField textNom = new JTextField(30);
237
                c.gridx++;
238
                c.weightx = 1;
239
                this.add(textNom, c);
240
 
241
                // c.gridy++;
242
                c.gridx++;
243
                c.weightx = 0;
244
                JCheckBox checkRacine = new JCheckBox("Racine");
245
                this.add(checkRacine, c);
246
 
142 ilm 247
                c.gridy++;
248
                c.gridx++;
249
                c.weightx = 0;
250
                JCheckBox checkObs = new JCheckBox("Obsolète");
251
                this.add(checkObs, c);
252
 
18 ilm 253
                // Infos
254
                JLabel labelInfos = new JLabel(getLabelFor("INFOS"));
255
                c.gridy++;
256
                c.gridx = 0;
257
                c.weightx = 0;
258
                this.add(labelInfos, c);
259
 
260
                ITextArea textInfos = new ITextArea();
261
                c.gridx++;
262
                c.weightx = 1;
263
                c.weighty = 1;
264
                c.gridwidth = GridBagConstraints.REMAINDER;
265
                c.gridheight = GridBagConstraints.REMAINDER;
266
                c.fill = GridBagConstraints.BOTH;
267
                this.add(textInfos, c);
268
 
269
                this.addRequiredSQLObject(this.textNumero, "NUMERO");
270
                this.addRequiredSQLObject(textNom, "NOM");
271
                this.addSQLObject(textInfos, "INFOS");
272
                this.addSQLObject(checkRacine, "RACINE");
142 ilm 273
                this.addSQLObject(checkObs, "OBSOLETE");
18 ilm 274
            }
275
 
276
            @Override
21 ilm 277
            public synchronized ValidState getValidState() {
65 ilm 278
                return super.getValidState().and(this.compteNumeroValidState);
18 ilm 279
            }
280
        };
281
    }
282
 
65 ilm 283
    public ValidState getCompteNumeroValidState(String text) {
284
 
285
        if (text.trim().length() > 0) {
286
            if ((text.trim().charAt(0) < '1') || (text.trim().charAt(0) > '8')) {
287
                // System.err.println("Numero de compte incorrect");
288
 
289
                return ValidState.create(false, "Le numéro de compte ne commence pas par un chiffre entre 1 et 8");
290
            } else if (text.endsWith(" ")) {
291
                return ValidState.create(false, "Le numéro de compte ne doit pas se terminer par un espace");
292
            } else {
293
                Pattern p = Pattern.compile("^\\d(\\w)+$");
294
                return ValidState.create(p.matcher(text).matches(), "Le numéro de compte n'est pas correct.");
295
            }
296
 
297
        }
298
        return ValidState.getTrueInstance();
299
 
300
    }
301
 
18 ilm 302
    @Override
132 ilm 303
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
304
        for (SQLRow row : trees.getRows()) {
305
            // on verifie qu'aucune ecriture n'est asssociée à ce compte
306
            SQLBase base = getTable().getBase();
307
            SQLTable ecritureTable = base.getTable("ECRITURE");
308
            SQLSelect selEcr = new SQLSelect();
309
            selEcr.addSelect(ecritureTable.getField("ID_COMPTE_PCE"));
310
            selEcr.setWhere(new Where(ecritureTable.getField("ID_COMPTE_PCE"), "=", row.getID()));
18 ilm 311
 
132 ilm 312
            String reqEcriture = selEcr.asString();
18 ilm 313
 
132 ilm 314
            Object obEcriture = base.getDataSource().execute(reqEcriture, new ArrayListHandler());
18 ilm 315
 
132 ilm 316
            List myListEcriture = (List) obEcriture;
317
            if (myListEcriture.size() != 0) {
156 ilm 318
                JOptionPane.showMessageDialog(null, "Impossible de supprimer un compte mouvementé!");
132 ilm 319
            } else {
320
                super.archive(new TreesOfSQLRows(this, row), cutLinks);
321
            }
18 ilm 322
        }
323
    }
324
 
325
    public static int getId(String numero) {
326
        return getId(numero, "Création automatique");
327
    }
328
 
67 ilm 329
    public static SQLRow getRow(String numero, String nom) {
149 ilm 330
        return getRow(numero, nom, ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete());
331
    }
73 ilm 332
 
149 ilm 333
    public static SQLRow getRow(String numero, String nom, DBRoot root) {
334
 
335
        SQLTable compteTable = root.getTable("COMPTE_PCE");
336
 
144 ilm 337
        final SQLBackgroundTableCacheItem cacheForTable = SQLBackgroundTableCache.getInstance().getCacheForTable(compteTable);
338
        if (numero == null) {
339
            throw new IllegalArgumentException("null numero");
340
        }
18 ilm 341
 
144 ilm 342
        final SQLField field = compteTable.getField("NUMERO");
343
        if (field == null) {
344
            throw new IllegalArgumentException("no field NUMERO in table " + compteTable.getName());
345
        }
151 ilm 346
        numero = numero.trim();
347
        SQLRow res = cacheForTable.getFirstRowContains(numero, field);
144 ilm 348
 
349
        if (res != null) {
350
            return res;
18 ilm 351
        } else {
151 ilm 352
            // Verification en BD
353
            SQLSelect sel = new SQLSelect();
354
            sel.addSelectStar(compteTable);
355
            sel.setWhere(new Where(compteTable.getField("NUMERO"), "=", numero));
356
            List<SQLRow> resultInDb = SQLRowListRSH.execute(sel);
357
            if (!resultInDb.isEmpty()) {
358
                return cacheForTable.getRows().get(0);
359
            } else {
18 ilm 360
 
151 ilm 361
                SQLRowValues rowVals = new SQLRowValues(compteTable);
362
                rowVals.put("NUMERO", numero);
363
                rowVals.put("NOM", nom);
364
                try {
365
                    return rowVals.insert();
366
                } catch (SQLException e) {
367
                    ExceptionHandler.handle("Erreur lors de la création du compte numéro : " + numero, e);
368
                    return null;
369
                }
67 ilm 370
            }
18 ilm 371
        }
372
    }
373
 
67 ilm 374
    /**
375
     * retourne l'id d'un compte en fonction de son numero, si le compte n'existe pas il sera créé
376
     * automatiquement
377
     *
378
     * @param numero du compte
379
     * @param nom nom du compte
380
     * @return id du compte
381
     */
382
    public static int getId(String numero, String nom) {
383
        return getRow(numero, nom).getID();
384
    }
18 ilm 385
 
67 ilm 386
    public static boolean isExist(String account) {
387
 
388
        if (account.trim().length() == 0) {
18 ilm 389
            return false;
390
        }
391
 
67 ilm 392
        final SQLTable tableAccount = Configuration.getInstance().getDirectory().getElement("COMPTE_PCE").getTable();
393
        final SQLBackgroundTableCacheItem item = SQLBackgroundTableCache.getInstance().getCacheForTable(tableAccount);
394
        return (item.getFirstRowContains(account, tableAccount.getField("NUMERO")) != null);
18 ilm 395
 
396
    }
397
 
398
    /**
399
     * @param name
400
     * @return Retourne le numero par défaut d'un compte
401
     * @throws IllegalArgumentException
402
     */
403
    public static String getComptePceDefault(final String name) throws IllegalArgumentException {
144 ilm 404
        // final SQLBase base = Configuration.getInstance().getBase();
405
        // final SQLTable tableDefault = base.getTable("COMPTE_PCE_DEFAULT");
406
        // final SQLSelect sel = new SQLSelect();
407
        // sel.addSelect(tableDefault.getField("NUMERO_DEFAULT"));
408
        //
409
        // sel.setWhere(Where.quote("UPPER(%n) = %s", tableDefault.getField("NOM"),
410
        // name.toUpperCase()));
411
        //
412
        // String numero = (String) base.getDataSource().executeScalar(sel.asString());
18 ilm 413
 
144 ilm 414
        String numero = mapCompteDefault.get(name.toUpperCase());
18 ilm 415
        if (numero == null) {
416
            throw new IllegalArgumentException("Impossible de trouver le compte PCE par défaut " + name);
417
        } else {
418
            return numero;
419
        }
420
    }
421
 
144 ilm 422
    public static void setComptePceDefault(final String name, final String numero) {
423
        mapCompteDefault.put(name, numero);
424
    }
425
 
426
    public static int getIdComptePceDefault(final String name) throws IllegalArgumentException {
18 ilm 427
        final String numeroDefault = getComptePceDefault(name);
428
        return getId(numeroDefault);
429
    }
57 ilm 430
 
144 ilm 431
    public static SQLRow getRowComptePceDefault(final String name) throws IllegalArgumentException {
67 ilm 432
        final String numeroDefault = getComptePceDefault(name);
433
        return getRow(numeroDefault, "création automatique");
434
    }
435
 
57 ilm 436
    @Override
437
    protected String createCode() {
156 ilm 438
        return createCodeOfPackage() + ".code.enterprise";
57 ilm 439
    }
149 ilm 440
 
18 ilm 441
}