OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 18 | Rev 73 | 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.model;
15
 
16
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
17
import org.openconcerto.erp.generationDoc.SpreadSheetGeneratorCompta;
18
import org.openconcerto.erp.generationDoc.gestcomm.ReleveChequeEmisSheet;
19
import org.openconcerto.erp.generationDoc.gestcomm.ReleveChequeSheet;
20
import org.openconcerto.erp.generationEcritures.GenerationMvtReglementAvoirChequeClient;
21
import org.openconcerto.erp.generationEcritures.GenerationMvtReglementChequeClient;
22
import org.openconcerto.erp.generationEcritures.GenerationMvtReglementChequeFourn;
23
import org.openconcerto.sql.Configuration;
24
import org.openconcerto.sql.element.SQLElement;
25
import org.openconcerto.sql.model.AliasedTable;
26
import org.openconcerto.sql.model.FieldRef;
27
import org.openconcerto.sql.model.IResultSetHandler;
28
import org.openconcerto.sql.model.SQLBase;
29
import org.openconcerto.sql.model.SQLData;
30
import org.openconcerto.sql.model.SQLDataSource;
31
import org.openconcerto.sql.model.SQLField;
32
import org.openconcerto.sql.model.SQLFieldsSet;
33
import org.openconcerto.sql.model.SQLRow;
34
import org.openconcerto.sql.model.SQLRowValues;
35
import org.openconcerto.sql.model.SQLSelect;
36
import org.openconcerto.sql.model.SQLTable;
37
import org.openconcerto.sql.model.SQLTableListener;
38
import org.openconcerto.sql.model.Where;
39
import org.openconcerto.utils.ExceptionHandler;
40
 
41
import java.sql.SQLException;
42
import java.util.ArrayList;
43
import java.util.Date;
44
import java.util.HashMap;
45
import java.util.List;
46
import java.util.Map;
47
import java.util.Set;
48
 
49
import javax.swing.SwingWorker;
50
import javax.swing.event.EventListenerList;
51
import javax.swing.table.AbstractTableModel;
52
 
