OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Rev 182 | 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.config.ComptaPropsConfiguration;
174 ilm 17
import org.openconcerto.erp.core.customerrelationship.mail.EmailTemplate;
18
import org.openconcerto.erp.core.customerrelationship.mail.ValueListener;
18 ilm 19
import org.openconcerto.erp.generationDoc.AbstractSheetXml;
20
import org.openconcerto.sql.Configuration;
41 ilm 21
import org.openconcerto.sql.model.SQLBase;
18 ilm 22
import org.openconcerto.sql.model.SQLField;
23
import org.openconcerto.sql.model.SQLRow;
19 ilm 24
import org.openconcerto.sql.model.SQLRowAccessor;
93 ilm 25
import org.openconcerto.sql.model.SQLRowValues;
18 ilm 26
import org.openconcerto.sql.model.SQLTable;
27
import org.openconcerto.sql.view.list.IListe;
19 ilm 28
import org.openconcerto.sql.view.list.RowAction;
18 ilm 29
import org.openconcerto.ui.EmailComposer;
30
import org.openconcerto.utils.ExceptionHandler;
156 ilm 31
import org.openconcerto.utils.ListMap;
174 ilm 32
import org.openconcerto.utils.i18n.TranslationManager;
18 ilm 33
 
34
import java.awt.event.ActionEvent;
35
import java.io.File;
36
import java.lang.reflect.Constructor;
37
import java.util.ArrayList;
38
import java.util.List;
39
import java.util.Set;
156 ilm 40
import java.util.StringJoiner;
18 ilm 41
 
42
import javax.swing.AbstractAction;
65 ilm 43
import javax.swing.Action;
73 ilm 44
import javax.swing.JOptionPane;
41 ilm 45
import javax.swing.SwingUtilities;
18 ilm 46
 
