OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | 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.customerrelationship.customer.element;
15
 
16
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
17
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
180 ilm 18
import org.openconcerto.erp.config.Log;
19
 
18 ilm 20
import org.openconcerto.erp.core.common.ui.DeviseField;
180 ilm 21
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
22
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
23
import org.openconcerto.erp.generationDoc.A4;
24
import org.openconcerto.erp.generationDoc.ProgressPrintingFrame;
25
import org.openconcerto.erp.generationDoc.gestcomm.FicheRelanceSheet;
18 ilm 26
import org.openconcerto.erp.generationDoc.gestcomm.RelanceSheet;
27
import org.openconcerto.erp.preferences.PrinterNXProps;
28
import org.openconcerto.sql.element.BaseSQLComponent;
29
import org.openconcerto.sql.element.SQLComponent;
132 ilm 30
import org.openconcerto.sql.element.TreesOfSQLRows;
18 ilm 31
import org.openconcerto.sql.model.SQLRow;
32
import org.openconcerto.sql.model.SQLRowAccessor;
33
import org.openconcerto.sql.model.SQLRowValues;
34
import org.openconcerto.sql.model.SQLTable;
35
import org.openconcerto.sql.sqlobject.ElementComboBox;
36
import org.openconcerto.sql.sqlobject.JUniqueTextField;
37
import org.openconcerto.sql.view.EditFrame;
38
import org.openconcerto.ui.DefaultGridBagConstraints;
180 ilm 39
import org.openconcerto.sql.view.list.IListe;
40
import org.openconcerto.sql.view.list.RowAction;
18 ilm 41
import org.openconcerto.ui.JDate;
42
import org.openconcerto.ui.component.ITextArea;
93 ilm 43
import org.openconcerto.ui.component.InteractionMode;
18 ilm 44
import org.openconcerto.utils.ExceptionHandler;
45
 
132 ilm 46
import java.awt.GridBagConstraints;
47
import java.awt.GridBagLayout;
180 ilm 48
 
49
import java.awt.Window;
50
import java.awt.event.ActionEvent;
51
import java.awt.print.Paper;
52
import java.awt.print.PrinterException;
53
import java.awt.print.PrinterJob;
132 ilm 54
import java.sql.SQLException;
55
import java.util.ArrayList;
56
import java.util.Calendar;
57
import java.util.List;
180 ilm 58
import java.util.logging.Level;
132 ilm 59
 
180 ilm 60
import javax.print.PrintService;
61
import javax.print.attribute.Attribute;
62
import javax.print.attribute.HashPrintRequestAttributeSet;
63
import javax.print.attribute.Size2DSyntax;
64
import javax.print.attribute.standard.Copies;
65
import javax.print.attribute.standard.MediaPrintableArea;
66
import javax.print.attribute.standard.MediaSizeName;
67
import javax.swing.AbstractAction;
132 ilm 68
import javax.swing.JCheckBox;
69
import javax.swing.JLabel;
70
import javax.swing.JPanel;
71
import javax.swing.JSeparator;
72
import javax.swing.SwingUtilities;
180 ilm 73
import javax.swing.JOptionPane;
74
import javax.swing.SwingUtilities;
132 ilm 75
 