53
public class GestionChequesModel extends AbstractTableModel {
54
 
55
    private List<Map<String, Object>> cheque = new ArrayList<Map<String, Object>>();
56
    private SQLTableListener tableListener;
57
    private EventListenerList loadingListener = new EventListenerList();
58
 
59
    // Table qui contient les cheques
60
    private SQLTable chqTable;
61
 
62
    // colonnes du modeles
63
    private List<FieldRef> fields;
64
 
65
    // field à cocher (decaissé ou encaissé)
66
    private SQLField fieldSelect;
67
 
68
    // field date minimum de depot ou d'encaissement
69
    private SQLField fieldDateMin;
70
 
71
    /**
72
     * Crée un model permettant de gérer l'encaissement ou le décaissement des cheques
73
     *
74
     * @param table SQLTable contenant les cheques
75
     * @param fields liste des colonnes à afficher
76
     * @param select SQLField boolean DECAISSE ou ENCAISSE
77
     * @param fieldDate date minimum de depot
78
     */
79
    public GestionChequesModel(SQLTable table, List<FieldRef> fields, SQLField select, SQLField fieldDate) {
80
        this.chqTable = table;
81
 
82
        this.fields = fields;
83
        this.fieldSelect = select;
84
        this.fieldDateMin = fieldDate;
85
 
86
        if (!fields.contains(select)) {
87
            throw new IllegalArgumentException("Le field select n'est dans aucune colonne.");
88
        }
89
 
90
        // loadCheque();
91
        this.tableListener = new SQLTableListener() {
92
            public void rowModified(SQLTable table, int id) {
93
 
94
                loadCheque();
95
                fireTableDataChanged();
96
            }
97
 
98
            public void rowAdded(SQLTable table, int id) {
99
                loadCheque();
100
                fireTableDataChanged();
101
            }
102
 
103
            public void rowDeleted(SQLTable table, int id) {
104
                loadCheque();
105
                fireTableDataChanged();
106
            }
107
        };
108
 
109
        this.chqTable.addTableListener(this.tableListener);
110
 
111
    }
112
 
113
    public Class<?> getColumnClass(int c) {
114
 
115
        final FieldRef field = this.fields.get(c);
116
 
117
        if (field.getField().getName().equalsIgnoreCase("ID_MOUVEMENT")) {
118
            return String.class;
119
        } else {
120
            return field.getField().getType().getJavaType();
121
        }
122
    }
123
 
124
    public int getRowCount() {
125
        return this.cheque.size();
126
    }
127
 
128
    public int getColumnCount() {
129
 
130
        return this.fields.size();
131
    }
132
 
133
    public String getColumnName(int col) {
134
        final FieldRef field = this.fields.get(col);
135
        if (field.getField().getName().equalsIgnoreCase("ID_MOUVEMENT")) {
136
            return "Source";
137
        } else {
138
            return Configuration.getInstance().getTranslator().getLabelFor(field.getField());
139
        }
140
    }
141
 
142
    public Object getValueAt(int rowIndex, int columnIndex) {
143
 
144
        final FieldRef field = this.fields.get(columnIndex);
145
        if (field.getField().getName().equalsIgnoreCase("ID_MOUVEMENT")) {
146
            // Integer i = (Integer) this.cheque.get(rowIndex).get(field.getField().getName());
147
            // if (i != null && i.intValue() > 1) {
148
            // int idScr = MouvementSQLElement.getSourceId(i);
149
            // SQLTable tableMvt =
150
            // Configuration.getInstance().getDirectory().getElement("MOUVEMENT").getTable();
151
            // if (idScr > 1) {
152
            // SQLRow rowMvt = tableMvt.getRow(idScr);
153
            // String source = rowMvt.getString("SOURCE");
154
            // int idSource = rowMvt.getInt("IDSOURCE");
155
            // SQLElement eltSource = Configuration.getInstance().getDirectory().getElement(source);
156
            // if (eltSource != null) {
157
            // final SQLTable table = eltSource.getTable();
158
            // SQLRow rowSource = table.getRow(idSource);
159
            // final Set<String> fields2 = table.getFieldsName();
160
            //
161
            // if (rowSource != null) {
162
            // if (fields2.contains("NUMERO")) {
163
            // return rowSource.getString("NUMERO");
164
            // } else {
165
            // if (fields2.contains("NOM")) {
166
            // return rowSource.getString("NOM");
167
            // }
168
            // }
169
            // }
170
            // }
171
            // }
172
            //
173
            // }
174
            // return "";
175
            return this.cheque.get(rowIndex).get("SOURCE_MOUVEMENT");
176
        } else {
177
            return this.cheque.get(rowIndex).get(field.getField().getName());
178
        }
179
    }
180
 
181
    public void fireIsLoading(boolean b) {
182
        for (LoadingTableListener l : this.loadingListener.getListeners(LoadingTableListener.class)) {
183
            l.isLoading(b);
184
        }
185
    }
186
 
187
    public void addLoadingListener(LoadingTableListener l) {
188
        this.loadingListener.add(LoadingTableListener.class, l);
189
    }
190
 
191
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
192
 
193
        this.cheque.get(rowIndex).put(this.fields.get(columnIndex).getField().getName(), aValue);
194
        fireTableDataChanged();
195
    }
196
 
197
    public boolean isCellEditable(int row, int col) {
198
        return this.fields.get(col).equals(this.fieldSelect);
199
    }
200
 
201
    SwingWorker<String, Object> worker;
202
 
203
    /**
204
     * Charge le model avec les cheques non decaisse, ou non encaisse
205
     *
206
     */