25 ilm 47
public class MouseSheetXmlListeListener {
18 ilm 48
 
49
    private Class<? extends AbstractSheetXml> clazz;
50
    protected IListe liste;
51
 
52
    private boolean previewIsVisible = true;
53
    private boolean showIsVisible = true;
54
    private boolean printIsVisible = true;
55
    private boolean generateIsVisible = true;
28 ilm 56
    private boolean previewHeader = false;
57
    private boolean showHeader = false;
58
    private boolean generateHeader = false;
18 ilm 59
 
25 ilm 60
    public MouseSheetXmlListeListener(Class<? extends AbstractSheetXml> clazz) {
61
        this(clazz, true, true, true, true);
62
 
18 ilm 63
    }
64
 
25 ilm 65
    public MouseSheetXmlListeListener(Class<? extends AbstractSheetXml> clazz, boolean show, boolean preview, boolean print, boolean generate) {
18 ilm 66
        this.clazz = clazz;
67
        this.printIsVisible = print;
68
        this.previewIsVisible = preview;
69
        this.showIsVisible = show;
70
        this.generateIsVisible = generate;
71
    }
72
 
73
    protected Class<? extends AbstractSheetXml> getSheetClass() {
74
        return this.clazz;
75
    }
76
 
77
    protected AbstractSheetXml createAbstractSheet(SQLRow row) {
41 ilm 78
        try {
79
            Constructor<? extends AbstractSheetXml> ctor = getSheetClass().getConstructor(SQLRow.class);
80
            AbstractSheetXml sheet = ctor.newInstance(row);
81
            return sheet;
82
        } catch (Exception e) {
73 ilm 83
            ExceptionHandler.handle("sheet creation error", e);
18 ilm 84
        }
41 ilm 85
        return null;
18 ilm 86
    }
87
 
142 ilm 88
    public List<AbstractSheetXml> createAbstractSheets(List<SQLRow> rows) {
149 ilm 89
        final List<AbstractSheetXml> sheets = new ArrayList<>(rows.size());
142 ilm 90
        try {
91
            final Constructor<? extends AbstractSheetXml> ctor = getSheetClass().getConstructor(SQLRow.class);
92
            for (SQLRow row : rows) {
93
                AbstractSheetXml sheet = ctor.newInstance(row);
94
                sheets.add(sheet);
95
            }
96
        } catch (Exception e) {
97
            ExceptionHandler.handle("sheet creation error", e);
98
        }
99
        return sheets;
100
    }
101
 
41 ilm 102
    protected String getMailObject(SQLRow row) {
103
        return "";
104
    }
105
 
28 ilm 106
    public void setPreviewHeader(boolean previewHeader) {
107
        this.previewHeader = previewHeader;
108
    }
18 ilm 109
 
28 ilm 110
    public void setGenerateHeader(boolean generateHeader) {
111
        this.generateHeader = generateHeader;
112
    }
18 ilm 113
 
28 ilm 114
    public void setShowHeader(boolean showHeader) {
115
        this.showHeader = showHeader;
116
    }
117
 
174 ilm 118
    protected void sendMail(EmailTemplate template, final AbstractSheetXml sheet, final boolean readOnly) {
156 ilm 119
        List<AbstractSheetXml> l = new ArrayList<>(1);
142 ilm 120
        l.add(sheet);
174 ilm 121
        sendMail(template, l, readOnly);
142 ilm 122
    }
28 ilm 123
 
174 ilm 124
    protected void sendMail(EmailTemplate template, final List<AbstractSheetXml> sheets, final boolean readOnly) {
156 ilm 125
        final Thread t = new Thread() {
126
            @Override
127
            public void run() {
128
                ListMap<String, File> mailFilesMap = new ListMap<>();
129
                for (AbstractSheetXml sheet : sheets) {
130
                    String mail = "";
131
                    final SQLRow row = sheet.getSQLRow();
132
                    Set<SQLField> setContact = null;
133
                    SQLTable tableContact = Configuration.getInstance().getRoot().findTable("CONTACT");
134
                    setContact = row.getTable().getForeignKeys(tableContact);
18 ilm 135
 
156 ilm 136
                    Set<SQLField> setClient = null;
137
                    SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getTable("CLIENT");
138
                    setClient = row.getTable().getForeignKeys(tableClient);
18 ilm 139
 
156 ilm 140
                    for (SQLField field : setContact) {
142 ilm 141
                        if (mail == null || mail.trim().length() == 0) {
156 ilm 142
                            mail = row.getForeignRow(field.getName()).getString("EMAIL");
142 ilm 143
                        }
18 ilm 144
                    }
156 ilm 145
                    String nomClient = "";
146
                    if (setClient != null && (mail == null || mail.trim().length() == 0)) {
147
                            for (SQLField field : setClient) {
148
                                SQLRow rowCli = row.getForeignRow(field.getName());
149
                                if (mail == null || mail.trim().length() == 0) {
150
                                    mail = rowCli.getString("MAIL");
151
                                }
152
                                nomClient = rowCli.getString("NOM");
153
                            }
154
                    }
18 ilm 155
 
156 ilm 156
                    if (mail.trim().length() == 0) {
157
                        mail = nomClient;
158
                    }
41 ilm 159
 
156 ilm 160
                    String table = row.getTable().getName();
161
                    if (table.equalsIgnoreCase("COMMANDE") || table.equalsIgnoreCase("DEMANDE_PRIX") || table.equalsIgnoreCase("FACTURE_FOURNISSEUR")) {
162
                        mail = "";
163
                    }
164
                    if (mail == null || mail.trim().length() == 0) {
165
                        SQLTable tableF = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getTable("FOURNISSEUR");
166
                        Set<SQLField> setF = null;
167
                        setF = row.getTable().getForeignKeys(tableF);
41 ilm 168
 
156 ilm 169
                        if (setF != null) {
170
 
171
                            for (SQLField field : setF) {
172
                                SQLRow rowF = row.getForeignRow(field.getName());
173
                                if (mail == null || mail.trim().length() == 0) {
174
                                    mail = rowF.getString("MAIL");
175
                                }
176
                            }
142 ilm 177
                        }
41 ilm 178
 
156 ilm 179
                        if (mail == null || mail.trim().length() == 0) {
180
                            SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
181
                            if (base.containsTable("MONTEUR")) {
182
                                SQLTable tableM = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getTable("MONTEUR");
183
                                Set<SQLField> setM = null;
184
                                setM = row.getTable().getForeignKeys(tableM);
185
                                if (setM != null) {
186
                                    for (SQLField field : setM) {
187
                                        SQLRow rowM = row.getForeignRow(field.getName());
188
                                        if (rowM.getForeignRow("ID_CONTACT_FOURNISSEUR") != null && !rowM.getForeignRow("ID_CONTACT_FOURNISSEUR").isUndefined()) {
189
                                            mail = rowM.getForeignRow("ID_CONTACT_FOURNISSEUR").getString("EMAIL");
190
                                        }
191
                                    }
142 ilm 192
                                }
41 ilm 193
                            }
194
                        }
156 ilm 195
                        if (mail == null || mail.trim().length() == 0) {
196
                            SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
197
                            if (base.containsTable("TRANSPORTEUR")) {
41 ilm 198
 
156 ilm 199
                                SQLTable tableM = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getTable("TRANSPORTEUR");
200
                                Set<SQLField> setM = null;
201
                                setM = row.getTable().getForeignKeys(tableM);
41 ilm 202
 
156 ilm 203
                                if (setM != null) {
41 ilm 204
 
156 ilm 205
                                    for (SQLField field : setM) {
206
                                        SQLRow rowM = row.getForeignRow(field.getName());
207
                                        if (rowM.getForeignRow("ID_CONTACT_FOURNISSEUR") != null && !rowM.getForeignRow("ID_CONTACT_FOURNISSEUR").isUndefined()) {
208
                                            mail = rowM.getForeignRow("ID_CONTACT_FOURNISSEUR").getString("EMAIL");
209
                                        }
210
                                    }
142 ilm 211
                                }
41 ilm 212
                            }
213
                        }
214
                    }
156 ilm 215
                    try {
216
                        if (readOnly) {
217
                            mailFilesMap.add(mail, sheet.getOrCreatePDFDocumentFile(true).getAbsoluteFile());
218
                        } else {
219
                            mailFilesMap.add(mail, sheet.getOrCreateDocumentFile().getAbsoluteFile());
220
 
221
                        }
222
                    } catch (Exception e) {
223
                        ExceptionHandler.handle("Impossible de charger le document PDF", e);
224
                    }
41 ilm 225
                }
18 ilm 226
 
156 ilm 227
                for (final String mailDest : mailFilesMap.keySet()) {
19 ilm 228
 
156 ilm 229
                    final List<File> files = mailFilesMap.get(mailDest);
142 ilm 230
 
156 ilm 231
                    SwingUtilities.invokeLater(new Runnable() {
41 ilm 232
 
156 ilm 233
                        @Override
234
                        public void run() {
235
                            try {
236
                                String subject = sheets.get(0).getReference();
174 ilm 237
                                if (template != null) {
238
                                    subject = template.getTitle() + " " + sheets.get(0).getReference().trim();
239
                                }
240
                                subject = subject.trim();
156 ilm 241
                                if (subject.isEmpty()) {
242
                                    final StringJoiner joiner = new StringJoiner(", ");
243
                                    for (File f : files) {
244
                                        joiner.add(f.getName());
245
                                    }
246
                                    subject = joiner.toString();
41 ilm 247
                                }
174 ilm 248
                                String message = getMailObject(sheets.get(0).getSQLRow());
249
                                if (template != null) {
250
                                    if (template.getText().contains("{message}")) {
251
                                        message = template.getText().replace("{message}", message);
252
                                    } else {
253
                                        message += template.getText();
254
                                    }
255
                                }
156 ilm 256
                                EmailComposer.getInstance().compose(mailDest, subject, message, files.toArray(new File[files.size()]));
257
                            } catch (Exception e) {
258
                                ExceptionHandler.handle("Impossible d'envoyer le courriel!", e);
41 ilm 259
                            }
156 ilm 260
                        }
261
                    });
18 ilm 262
                }
156 ilm 263
 
18 ilm 264
            }
265
 
156 ilm 266
        };
267
        t.start();
268
 
18 ilm 269
    }
270
 
25 ilm 271
    public List<RowAction> addToMenu() {
18 ilm 272
        return null;
273
    }
274
 
19 ilm 275
    public List<RowAction> getRowActions() {
149 ilm 276
        List<RowAction> l = new ArrayList<>();
19 ilm 277
 
278
        if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
279
            if (this.showIsVisible) {
67 ilm 280
                RowAction action = new RowAction(new AbstractAction() {
19 ilm 281
                    public void actionPerformed(ActionEvent ev) {
149 ilm 282
                        try {
283
                            createAbstractSheet(IListe.get(ev).fetchSelectedRow()).openDocument(false);
284
                        } catch (Exception e) {
285
                            ExceptionHandler.handle("Impossible d'ouvrir le fichier", e);
286
                        }
19 ilm 287
                    }
288
 
67 ilm 289
                }, this.previewHeader, "document.modify") {
142 ilm 290
 
19 ilm 291
                    @Override
21 ilm 292
                    public boolean enabledFor(IListeEvent evt) {
149 ilm 293
                        // On ne teste pas l'existence du fichier génété car les IOs peuvent prendre
294
                        // du temps
295
                        return evt.getSelectedRow() != null && (evt.getTotalRowCount() >= 1);
19 ilm 296
                    }
65 ilm 297
 
28 ilm 298
                };
299
                l.add(action);
19 ilm 300
 
301
            }
302
        } else {
174 ilm 303
            // ODS Viewer
19 ilm 304
            if (this.previewIsVisible) {
67 ilm 305
                l.add(new RowAction(new AbstractAction() {
19 ilm 306
                    public void actionPerformed(ActionEvent ev) {
25 ilm 307
                        try {
174 ilm 308
                            final AbstractSheetXml sheet = createAbstractSheet(IListe.get(ev).fetchSelectedRow());
309
                            final SQLTable table = IListe.get(ev).getSource().getPrimaryTable();
310
                            sheet.showPreviewDocument(TranslationManager.getInstance().getTranslationForAction("email"), new Runnable() {
311
 
312
                                @Override
313
                                public void run() {
314
                                    EmailTemplate.askTemplate(IListe.get(ev), table.getDBRoot(), new ValueListener() {
315
 
316
                                        @Override
317
                                        public void valueSelected(Object value) {
318
                                            sendMail((EmailTemplate) value, sheet, true);
319
                                        }
320
                                    });
321
 
322
                                }
323
                            });
25 ilm 324
                        } catch (Exception e) {
149 ilm 325
                            ExceptionHandler.handle("Impossible d'ouvrir le fichier", e);
25 ilm 326
                        }
19 ilm 327
                    }
328
 
67 ilm 329
                }, this.previewHeader, "document.preview") {
25 ilm 330
 
19 ilm 331
                    @Override
25 ilm 332
                    public boolean enabledFor(IListeEvent evt) {
149 ilm 333
                        // On ne teste pas l'existence du fichier génété car les IOs peuvent prendre
334
                        // du temps
335
                        return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1;
19 ilm 336
                    }
337
                });
25 ilm 338
 
19 ilm 339
            }
340
        }
341
 
342
        // action supplémentaire
25 ilm 343
        List<RowAction> list = addToMenu();
19 ilm 344
        if (list != null) {
25 ilm 345
            for (RowAction rowAction : list) {
346
                l.add(rowAction);
19 ilm 347
            }
348
        }
349
 
149 ilm 350
        if (Boolean.getBoolean("org.openconcerto.oo.useODSViewer") && this.showIsVisible) {
351
            l.add(new RowAction(new AbstractAction() {
352
                public void actionPerformed(ActionEvent ev) {
353
                    try {
80 ilm 354
                        createAbstractSheet(IListe.get(ev).fetchSelectedRow()).openDocument(false);
149 ilm 355
                    } catch (Exception e) {
356
                        ExceptionHandler.handle("Impossible d'ouvrir le fichier", e);
19 ilm 357
                    }
149 ilm 358
                }
359
            }, this.showHeader, "document.modify") {
142 ilm 360
 
149 ilm 361
                @Override
362
                public boolean enabledFor(IListeEvent evt) {
363
                    // On ne teste pas l'existence du fichier génété car les IOs peuvent prendre
364
                    // du temps
365
                    return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1;
366
                }
367
            });
368
 
19 ilm 369
        }
370
 
371
        if (this.printIsVisible) {
372
 
132 ilm 373
            // Impression rapide : imprime le ou les documents sélectionnés (les génère si besoin)
374
            // en proposant l'interface Java d'impression
149 ilm 375
            l.add(new RowAction(new PrintDocumentAction(this), false, "document.print") {
65 ilm 376
 
19 ilm 377
                @Override
25 ilm 378
                public boolean enabledFor(IListeEvent evt) {
132 ilm 379
                    return evt.getSelectedRow() != null && evt.getSelectedRows().size() > 0;
19 ilm 380
                }
381
            });
382
 
383
        }
384
 
149 ilm 385
        if (this.showIsVisible)
19 ilm 386
 
149 ilm 387
        {
388
 
144 ilm 389
            l.add(getSendMailPDF());
142 ilm 390
 
144 ilm 391
            l.add(getSendMail());
142 ilm 392
 
19 ilm 393
        }
394
        if (this.generateIsVisible) {
67 ilm 395
            l.add(new RowAction(new AbstractAction() {
19 ilm 396
                public void actionPerformed(ActionEvent ev) {
93 ilm 397
                    List<SQLRowValues> l = IListe.get(ev).getSelectedRows();
90 ilm 398
 
399
                    if (l.size() == 1) {
400
                        createDocument(ev);
401
                    } else {
402
                        createDocuments(l);
403
                    }
19 ilm 404
                }
67 ilm 405
            }, this.generateHeader, "document.create") {
73 ilm 406
 
19 ilm 407
                @Override
93 ilm 408
                public boolean enabledFor(List<SQLRowValues> selection) {
156 ilm 409
                    return selection != null && !selection.isEmpty();
19 ilm 410
                }
65 ilm 411
 
19 ilm 412
            });
413
        }
414
 
415
        return l;
416
    }