18 ilm 76
public class RelanceSQLElement extends ComptaSQLConfElement {
180 ilm 77
    public static final String ITEM_TYPE = "type.id";
78
    public static final String ITEM_DATE = "date";
79
    public static final String ITEM_NUMBER = "number";
80
    public static final String ITEM_CUSTOMER = "customer.id";
81
    public static final String ITEM_SALES_INVOICE_INPUT = "sales.invoice.input.id";
82
    public static final String ITEM_AMOUNT = "amount";
83
    public static final String ITEM_INFORMATIONS = "informations";
84
    public static final String ITEM_VISUALIZATION = "visualization";
85
    public static final String ITEM_PRINT = "impression";
86
    private static final double POINTS_PER_INCH = 72.0;
18 ilm 87
 
88
    public RelanceSQLElement() {
156 ilm 89
        super("RELANCE", "une relance client", "relances clients");
180 ilm 90
 
91
        RowAction actionShowDoc = new RowAction(new AbstractAction("Voir le document") {
92
            public void actionPerformed(ActionEvent e) {
93
                final RelanceSheet s = new RelanceSheet(IListe.get(e).getSelectedRow().asRow().fetchNew(false));
94
                s.generate(false, false, "");
95
                s.showDocument();
96
            }
97
        }, false) {
98
            @Override
99
            public boolean enabledFor(List<SQLRowValues> selection) {
100
                if (selection.size() == 1) {
101
                    SQLRowValues rowRelance = selection.get(0);
102
                    boolean isNotMail = !(rowRelance.getForeign("ID_TYPE_LETTRE_RELANCE") == null || rowRelance.isForeignEmpty("ID_TYPE_LETTRE_RELANCE"));
103
                    return isNotMail;
104
                }
105
                return false;
106
            }
107
        };
108
 
109
        getRowActions().add(actionShowDoc);
110
 
111
        RowAction actionPrintDoc = new RowAction(new AbstractAction("Imprimer") {
112
            public void actionPerformed(ActionEvent e) {
113
                print(e, false);
114
            }
115
        }, false) {
116
            @Override
117
            public boolean enabledFor(List<SQLRowValues> selection) {
118
                if (selection.size() >= 1) {
119
                    boolean isNotMail = true;
120
                    for (SQLRowValues rowRelance : selection) {
121
 
122
                        isNotMail &= !(rowRelance.getForeign("ID_TYPE_LETTRE_RELANCE") == null || rowRelance.isForeignEmpty("ID_TYPE_LETTRE_RELANCE"));
123
                    }
124
                    return isNotMail;
125
                }
126
                return false;
127
            }
128
        };
129
 
130
        getRowActions().add(actionPrintDoc);
131
 
132
        // Impression
133
 
134
        RowAction actionPrintDocFact = new RowAction(new AbstractAction("Imprimer avec la facture") {
135
            public void actionPerformed(ActionEvent e) {
136
                print(e, true);
137
            }
138
        }, false) {
139
            @Override
140
            public boolean enabledFor(List<SQLRowValues> selection) {
141
                if (selection.size() >= 1) {
142
                    boolean isNotMail = true;
143
                    for (SQLRowValues rowRelance : selection) {
144
 
145
                        isNotMail &= !(rowRelance.getForeign("ID_TYPE_LETTRE_RELANCE") == null || rowRelance.isForeignEmpty("ID_TYPE_LETTRE_RELANCE"));
146
                    }
147
                    return isNotMail;
148
                }
149
                return false;
150
            }
151
        };
152
 
153
        getRowActions().add(actionPrintDocFact);
154
 
155
        // Générer
156
 
157
        RowAction actionGen = new RowAction(new AbstractAction("Générer le document") {
158
            public void actionPerformed(ActionEvent e) {
159
 
160
                for (SQLRowValues rowVals : IListe.get(e).getSelectedRows()) {
161
                    final RelanceSheet s = new RelanceSheet(rowVals.asRow().fetchNew(false));
162
                    String printer = PrinterNXProps.getInstance().getStringProperty("RelancePrinter");
163
                    s.generate(false, true, printer, true);
164
                    s.showDocument();
165
                }
166
            }
167
        }, false) {
168
            @Override
169
            public boolean enabledFor(List<SQLRowValues> selection) {
170
                if (selection.size() >= 1) {
171
                    SQLRowValues rowRelance = selection.get(0);
172
                    boolean isNotMail = !(rowRelance.getForeign("ID_TYPE_LETTRE_RELANCE") == null || rowRelance.isForeignEmpty("ID_TYPE_LETTRE_RELANCE"));
173
                    return isNotMail;
174
                }
175
                return false;
176
            }
177
        };
178
 
179
        getRowActions().add(actionGen);
180
 
181
        RowAction actionFiche = new RowAction(new AbstractAction("Créer la fiche de relance") {
182
            public void actionPerformed(ActionEvent e) {
183
                try {
184
                    FicheRelanceSheet sheet = new FicheRelanceSheet(IListe.get(e).getSelectedRow().asRow().fetchNew(false));
185
                    sheet.createDocumentAsynchronous();
186
                    sheet.showPrintAndExportAsynchronous(true, false, true);
187
                } catch (Exception ex) {
188
                    ExceptionHandler.handle("Impression impossible", ex);
189
                }
190
            }
191
        }, false) {
192
            @Override
193
            public boolean enabledFor(List<SQLRowValues> selection) {
194
                return (selection.size() == 1);
195
            }
196
        };
197
 
198
        getRowActions().add(actionFiche);
199
 
18 ilm 200
    }
201
 
202
    protected List<String> getListFields() {
203
        final List<String> l = new ArrayList<String>();
204
        l.add("NUMERO");
205
        l.add("ID_CLIENT");
206
        l.add("ID_SAISIE_VENTE_FACTURE");
207
        l.add("DATE");
208
        l.add("ID_TYPE_LETTRE_RELANCE");
209
        l.add("MONTANT");
210
        l.add("INFOS");
211
        return l;
212
    }
213
 
214
    protected List<String> getComboFields() {
215
        final List<String> l = new ArrayList<String>();
216
        l.add("NUMERO");
217
        return l;
218
    }
219
 
220
    /*
221
     * (non-Javadoc)
222
     *
223
     * @see org.openconcerto.devis.SQLElement#getComponent()
224
     */
225
    public SQLComponent createComponent() {
226
        return new BaseSQLComponent(this) {
227
 
228
            ElementComboBox comboFacture = new ElementComboBox();
229
            ElementComboBox comboClient = new ElementComboBox();
230
            ElementComboBox comboTypeLettre;
231
            JUniqueTextField textNumero = new JUniqueTextField();
232
            JCheckBox checkImpression = new JCheckBox("Impression");
233
            JCheckBox checkVisu = new JCheckBox("Visualisation");
234
 
235
            public void addViews() {
236
 
237
                this.setLayout(new GridBagLayout());
238
                final GridBagConstraints c = new DefaultGridBagConstraints();
239
 
240
                // Type lettre
241
                JLabel labelTypeLettre = new JLabel(getLabelFor("ID_TYPE_LETTRE_RELANCE"));
242
                labelTypeLettre.setHorizontalAlignment(JLabel.RIGHT);
243
                this.add(labelTypeLettre, c);
244
 
245
                c.gridx++;
246
                // SQLElement typeLettreElt =
247
                // Configuration.getInstance().getDirectory().getElement("TYPE_LETTRE_RELANCE");
248
                this.comboTypeLettre = new ElementComboBox(false);
249
 
250
                this.add(this.comboTypeLettre, c);
251
 
252
                // Date
253
                c.gridx++;
254
                JLabel labelDate = new JLabel(getLabelFor("DATE"));
255
                labelDate.setHorizontalAlignment(JLabel.RIGHT);
256
                this.add(labelDate, c);
257
 
258
                JDate date = new JDate(true);
259
                c.gridx++;
260
                this.add(date, c);
261
 
262
                // Numero
263
                c.gridx = 0;
264
                c.gridy++;
265
                JLabel labelNumero = new JLabel(getLabelFor("NUMERO"));
266
                labelNumero.setHorizontalAlignment(JLabel.RIGHT);
267
                this.add(labelNumero, c);
268
 
269
                c.gridx++;
270
                this.add(this.textNumero, c);
271
 
272
                // Client
273
                c.gridy++;
274
                c.gridx = 0;
275
 
276
                JLabel labelClient = new JLabel(getLabelFor("ID_CLIENT"));
277
                labelClient.setHorizontalAlignment(JLabel.RIGHT);
278
                this.add(labelClient, c);
279
                c.gridx++;
280
                c.gridwidth = GridBagConstraints.REMAINDER;
281
                this.add(this.comboClient, c);
282
 
283
                // Facture
284
                c.gridy++;
285
                c.gridx = 0;
286
                c.gridwidth = 1;
287
                JLabel labelFacture = new JLabel(getLabelFor("ID_SAISIE_VENTE_FACTURE"));
288
                labelFacture.setHorizontalAlignment(JLabel.RIGHT);
289
                this.add(labelFacture, c);
290
                c.gridx++;
291
                // c.gridwidth = GridBagConstraints.REMAINDER;
292
                this.add(this.comboFacture, c);
293
 
294
                // Montant
295
                c.gridx++;
296
                JLabel labelMontant = new JLabel(getLabelFor("MONTANT"));
297
                labelMontant.setHorizontalAlignment(JLabel.RIGHT);
298
                this.add(labelMontant, c);
299
 
300
                c.gridx++;
301
                DeviseField textMontant = new DeviseField();
302
                this.add(textMontant, c);
303
 
304
                // Commentaires
305
                c.gridx = 0;
306
                c.gridy++;
307
                this.add(new JLabel(getLabelFor("INFOS")), c);
308
 
309
                c.gridx++;
310
                c.gridwidth = GridBagConstraints.REMAINDER;
311
                c.fill = GridBagConstraints.HORIZONTAL;
312
                c.weightx = 1;
313
                this.add(new JSeparator(JSeparator.HORIZONTAL), c);
314
 
315
                c.gridx = 0;
316
                c.gridy++;
317
                c.weighty = 1;
318
                c.fill = GridBagConstraints.BOTH;
319
                ITextArea textInfos = new ITextArea();
320
                this.add(textInfos, c);
321
 
322
                JPanel panelCheck = new JPanel();
323
                panelCheck.setBorder(null);
324
                panelCheck.add(this.checkVisu);
325
                panelCheck.add(this.checkImpression);
326
                c.fill = GridBagConstraints.NONE;
327
                c.weighty = 0;
328
                c.gridy++;
329
                this.add(panelCheck, c);
330
 
331
                this.addRequiredSQLObject(textMontant, "MONTANT");
332
                this.addRequiredSQLObject(date, "DATE");
333
                this.addRequiredSQLObject(this.comboTypeLettre, "ID_TYPE_LETTRE_RELANCE");
334
                this.addRequiredSQLObject(this.comboClient, "ID_CLIENT");
335
                this.addRequiredSQLObject(this.comboFacture, "ID_SAISIE_VENTE_FACTURE");
336
                this.addSQLObject(textInfos, "INFOS");
337
                this.addRequiredSQLObject(this.textNumero, "NUMERO");
338
                this.comboTypeLettre.setButtonsVisible(false);
339
 
340
                this.textNumero.setText(NumerotationAutoSQLElement.getNextNumero(RelanceSQLElement.class));
341
                this.checkVisu.setSelected(true);
342
            }
343
 
344
            @Override
345
            public int insert(SQLRow order) {
346
 
347
                if (this.textNumero.checkValidation()) {
348
                    // incrémentation du numéro auto
349
                    if (NumerotationAutoSQLElement.getNextNumero(RelanceSQLElement.class).equalsIgnoreCase(this.textNumero.getText().trim())) {
350
                        SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
351
                        SQLRowValues rowVals = new SQLRowValues(tableNum);
352
                        int val = tableNum.getRow(2).getInt("RELANCE_START");
353
                        val++;
354
                        rowVals.put("RELANCE_START", Integer.valueOf(val));
355
 
356
                        try {
357
                            rowVals.update(2);
358
                        } catch (SQLException e) {
359
 
360
                            e.printStackTrace();
361
                        }
362
                    }
363
 
364
                    // insertion
365
                    int id = super.insert(order);
366
 
367
                    // génération du document
368
                    RelanceSheet s = new RelanceSheet(getTable().getRow(id));
369
                    String printer = PrinterNXProps.getInstance().getStringProperty("RelancePrinter");
370
                    s.generate(this.checkImpression.isSelected(), this.checkVisu.isSelected(), printer, true);
371
 
372
                    return id;
373
                } else {
374
                    ExceptionHandler.handle("Impossible d'ajouter, numéro de relance existant.");
375
                    Object root = SwingUtilities.getRoot(this);
376
                    if (root instanceof EditFrame) {
377
                        EditFrame frame = (EditFrame) root;
378
                        frame.getPanel().setAlwaysVisible(true);
379
                    }
380
                    return getSelectedID();
381
                }
382
            }
383
 
384
            @Override
385
            public void select(SQLRowAccessor r) {
386
                super.select(r);
387
 
388
                // numero de facture et client figé
93 ilm 389
                this.comboFacture.setInteractionMode(InteractionMode.DISABLED);
390
                this.comboClient.setInteractionMode(InteractionMode.DISABLED);
18 ilm 391
                this.fireValidChange();
392
            }
393
 
394
            @Override
395
            public void update() {
396
                if (!this.textNumero.checkValidation()) {
397
                    ExceptionHandler.handle("Impossible d'ajouter, numéro de relance existant.");
398
                    Object root = SwingUtilities.getRoot(this);
399
                    if (root instanceof EditFrame) {
400
                        EditFrame frame = (EditFrame) root;
401
                        frame.getPanel().setAlwaysVisible(true);
402
                    }
403
                    return;
404
                }
405
 
406
                super.update();
407
 
408
                // regénération du document
409
                RelanceSheet s = new RelanceSheet(getTable().getRow(getSelectedID()));
410
                String printer = PrinterNXProps.getInstance().getStringProperty("RelancePrinter");
411
                s.generate(this.checkImpression.isSelected(), this.checkVisu.isSelected(), printer);
412
            }
413
 
414
        };
415
    }
57 ilm 416
 
417
    @Override
132 ilm 418
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
419
 
420
        for (SQLRow row : trees.getRows()) {
421
            if (row.getForeign("ID_ECHEANCE_CLIENT") != null && !row.isForeignEmpty("ID_ECHEANCE_CLIENT")) {
422
                SQLRow rowEch = row.getForeign("ID_ECHEANCE_CLIENT");
423
                int count = rowEch.getInt("NOMBRE_RELANCE");
424
                count = Math.max(0, count - 1);
425
 
426
                SQLRowValues rowValsUp = rowEch.createEmptyUpdateRow();
427
                rowValsUp.put("NOMBRE_RELANCE", count);
428
                rowValsUp.put("DATE_LAST_RELANCE", null);
429
                if (count > 0) {
430
                    List<SQLRow> rows = rowEch.getReferentRows(row.getTable());
431
                    Calendar cal = null;
432
                    for (SQLRow sqlRow : rows) {
433
                        if (sqlRow.getID() != row.getID() && sqlRow.getDate("DATE") != null && (cal == null || cal.before(sqlRow.getDate("DATE")))) {
434
                            cal = sqlRow.getDate("DATE");
435
                        }
436
                    }
437
                    if (cal != null) {
438
                        rowValsUp.put("DATE_LAST_RELANCE", cal.getTime());
439
                    }
440
                }
441
                rowValsUp.commit();
442
            }
443
        }
444
        super.archive(trees, cutLinks);
445
    }
