OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 18 | Rev 28 | 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.sales.invoice.ui;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.config.Gestion;
18
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
19 ilm 19
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
18 ilm 20
import org.openconcerto.erp.core.customerrelationship.customer.element.RelanceSQLElement;
21
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
22
import org.openconcerto.erp.core.finance.payment.component.EncaisserMontantSQLComponent;
19 ilm 23
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
18 ilm 24
import org.openconcerto.erp.rights.ComptaUserRight;
25
import org.openconcerto.erp.rights.NXRights;
26
import org.openconcerto.sql.Configuration;
27
import org.openconcerto.sql.element.SQLElement;
28
import org.openconcerto.sql.model.SQLBase;
19 ilm 29
import org.openconcerto.sql.model.SQLField;
18 ilm 30
import org.openconcerto.sql.model.SQLRow;
31
import org.openconcerto.sql.model.SQLRowValues;
32
import org.openconcerto.sql.model.SQLTable;
33
import org.openconcerto.sql.users.UserManager;
34
import org.openconcerto.sql.users.rights.UserRightsManager;
35
import org.openconcerto.sql.view.EditFrame;
36
import org.openconcerto.sql.view.EditPanelListener;
37
import org.openconcerto.sql.view.IListPanel;
38
import org.openconcerto.sql.view.IListener;
39
import org.openconcerto.ui.DefaultGridBagConstraints;
19 ilm 40
import org.openconcerto.ui.EmailComposer;
18 ilm 41
import org.openconcerto.utils.GestionDevise;
42
 
43
import java.awt.GridBagConstraints;
44
import java.awt.GridBagLayout;
45
import java.awt.event.ActionEvent;
46
import java.awt.event.ActionListener;
47
import java.awt.event.MouseAdapter;
48
import java.awt.event.MouseEvent;
19 ilm 49
import java.io.IOException;
18 ilm 50
import java.sql.SQLException;
19 ilm 51
import java.text.SimpleDateFormat;
18 ilm 52
import java.util.ArrayList;
19 ilm 53
import java.util.Arrays;
18 ilm 54
import java.util.Date;
55
import java.util.List;
19 ilm 56
import java.util.Locale;
57
import java.util.Set;
18 ilm 58
 
59
import javax.swing.AbstractAction;
60
import javax.swing.JButton;
61
import javax.swing.JCheckBox;
62
import javax.swing.JFrame;
63
import javax.swing.JOptionPane;
64
import javax.swing.JPanel;
65
import javax.swing.JPopupMenu;
66
import javax.swing.SwingConstants;
67
import javax.swing.SwingUtilities;
68
 