65 ilm 417
 
144 ilm 418
    public RowAction getSendMail() {
419
        return new RowAction(new AbstractAction() {
420
            public void actionPerformed(ActionEvent ev) {
174 ilm 421
                sendMail(ev, false);
144 ilm 422
            }
423
        }, false, "document.send.email") {
424
 
425
            @Override
426
            public boolean enabledFor(IListeEvent evt) {
149 ilm 427
                // On ne teste pas l'existence du fichier génété car les IOs peuvent prendre du
428
                // temps
429
                return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1;
144 ilm 430
            }
149 ilm 431
 
144 ilm 432
        };
433
    }
434
 
435
    public RowAction getSendMailPDF() {
436
        return new RowAction(new AbstractAction() {
437
            public void actionPerformed(ActionEvent ev) {
174 ilm 438
                sendMail(ev, true);
144 ilm 439
            }
440
        }, false, "document.pdf.send.email") {
441
 
442
            @Override
443
            public boolean enabledFor(IListeEvent evt) {
149 ilm 444
                // On ne teste pas l'existence du fichier génété car les IOs peuvent prendre du
445
                // temps
446
                return evt.getSelectedRow() != null && evt.getTotalRowCount() >= 1;
144 ilm 447
            }
149 ilm 448
 
144 ilm 449
        };
450
 
451
    }