446
 
447
    @Override
57 ilm 448
    protected String createCode() {
156 ilm 449
        return this.createCodeOfPackage() + ".chaseletter";
57 ilm 450
    }
180 ilm 451
 
452
    public void print(final ActionEvent ev, boolean withInvoice) {
453
        //
454
        final IListe ilist = IListe.get(ev);
455
        String printerName = PrinterNXProps.getInstance().getStringProperty("RelancePrinter");
456
        // Printer configuration
457
        final PrinterJob printJob = PrinterJob.getPrinterJob();
458
 
459
        // Set the printer
460
        PrintService myService = null;
461
        if (printerName != null && printerName.trim().length() > 0) {
462
            final PrintService[] services = PrinterJob.lookupPrintServices();
463
            for (int i = 0; i < services.length; i++) {
464
                if (services[i].getName().equals(printerName)) {
465
                    myService = services[i];
466
                    break;
467
                }
468
            }
469
            if (myService != null) {
470
                try {
471
                    printJob.setPrintService(myService);
472
                } catch (PrinterException e) {
473
                    Log.get().log(Level.SEVERE, "cannot print", e);
474
                    JOptionPane.showMessageDialog(null, "Imprimante non compatible");
475
                    return;
476
                }
477
            }
478
        }
479
 
480
        final HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
481
        // L'impression est forcée en A4, sur OpenSuse le format est en
482
        // Letter par défaut alors que l'imprimante est en A4 dans le système
483
        final MediaSizeName media = MediaSizeName.ISO_A4;
484
        attributes.add(media);
485
        Paper paper = new A4(0, 0);
486
 
487
        final MediaPrintableArea printableArea = new MediaPrintableArea((float) (paper.getImageableX() / POINTS_PER_INCH), (float) (paper.getImageableY() / POINTS_PER_INCH),
488
                (float) (paper.getImageableWidth() / POINTS_PER_INCH), (float) (paper.getImageableHeight() / POINTS_PER_INCH), Size2DSyntax.INCH);
489
        attributes.add(printableArea);
490
        attributes.add(new Copies(1));
491
 
492
        boolean okToPrint = printJob.printDialog(attributes);
493
        final Attribute attribute = attributes.get(Copies.class);
494
        if (attribute != null) {
495
            final Copies attributeCopies = (Copies) attribute;
496
            final int value = attributeCopies.getValue();
497
            printJob.setCopies(value);
498
        } else {
499
            printJob.setCopies(1);
500
        }
501
 
502
        if (okToPrint) {
503
            Window w = SwingUtilities.getWindowAncestor(ilist);
504
            final ProgressPrintingFrame pFrame = new ProgressPrintingFrame(w, printJob, "Impression", "Impression en cours", 300);
505
            // Génération + impression
506
            final List<SQLRowValues> rows = IListe.get(ev).getSelectedRows();
507
            final Thread thread = new Thread() {
508
                @Override
509
                public void run() {
510
                    final int size = rows.size();
511
                    for (int i = 0; i < size; i++) {
512
                        final int index = i;
513
                        SwingUtilities.invokeLater(new Runnable() {
514
 
515
                            @Override
516
                            public void run() {
517
                                pFrame.setMessage("Document " + (index + 1) + "/" + size);
518
                                pFrame.setProgress((100 * (index + 1)) / size);
519
                            }
520
                        });
521
                        if (!pFrame.isCancelled()) {
522
                            SQLRowValues r = rows.get(i);
523
                            SQLRow rowRelance = r.asRow().fetchNew(false);
524
                            RelanceSheet s = new RelanceSheet(rowRelance);
525
                            s.printDocument(printJob);
526
                            if (withInvoice) {
527
                                SaisieVenteFactureSQLElement element = getDirectory().getElement(SaisieVenteFactureSQLElement.class);
528
                                final VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowRelance.getForeignRow("ID_SAISIE_VENTE_FACTURE"));
529
                                try {
530
                                    sheet.getOrCreateDocumentFile();
531
                                    sheet.printDocument(printJob);
532
                                } catch (Exception e) {
533
                                    ExceptionHandler.handle("Erreur lors de la création de la facture", e);
534
                                }
535
                            }
536
 
537
                        }
538
                    }
539
                }
540
            };
541
            thread.setPriority(Thread.MIN_PRIORITY);
542
            thread.setDaemon(true);
543
            pFrame.setLocationRelativeTo(ilist);
544
            pFrame.setVisible(true);
545
            thread.start();
546
 
547
        }
548
 
549
    }
18 ilm 550
}