69
public class ListeDesEcheancesClientsPanel extends JPanel {
70
 
71
    private ListPanelEcheancesClients panelEcheances;
72
    private EditFrame editEncaisse = null;
73
    private EditFrame editRelance = null;
74
    private JButton relancer, encaisser;
75
 
76
    // TODO GEstion Relance (??? loi NRE pour le calcul des penalites)
77
    public ListeDesEcheancesClientsPanel() {
78
        this.setLayout(new GridBagLayout());
79
        final GridBagConstraints c = new DefaultGridBagConstraints();
80
 
81
        this.panelEcheances = new ListPanelEcheancesClients();
82
 
83
        // PANEL AVEC LA LISTE DES ECHEANCES
84
        c.weightx = 1;
85
        c.weighty = 1;
86
        c.gridwidth = GridBagConstraints.REMAINDER;
87
        c.fill = GridBagConstraints.BOTH;
88
        this.add(this.panelEcheances, c);
89
 
19 ilm 90
        IListTotalPanel totalPanel = new IListTotalPanel(this.panelEcheances.getListe(), Arrays.asList(this.panelEcheances.getElement().getTable().getField("MONTANT")));
91
 
92
        c.weighty = 0;
93
        c.gridy++;
94
        c.anchor = GridBagConstraints.EAST;
95
        c.weightx = 0;
96
        c.fill = GridBagConstraints.NONE;
97
        this.add(totalPanel, c);
98
 
99
        c.anchor = GridBagConstraints.WEST;
18 ilm 100
        c.gridx = 0;
101
        c.gridy++;
102
        c.gridwidth = 1;
103
 
104
        c.weighty = 0;
105
        c.fill = GridBagConstraints.NONE;
106
        c.weightx = 0;
107
        final JCheckBox checkRegCompta = new JCheckBox("Voir les régularisations de comptabilité");
108
        if (UserRightsManager.getCurrentUserRights().haveRight(ComptaUserRight.MENU)) {
109
            this.add(checkRegCompta, c);
110
        }
111
 
112
        checkRegCompta.addActionListener(new ActionListener() {
113
            @Override
114
            public void actionPerformed(ActionEvent e) {
115
                panelEcheances.setShowRegCompta(checkRegCompta.isSelected());
116
 
117
            }
118
        });
119
 
120
        c.weightx = 1;
121
        c.anchor = GridBagConstraints.EAST;
122
        // Bouton Relancer
123
        this.relancer = new JButton("Relancer");
124
        this.relancer.setHorizontalAlignment(SwingConstants.RIGHT);
125
        if (UserManager.getInstance().getCurrentUser().getRights().haveRight(NXRights.GESTION_ENCAISSEMENT.getCode())) {
126
            c.gridx++;
127
            this.add(this.relancer, c);
128
            this.relancer.addActionListener(new ActionListener() {
129
                public void actionPerformed(ActionEvent e) {
130
                    relanceClient();
131
                }
132
            });
133
        }
134
 
135
        // Bouton Encaisser
136
        this.encaisser = new JButton("Encaisser");
137
        this.encaisser.setHorizontalAlignment(SwingConstants.RIGHT);
138
        c.gridx++;
139
        c.weightx = 0;
140
        if (UserManager.getInstance().getCurrentUser().getRights().haveRight(NXRights.GESTION_ENCAISSEMENT.getCode())) {
141
 
142
            this.add(this.encaisser, c);
143
        }
144
        this.encaisser.addActionListener(new ActionListener() {
145
 
146
            public void actionPerformed(ActionEvent e) {
147
 
148
                List<Integer> selectedIds = ListeDesEcheancesClientsPanel.this.panelEcheances.getListe().getSelection().getSelectedIDs();
149
                List<SQLRow> selectedRows = new ArrayList<SQLRow>(selectedIds.size());
150
                int idCpt = -1;
151
                int idClient = -1;
152
                boolean showMessage = false;
153
 
154
                String numeroFact = "";
155
                for (Integer integer : selectedIds) {
156
                    final SQLRow row = ListeDesEcheancesClientsPanel.this.panelEcheances.getListe().getSource().getPrimaryTable().getRow(integer);
157
                    // System.err.println("ListeDesEcheancesClientsPanel.ListeDesEcheancesClientsPanel().new ActionListener() {...}.actionPerformed()"
158
                    // + row);
159
                    selectedRows.add(row);
160
 
161
                    String nom = row.getForeignRow("ID_MOUVEMENT").getForeignRow("ID_PIECE").getString("NOM");
162
                    numeroFact += " " + nom;
163
 
164
                    SQLRow rowClient = row.getForeignRow("ID_CLIENT");
165
                    int idTmp = rowClient.getInt("ID_COMPTE_PCE");
166
                    int idCliTmp = rowClient.getID();
167
                    if (idCpt > -1 && idCpt != idTmp) {
168
                        JOptionPane.showMessageDialog(null, "Impossible d'effectuer un encaissement sur plusieurs factures ayant des clients avec des comptes différents.");
169
                        return;
170
                    } else {
171
                        idCpt = idTmp;
172
                    }
173
 
174
                    if (idClient > -1 && idClient != idCliTmp) {
175
                        showMessage = true;
176
                    } else {
177
                        idClient = idCliTmp;
178
                    }
179
                }
180
                if (showMessage) {
181
                    int answer = JOptionPane.showConfirmDialog(null, "Attention vous avez sélectionné des factures ayant des clients différents. Voulez vous continuer?");
182
                    if (answer != JOptionPane.YES_OPTION) {
183
                        return;
184
                    }
185
 
186
                }
187
                SQLElement encaisseElt = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT");
188
                if (ListeDesEcheancesClientsPanel.this.editEncaisse == null) {
189
                    ListeDesEcheancesClientsPanel.this.editEncaisse = new EditFrame(encaisseElt);
190
                    ListeDesEcheancesClientsPanel.this.editEncaisse.setIconImages(Gestion.getFrameIcon());
191
                }
192
 
193
                SQLRowValues rowVals = new SQLRowValues(encaisseElt.getTable());
194
 
195
                rowVals.put("ID_CLIENT", idClient);
196
                rowVals.put("NOM", numeroFact);
197
 
198
                final EncaisserMontantSQLComponent sqlComponent = (EncaisserMontantSQLComponent) ListeDesEcheancesClientsPanel.this.editEncaisse.getSQLComponent();
199
 
200
                sqlComponent.resetValue();
201
                sqlComponent.select(rowVals);
202
                sqlComponent.loadEcheancesFromRows(selectedRows);
203
                ListeDesEcheancesClientsPanel.this.editEncaisse.pack();
204
                ListeDesEcheancesClientsPanel.this.editEncaisse.setVisible(true);
205
            }
206
        });
207
 
208
        // Bouton Fermer
209
        c.gridx++;
210
        c.weightx = 0;
211
        JButton fermer = new JButton("fermer");
212
        this.add(fermer, c);
213
        fermer.addActionListener(new ActionListener() {
214
 
215
            public void actionPerformed(ActionEvent e) {
216
 
217
                JFrame tmpF = (JFrame) SwingUtilities.getRoot(ListeDesEcheancesClientsPanel.this);
218
                tmpF.setVisible(false);
219
                tmpF.dispose();
220
 
221
            }
222
        });
223
 
224
        // Gestion de la souris
225
        this.panelEcheances.getJTable().addMouseListener(new MouseAdapter() {
226
 
227
            public void mousePressed(MouseEvent mE) {
228
 
229
                // Mise à jour de l'echeance sur la frame de reglement
230
                // si cette derniere est cree
231
                final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
232
                final SQLRow row = panelEcheances.getListe().getSelectedRow();
233
                if (mE.getButton() == MouseEvent.BUTTON1) {
234
 
235
                    if (ListeDesEcheancesClientsPanel.this.editEncaisse != null) {
236
                        final SQLRowValues rowVals = new SQLRowValues(base.getTable("ENCAISSER_MONTANT"));
237
                        rowVals.put("ID_ECHEANCE_CLIENT", row.getID());
238
 
239
                        ListeDesEcheancesClientsPanel.this.editEncaisse.getSQLComponent().select(rowVals);
240
                        ListeDesEcheancesClientsPanel.this.editEncaisse.pack();
241
                    }
242
                }
243
 
244
                // Gestion du clic droit
245
                if (mE.getButton() == MouseEvent.BUTTON3) {
246
                    JPopupMenu menuDroit = new JPopupMenu();
247
 
248
                    menuDroit.add(new AbstractAction("Voir la source") {
249
 
250
                        public void actionPerformed(ActionEvent e) {
251
                            MouvementSQLElement.showSource(row.getInt("ID_MOUVEMENT"));
252
                        }
253
                    });
254
 
19 ilm 255
 
256
                    if (row != null) {
257
                        menuDroit.add(new AbstractAction("Envoyer un e-mail de relance") {
258
 
259
                            public void actionPerformed(ActionEvent e) {
260
                                sendMail(row);
261
                            }
262
                        });
263
                    }
264
 
18 ilm 265
                    if (UserRightsManager.getCurrentUserRights().haveRight(ComptaUserRight.MENU)) {
266
                        if (row.getBoolean("REG_COMPTA")) {
267
 
268
                            menuDroit.add(new AbstractAction("Annuler la régularisation en comptabilité") {
269
 
270
                                public void actionPerformed(ActionEvent e) {
271
 
272
                                    int answer = JOptionPane.showConfirmDialog(ListeDesEcheancesClientsPanel.this, "Etes vous sûr de vouloir annuler la régularisation ?");
273
                                    if (answer == JOptionPane.YES_OPTION) {
274
 
275
                                        SQLRowValues rowVals = row.createEmptyUpdateRow();
276
                                        rowVals.put("REG_COMPTA", Boolean.FALSE);
277
                                        try {
278
                                            rowVals.commit();
279
                                        } catch (SQLException e1) {
280
                                            // TODO Auto-generated catch block
281
                                            e1.printStackTrace();
282
                                        }
283
                                    }
284
                                }
285
                            });
286
                        } else {
287
 
288
                            menuDroit.add(new AbstractAction("Régularisation en comptabilité") {
289
 
290
                                public void actionPerformed(ActionEvent e) {
291
 
292
                                    String price = GestionDevise.currencyToString(row.getLong("MONTANT"));
293
                                    SQLRow rowClient = row.getForeignRow("ID_CLIENT");
294
                                    String nomClient = rowClient.getString("NOM");
295
                                    String piece = "";
296
                                    SQLRow rowMvt = row.getForeignRow("ID_MOUVEMENT");
297
                                    if (rowMvt != null) {
298
                                        SQLRow rowPiece = rowMvt.getForeignRow("ID_PIECE");
299
                                        piece = rowPiece.getString("NOM");
300
                                    }
301
                                    int answer = JOptionPane.showConfirmDialog(ListeDesEcheancesClientsPanel.this, "Etes vous sûr de vouloir régulariser l'échéance de " + nomClient
302
                                            + " d'un montant de " + price + "€ avec une saisie au kilometre?\nNom de la piéce : " + piece + ".");
303
                                    if (answer == JOptionPane.YES_OPTION) {
304
 
305
                                        SQLRowValues rowVals = row.createEmptyUpdateRow();
306
                                        rowVals.put("REG_COMPTA", Boolean.TRUE);
307
                                        try {
308
                                            rowVals.commit();
309
                                        } catch (SQLException e1) {
310
                                            // TODO Auto-generated catch block
311
                                            e1.printStackTrace();
312
                                        }
313
                                    }
314
                                }
315
                            });
316
                        }
317
                    }
318
 
319
                    menuDroit.show(mE.getComponent(), mE.getX(), mE.getY());
320
                }
321
 
322
            }
323
        });
324
 
325
        this.panelEcheances.getListe().addIListener(new IListener() {
326
            public void selectionId(int id, int field) {
327
                if (id > 1) {
328
                    final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
329
                    final SQLTable tableEch = base.getTable("ECHEANCE_CLIENT");
330
                    final SQLRow rowEch = tableEch.getRow(id);
331
 
332
                    int idMvtSource = MouvementSQLElement.getSourceId(rowEch.getInt("ID_MOUVEMENT"));
333
                    SQLRow rowMvtSource = base.getTable("MOUVEMENT").getRow(idMvtSource);
334
 
335
                    if (!rowMvtSource.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) {
336
                        ListeDesEcheancesClientsPanel.this.relancer.setEnabled(false);
337
                    } else {
338
                        ListeDesEcheancesClientsPanel.this.relancer.setEnabled(true);
339
                    }
340
                    ListeDesEcheancesClientsPanel.this.encaisser.setEnabled(true);
341
                } else {
342
                    ListeDesEcheancesClientsPanel.this.relancer.setEnabled(false);
343
 
344
                    ListeDesEcheancesClientsPanel.this.encaisser.setEnabled(false);
345
                }
346
 
347
            }
348
        });
349
        this.relancer.setEnabled(false);
350
        this.encaisser.setEnabled(false);
351
 
352
    }
353
 
354
    private SQLRow rowSource;
355
 
356
    private void relanceClient() {
357
 
358
        SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
359
        SQLElement relanceElt = Configuration.getInstance().getDirectory().getElement("RELANCE");
360
 
361
        this.rowSource = this.panelEcheances.getListe().getSelectedRow();
362
 
363
        if (this.rowSource != null) {
364
            int idMvtSource = MouvementSQLElement.getSourceId(rowSource.getInt("ID_MOUVEMENT"));
365
            SQLRow rowMvtSource = base.getTable("MOUVEMENT").getRow(idMvtSource);
366
 
367
            if (!rowMvtSource.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) {
368
                this.relancer.setEnabled(false);
369
                return;
370
            }
371
 
372
            if (this.editRelance == null) {
373
                this.editRelance = new EditFrame(relanceElt);
374
                this.editRelance.setIconImages(Gestion.getFrameIcon());
375
                this.editRelance.addEditPanelListener(new EditPanelListener() {
376
 
377
                    public void cancelled() {
378
                    }
379
 
380
                    public void modified() {
381
                    }
382
 
383
                    public void deleted() {
384
                    }
385
 
386
                    public void inserted(int id) {
387
                        System.err.println("INSERTED " + id + " -- " + rowSource.getID());
388
                        int nbRelance = rowSource.getInt("NOMBRE_RELANCE");
389
                        nbRelance++;
390
 
391
                        SQLRowValues rowValsEch = new SQLRowValues(rowSource.getTable());
392
                        rowValsEch.put("NOMBRE_RELANCE", nbRelance);
393
                        rowValsEch.put("DATE_LAST_RELANCE", new Date());
394
 
395
                        try {
396
                            rowValsEch.update(rowSource.getID());
397
                        } catch (SQLException e1) {
398
                            e1.printStackTrace();
399
                        }
400
                    }
401
                });
402
            }
403
 
404
            SQLRowValues rowVals = new SQLRowValues(relanceElt.getTable());
405
            rowVals.put("ID_SAISIE_VENTE_FACTURE", rowMvtSource.getInt("IDSOURCE"));
406
            rowVals.put("MONTANT", rowSource.getObject("MONTANT"));
407
            rowVals.put("ID_CLIENT", rowSource.getInt("ID_CLIENT"));
408
            rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(RelanceSQLElement.class));
409
            this.editRelance.getSQLComponent().select(rowVals);
410
 
411
            this.editRelance.pack();
412
            this.editRelance.setVisible(true);
413
        } else {
414
            Thread.dumpStack();
415
        }
416
    }