207
    public void loadCheque() {
208
        // FIXME cancel worker and restart load
209
        if (worker != null && !worker.isDone()) {
210
            return;
211
        }
212
        fireIsLoading(true);
213
        worker = new SwingWorker<String, Object>() {
214
 
215
            @Override
216
            protected String doInBackground() throws Exception {
217
 
218
                SQLBase base = GestionChequesModel.this.chqTable.getBase();
219
                // System.err.println("Load Cheque");
220
                final SQLSelect selCheque = new SQLSelect(base);
221
                selCheque.setWaitPreviousWriteTX(true);
222
                Where w = new Where(GestionChequesModel.this.fieldSelect, "=", Boolean.FALSE);
223
                w = w.and(new Where(GestionChequesModel.this.chqTable.getField("REG_COMPTA"), "=", Boolean.FALSE));
224
                for (int i = 0; i < GestionChequesModel.this.fields.size(); i++) {
225
                    FieldRef f = GestionChequesModel.this.fields.get(i);
226
 
227
                    selCheque.addSelect(f);
228
 
229
                    if (!f.getField().getTable().equals(GestionChequesModel.this.chqTable)) {
230
 
231
                        Set<SQLField> s = GestionChequesModel.this.chqTable.getForeignKeys(f.getField().getTable());
232
 
233
                        if (s != null && s.size() > 0) {
234
                            for (SQLField field : s) {
235
                                w = w.and(new Where(field, "=", f.getField().getTable().getKey()));
236
                            }
237
                        } else {
238
                            AliasedTable aliasedTable = new AliasedTable(f.getField().getTable(), "CLIENT_COMMUN");
239
                            final SQLTable clientTable = chqTable.getForeignTable("ID_CLIENT");
240
                            w = w.and(new Where(chqTable.getField("ID_CLIENT"), "=", clientTable.getKey()));
241
                            w = w.and(new Where(clientTable.getField("ID_CLIENT"), "=", aliasedTable.getField("ID")));
242
                        }
243
                    }
244
                }
245
                selCheque.addSelect(GestionChequesModel.this.chqTable.getKey());
246
                selCheque.addSelect(GestionChequesModel.this.chqTable.getField("ID_MOUVEMENT"));
247
 
248
                selCheque.setWhere(w);
249
 
250
                String reqCheque = selCheque.asString();
251
                // System.err.println("GestionChequesModel.loadCheque()" + reqCheque);
252
                GestionChequesModel.this.cheque = (List<Map<String, Object>>) base.getDataSource().execute(reqCheque, new IResultSetHandler(SQLDataSource.MAP_LIST_HANDLER) {
253
                    @Override
254
                    public Set<? extends SQLData> getCacheModifiers() {
255
                        return new SQLFieldsSet(selCheque.getSelectFields()).getTables();
256
                    }
257
                });
258
 
259
                for (Map<String, Object> m : GestionChequesModel.this.cheque) {
260
 
261
                    Number i = (Number) m.get("ID_MOUVEMENT");
262
                    m.put("SOURCE_MOUVEMENT", "");
263
                    if (i != null && i.intValue() > 1) {
264
                        int idScr = MouvementSQLElement.getSourceId(i.intValue());
265
                        SQLTable tableMvt = Configuration.getInstance().getDirectory().getElement("MOUVEMENT").getTable();
266
                        if (idScr > 1) {
267
                            SQLRow rowMvt = tableMvt.getRow(idScr);
268
                            String source = rowMvt.getString("SOURCE");
269
                            int idSource = rowMvt.getInt("IDSOURCE");
270
                            SQLElement eltSource = Configuration.getInstance().getDirectory().getElement(source);
271
                            if (eltSource != null) {
272
                                final SQLTable table = eltSource.getTable();
273
                                SQLRow rowSource = table.getRow(idSource);
274
                                final Set<String> fields2 = table.getFieldsName();
275
 
276
                                if (rowSource != null) {
277
                                    if (fields2.contains("NUMERO")) {
278
                                        m.put("SOURCE_MOUVEMENT", rowSource.getString("NUMERO"));
279
                                    } else {
280
                                        if (fields2.contains("NOM")) {
281
                                            m.put("SOURCE_MOUVEMENT", rowSource.getString("NOM"));
282
                                        }
283
                                    }
284
                                }
285
                            }
286
                        }
287
 
288
                    }
289
                }
290
 
291
                return null;
292
            }
293
 
294
            @Override
295
            protected void done() {
296
                fireTableDataChanged();
297
                fireIsLoading(false);
298
            }
299
        };
300
        worker.execute();
301
        // System.err.println(this.cheque);
302
    }
303
 
304
    /**
305
     *
306
     * @return le nombre de cheque sélectionné
307
     */
308
    public int getNbChequeSelected() {
309
        int nbCheq = 0;
310
        for (int i = 0; i < this.cheque.size(); i++) {
311
            Map<String, Object> chqTmp = this.cheque.get(i);
312
            Boolean b = (Boolean) chqTmp.get(this.fieldSelect.getName());
313
            if ((b != null) && (b.booleanValue())) {
314
                nbCheq++;
315
            }
316
        }
317
        return nbCheq;
318
    }
