OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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