417
 
19 ilm 418
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);
419
 
420
    private void sendMail(SQLRow row) {
421
 
422
        SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
423
        SQLElement relanceElt = Configuration.getInstance().getDirectory().getElement("RELANCE");
424
 
425
        this.rowSource = this.panelEcheances.getListe().getSelectedRow();
426
 
427
        if (this.rowSource != null) {
428
            int idMvtSource = MouvementSQLElement.getSourceId(rowSource.getInt("ID_MOUVEMENT"));
429
            SQLRow rowMvtSource = base.getTable("MOUVEMENT").getRow(idMvtSource);
430
 
431
            if (!rowMvtSource.getString("SOURCE").equalsIgnoreCase("SAISIE_VENTE_FACTURE")) {
432
                this.relancer.setEnabled(false);
433
                return;
434
            }
435
            int idFact = rowMvtSource.getInt("IDSOURCE");
436
            SQLRow rowFacture = base.getTable("SAISIE_VENTE_FACTURE").getRow(idFact);
437
 
438
            Set<SQLField> setContact = null;
439
            SQLTable tableContact = Configuration.getInstance().getRoot().findTable("CONTACT");
440
            setContact = row.getTable().getForeignKeys(tableContact);
441
 
442
            Set<SQLField> setClient = null;
443
            SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getTable("CLIENT");
444
            setClient = row.getTable().getForeignKeys(tableClient);
445
 
446
            // Infos facture
447
            Long lTotal = (Long) rowFacture.getObject("T_TTC");
448
            Long lRestant = (Long) row.getObject("MONTANT");
449
            Long lVerse = new Long(lTotal.longValue() - lRestant.longValue());
450
            // m.put("FactureNumero", rowFacture.getString("NUMERO"));
451
            // m.put("FactureTotal", GestionDevise.currencyToString(lTotal.longValue(), true));
452
            // m.put("FactureRestant", GestionDevise.currencyToString(lRestant.longValue(), true));
453
            // m.put("FactureVerse", GestionDevise.currencyToString(lVerse.longValue(), true));
454
            // m.put("FactureDate", dateFormat2.format((Date) rowFacture.getObject("DATE")));
455
            Date dFacture = (Date) rowFacture.getObject("DATE");
456
            SQLRow modeRegRow = rowFacture.getForeignRow("ID_MODE_REGLEMENT");
457
            Date dateEch = ModeDeReglementSQLElement.calculDate(modeRegRow.getInt("AJOURS"), modeRegRow.getInt("LENJOUR"), dFacture);
458
 
459
            final String text = "Date: "
460
                    + dateFormat.format(new Date())
461
                    + "\n"
462
                    + "Concerning : Late Payment reminder\n"
463
                    + "\n\n\nTo "
464
                    + rowFacture.getForeign("ID_CLIENT").getString("NOM")
465
                    + ","
466
                    +
467
 
468
                    "\n\n\nIt has come to our attention that the following invoice has not been paid to this day."
469
                    +
470
 
471
                    "\nInvoice # "
472
                    + rowFacture.getString("NUMERO")
473
                    + " from "
474
                    + dateFormat.format(rowFacture.getDate("DATE").getTime())
475
                    + " of "
476
                    + GestionDevise.currencyToString(lRestant.longValue(), true)
477
                    + " duedate "
478
                    + dateFormat.format(dateEch)
479
                    + ".\nWe assume that this is a mere oversight and we would appreciate it if you would settle this invoice as soon as possible. In the event that this has already been accomplished in the meantime, please ignore this notice."
480
                    +
481
 
482
                    "\n\n\nThanking you in advance.";
483
            String mail = "";
484
            for (SQLField field : setContact) {
485
                if (mail == null || mail.trim().length() == 0) {
486
                    mail = row.getForeignRow(field.getName()).getString("EMAIL");
487
                }
488
            }
489
 
490
            for (SQLField field : setClient) {
491
                SQLRow rowCli = row.getForeignRow(field.getName());
492
                if (mail == null || mail.trim().length() == 0) {
493
                    mail = rowCli.getString("MAIL");
494
                }
495
            }
496
 
497
            final String adresseMail = mail;
498
 
499
            final Thread t = new Thread() {
500
                @Override
501
                public void run() {
502
 
503
                    try {
504
                        EmailComposer.getInstance().compose(adresseMail, "Late Payment reminder", text, null);
505
                    } catch (IOException exn) {
506
                        // TODO Bloc catch auto-généré
507
                        exn.printStackTrace();
508
                    } catch (InterruptedException exn) {
509
                        // TODO Bloc catch auto-généré
510
                        exn.printStackTrace();
511
                    }
512
 
513
                }
514
            };
515
 
516
            t.start();
517
        }
518
    }
519
 
18 ilm 520
    public IListPanel getListPanelEcheancesClients() {
521
        return this.panelEcheances;
522
    }
523
}