319
 
320
    /**
321
     *
322
     * @return le montant total des cheques selectionne en cents
323
     */
324
    public long getMontantTotalSelected() {
325
        long montant = 0;
326
        for (int i = 0; i < this.cheque.size(); i++) {
327
            Map<String, Object> chqTmp = this.cheque.get(i);
328
            Boolean b = (Boolean) chqTmp.get(this.fieldSelect.getName());
329
            if ((b != null) && (b.booleanValue())) {
330
                Long l = (Long) chqTmp.get("MONTANT");
331
 
332
                montant += ((l == null) ? 0 : l.longValue());
333
            }
334
        }
335
        return montant;
336
    }
337
 
338
    /**
339
     * Selectionne tous les cheques ayant depasse la date minimum de depot
340
     *
341
     */
342
    public void selectionDecaisseAll() {
343
        if (this.cheque == null) {
344
            return;
345
        }
346
        for (int i = 0; i < this.cheque.size(); i++) {
347
 
348
            Map<String, Object> chqTmp = this.cheque.get(i);
349
 
350
            Date d = (Date) chqTmp.get(this.fieldDateMin.getName());
351
            if (d != null && !d.after(new Date())) {
352
                chqTmp.put(this.fieldSelect.getName(), Boolean.TRUE);
353
            } else {
354
                chqTmp.put(this.fieldSelect.getName(), Boolean.FALSE);
355
            }
356
        }
357
        this.fireTableDataChanged();
358
    }
359
 
360
    public void deselectionAll() {
361
 
362
        for (int i = 0; i < this.cheque.size(); i++) {
363
 
364
            Map<String, Object> chqTmp = this.cheque.get(i);
365
            chqTmp.put(this.fieldSelect.getName(), Boolean.FALSE);
366
        }
367
        this.fireTableDataChanged();
368
    }
369
 
370
    public Date getDateMinimum(int rowIndex) {
371
        if (rowIndex >= 0 && rowIndex < this.getRowCount()) {
372
            return (Date) this.cheque.get(rowIndex).get(this.fieldDateMin.getName());
373
        } else {
374
            throw new IllegalArgumentException();
375
        }
376
    }
377
 
378
    public int getIdAtRow(int rowIndex) {
379
        if (rowIndex >= 0 && rowIndex < this.getRowCount()) {
380
            return ((Number) this.cheque.get(rowIndex).get(this.chqTable.getKey().getName())).intValue();
381
        } else {
382
            throw new IllegalArgumentException();
383
        }
384
    }
385
 
386
    public static final int MODE_ACHAT = 1;
387
    public static final int MODE_VENTE = 2;
388
    public static final int MODE_AVOIR = 3;
389
 
390
    public void valideDepot(Date d, int mode, boolean print) {
391
        valideDepot(d, mode, print, null);
392
    }
393
 
394
    /**
395
     * Valider le depot des cheques
396
     *
397
     * @param d Date de dépot
398
     * @param mode
399
     * @param print
400
     * @param s libellé pour l'ecriture en banque
401
     */