452
 
93 ilm 453
    private void createDocuments(List<? extends SQLRowAccessor> selection) {
90 ilm 454
        int a = JOptionPane.showConfirmDialog(null, "Voulez vous recréer l'ensemble des documents sélectionnés?", "Génération de documents", JOptionPane.YES_NO_OPTION);
455
        if (a == JOptionPane.YES_OPTION) {
456
            for (SQLRowAccessor sqlRowAccessor : selection) {
457
                final AbstractSheetXml sheet = createAbstractSheet(sqlRowAccessor.getTable().getRow(sqlRowAccessor.getID()));
458
                sheet.createDocumentAsynchronous();
459
                sheet.showPrintAndExportAsynchronous(false, false, true);
460
            }
461
        }
462
    }
463
 
73 ilm 464
    private void createDocument(ActionEvent ev) {
80 ilm 465
        final AbstractSheetXml sheet = createAbstractSheet(IListe.get(ev).fetchSelectedRow());
73 ilm 466
        if (sheet.getGeneratedFile().exists()) {
467
            int a = JOptionPane.showConfirmDialog(null, "Voulez vous remplacer le document existant?", "Génération de documents", JOptionPane.YES_NO_OPTION);
468
            if (a == JOptionPane.YES_OPTION) {
469
                sheet.createDocumentAsynchronous();
470
                sheet.showPrintAndExportAsynchronous(true, false, true);
471
                return;
472
            }
473
        }
474
 
475
        try {
476
            sheet.getOrCreateDocumentFile();
477
            sheet.showPrintAndExportAsynchronous(true, false, false);
478
        } catch (Exception exn) {
479
            exn.printStackTrace();
480
        }
481
 
482
    }