402
    public void valideDepot(Date d, int mode, boolean print, String s) {
403
 
404
        Map<String, Object> m = new HashMap<String, Object>();
405
 
406
        if (mode == MODE_VENTE) {
407
            m.put("ENCAISSE", Boolean.TRUE);
408
            m.put("DATE_DEPOT", d);
409
        } else {
410
            m.put("DECAISSE", Boolean.TRUE);
411
            m.put("DATE_DECAISSE", d);
412
        }
413
 
414
        // chqTable.removeTableListener(tableListener);
415
        List<Map<String, Object>> l = new ArrayList<Map<String, Object>>(this.cheque);
416
        List<Integer> listeCheque = new ArrayList<Integer>();
417
        for (int i = 0; i < l.size(); i++) {
418
 
419
            Map<String, Object> chqTmp = l.get(i);
420
 
421
            Boolean b = (Boolean) chqTmp.get(this.fieldSelect.getName());
422
 
423
            if ((b != null) && (b.booleanValue())) {
424
 
425
                SQLRowValues valChq = new SQLRowValues(this.chqTable, m);
426
                Number id = (Number) chqTmp.get(this.chqTable.getKey().getName());
427
                SQLRow rowCheque = this.chqTable.getRow(id.intValue());
428
 
429
                if (!rowCheque.getBoolean(this.fieldSelect.getName())) {
430
                    listeCheque.add(id.intValue());
431
                    try {
432
                        // if (valChq.getInvalid() == null) {
433
 
434
                        // ajout de l'ecriture
435
                        valChq.update(id.intValue());
436
 
437
                        Number idMvt = (Number) chqTmp.get("ID_MOUVEMENT");
438
 
439
                        if (mode == MODE_AVOIR) {
25 ilm 440
                            GenerationMvtReglementAvoirChequeClient gen = new GenerationMvtReglementAvoirChequeClient(idMvt.intValue(), Long.valueOf(chqTmp.get("MONTANT").toString()), d,
441
                                    id.intValue());
18 ilm 442
                            gen.genere();
443
                        } else {
444
                            if (mode == MODE_ACHAT) {
445
                                new GenerationMvtReglementChequeFourn(idMvt.intValue(), Long.valueOf(chqTmp.get("MONTANT").toString()).longValue(), id.intValue(), d);
446
                            } else {
447
                                if (mode == MODE_VENTE) {
448
                                    GenerationMvtReglementChequeClient gen = new GenerationMvtReglementChequeClient(idMvt.intValue(), Long.valueOf(chqTmp.get("MONTANT").toString()), d, id.intValue(),
449
                                            s);
450
                                    gen.genere();
451
                                } else {
452
                                    System.err.println("Aucune écriture générer pour le cheque " + id + " mode inconnu");
453
                                }
454
                            }
455
                        }
456
                    } catch (SQLException e) {
457
                        System.err.println("Erreur pendant la mise à jour dans la table " + valChq.getTable().getName());
458
                        ExceptionHandler.handle("Erreur lors de la génération des écritures du chéques + " + this.chqTable.getName() + " ID : " + id);
459
                        e.printStackTrace();
460
                    }
461
                }
462
            }
463
        }
464
 
465
        if (print) {
466
            if (mode == MODE_ACHAT) {
467
                ReleveChequeEmisSheet sheet = new ReleveChequeEmisSheet(listeCheque);
468
                new SpreadSheetGeneratorCompta(sheet, "ReleveChequeEmis", false, true);
469
            } else {
470
                if (mode == MODE_VENTE) {
471
                    ReleveChequeSheet sheet = new ReleveChequeSheet(listeCheque, d);
25 ilm 472
                    sheet.createDocumentAsynchronous();
473
                    sheet.showPrintAndExportAsynchronous(true, false, true);
18 ilm 474
                }
475
            }
476
        }
477
 
478
    }
479
 
480
    /**
481
     * Apercu du relevè
482
     *
483
     * @param mode
484
     */
485
    public void printPreview(int mode) {
486
 
487
        // chqTable.removeTableListener(tableListener);
488
        List<Map<String, Object>> l = new ArrayList<Map<String, Object>>(this.cheque);
489
        List<Integer> listeCheque = new ArrayList<Integer>();
490
        for (int i = 0; i < l.size(); i++) {
491
 
492
            Map<String, Object> chqTmp = l.get(i);
493
 
494
            Boolean b = (Boolean) chqTmp.get(this.fieldSelect.getName());
495
 
496
            if ((b != null) && (b.booleanValue())) {
497
 
498
                Number id = (Number) chqTmp.get(this.chqTable.getKey().getName());
499
                SQLRow rowCheque = this.chqTable.getRow(id.intValue());
500
 
501
                if (!rowCheque.getBoolean(this.fieldSelect.getName())) {
502
                    listeCheque.add(id.intValue());
503
                }
504
            }
505
        }
506
 
507
        if (mode == MODE_ACHAT) {
508
            ReleveChequeEmisSheet sheet = new ReleveChequeEmisSheet(listeCheque);
509
            new SpreadSheetGeneratorCompta(sheet, "ReleveChequeEmis", false, true);
510
        } else {
511
            if (mode == MODE_VENTE) {
512
                ReleveChequeSheet sheet = new ReleveChequeSheet(listeCheque, new Date(), true);
25 ilm 513
                sheet.createDocumentAsynchronous();
514
                sheet.showPrintAndExportAsynchronous(true, false, true);
18 ilm 515
            }
516
        }
517
 
518
    }
519
}