483
 
65 ilm 484
    /**
485
     * Action sur le double clic
486
     *
487
     * @return
488
     */
489
    public RowAction getDefaultRowAction() {
67 ilm 490
        return new RowAction(new AbstractAction() {
65 ilm 491
            public void actionPerformed(ActionEvent ev) {
80 ilm 492
                final AbstractSheetXml sheet = createAbstractSheet(IListe.get(ev).fetchSelectedRow().asRow());
65 ilm 493
                try {
494
                    sheet.getOrCreateDocumentFile();
495
                    sheet.showPrintAndExportAsynchronous(true, false, true);
496
                } catch (Exception exn) {
497
                    ExceptionHandler.handle("Une erreur est survenue lors de la création du document.", exn);
498
                }
499
            }
67 ilm 500
        }, false, false, "document.create") {
142 ilm 501
 
65 ilm 502
            @Override
93 ilm 503
            public boolean enabledFor(List<SQLRowValues> selection) {
65 ilm 504
                return selection != null && selection.size() == 1;
505
            }
506
 
507
            @Override
508
            public Action getDefaultAction(final IListeEvent evt) {
509
                return this.getAction();
510
            }
511
        };
512
    }
174 ilm 513
 
514
    private void sendMail(ActionEvent ev, boolean pdf) {
515
        final List<SQLRowValues> selectedRows = IListe.get(ev).getSelectedRows();
516
        final SQLTable table = IListe.get(ev).getSource().getPrimaryTable();
517
        final List<SQLRow> rows = new ArrayList<>();
518
        for (SQLRowValues r : selectedRows) {
519
            rows.add(table.getRow(r.getID()));
520
        }
521
 
522
        EmailTemplate.askTemplate(IListe.get(ev), table.getDBRoot(), new ValueListener() {
523
 
524
            @Override
525
            public void valueSelected(Object value) {
526
                sendMail((EmailTemplate) value, createAbstractSheets(rows), pdf);
527
            }
528
        });
529
    }
18 ilm 530
}