OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 182 | 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.generationDoc;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.ui.PreviewFrame;
182 ilm 18
import org.openconcerto.erp.core.customerrelationship.mail.EmailTemplate;
19
import org.openconcerto.erp.core.customerrelationship.mail.ValueListener;
156 ilm 20
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
21
import org.openconcerto.erp.core.sales.quote.report.PaypalStamper;
21 ilm 22
import org.openconcerto.erp.generationDoc.element.TypeModeleSQLElement;
182 ilm 23
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
156 ilm 24
import org.openconcerto.erp.preferences.PayPalPreferencePanel;
61 ilm 25
import org.openconcerto.erp.storage.CloudStorageEngine;
25 ilm 26
import org.openconcerto.erp.storage.StorageEngine;
27
import org.openconcerto.erp.storage.StorageEngines;
19 ilm 28
import org.openconcerto.openoffice.OOUtils;
18 ilm 29
import org.jopendocument.link.Component;
30
import org.openconcerto.sql.Configuration;
182 ilm 31
import org.openconcerto.sql.element.SQLComponent;
18 ilm 32
import org.openconcerto.sql.element.SQLElement;
33
import org.openconcerto.sql.model.SQLBase;
34
import org.openconcerto.sql.model.SQLRow;
144 ilm 35
import org.openconcerto.sql.model.SQLRowAccessor;
182 ilm 36
import org.openconcerto.sql.model.SQLTable;
156 ilm 37
import org.openconcerto.sql.preferences.SQLPreferences;
182 ilm 38
import org.openconcerto.sql.view.EditFrame;
39
import org.openconcerto.sql.view.EditPanel.EditMode;
40
import org.openconcerto.ui.FrameUtil;
41
import org.openconcerto.utils.Action;
18 ilm 42
import org.openconcerto.utils.ExceptionHandler;
144 ilm 43
import org.openconcerto.utils.cc.ITransformer;
182 ilm 44
import org.openconcerto.utils.i18n.Grammar;
45
import org.openconcerto.utils.i18n.TranslationManager;
18 ilm 46
 
156 ilm 47
import java.awt.GraphicsEnvironment;
132 ilm 48
import java.awt.print.PrinterJob;
25 ilm 49
import java.io.BufferedInputStream;
18 ilm 50
import java.io.File;
25 ilm 51
import java.io.FileInputStream;
156 ilm 52
import java.io.FileNotFoundException;
19 ilm 53
import java.io.IOException;
156 ilm 54
import java.io.InputStream;
55
import java.io.InputStreamReader;
56
import java.io.OutputStream;
18 ilm 57
import java.lang.Thread.UncaughtExceptionHandler;
156 ilm 58
import java.net.HttpURLConnection;
59
import java.net.URL;
60
import java.net.URLConnection;
61
import java.net.URLEncoder;
62
import java.nio.charset.StandardCharsets;
182 ilm 63
import java.util.ArrayList;
132 ilm 64
import java.util.Arrays;
182 ilm 65
import java.util.Collections;
18 ilm 66
import java.util.HashMap;
25 ilm 67
import java.util.List;
18 ilm 68
import java.util.Map;
156 ilm 69
import java.util.StringJoiner;
25 ilm 70
import java.util.concurrent.Callable;
71
import java.util.concurrent.ExecutionException;
18 ilm 72
import java.util.concurrent.ExecutorService;
73
import java.util.concurrent.Future;
74
import java.util.concurrent.LinkedBlockingQueue;
132 ilm 75
import java.util.concurrent.ThreadFactory;
18 ilm 76
import java.util.concurrent.ThreadPoolExecutor;
77
import java.util.concurrent.TimeUnit;
78
 
132 ilm 79
import javax.swing.JOptionPane;
18 ilm 80
 
81
import org.jopendocument.model.OpenDocument;
82
 
83
public abstract class SheetXml {
84
 
144 ilm 85
    private ITransformer<List<SQLRowAccessor>, List<SQLRowAccessor>> postProcess = null;
86
 
87
    public ITransformer<List<SQLRowAccessor>, List<SQLRowAccessor>> getPostProcess() {
88
        return postProcess;
89
    }
90
 
93 ilm 91
    // INSTEAD USE THE PREF IN L.O. CALC --> Formules, toujours recalculer
92
    private boolean refreshFormulasRequired = false;
93
 
25 ilm 94
    // return null to keep default value
95
    public interface StorageDirs {
96
        public File getDocumentOutputDirectory(SheetXml sheet);
97
 
98
        public File getPDFOutputDirectory(SheetXml sheet);
99
 
100
        public String getStoragePath(SheetXml sheet);
101
    }
102
 
144 ilm 103
    /**
104
     * Post process line
105
     *
106
     * @param postProcess
107
     */
108
    public void setPostProcess(ITransformer<List<SQLRowAccessor>, List<SQLRowAccessor>> postProcess) {
109
        this.postProcess = postProcess;
110
    }
111
 
25 ilm 112
    private static StorageDirs STORAGE_DIRS;
113
 
114
    // allow to redirect all documents
115
    public static void setStorageDirs(StorageDirs d) {
116
        STORAGE_DIRS = d;
117
    }
118
 
119
    public static final String DEFAULT_PROPERTY_NAME = "Default";
18 ilm 120
    protected SQLElement elt;
121
 
122
    // nom de l'imprimante à utiliser
123
    protected String printer;
124
 
125
    // id
126
    protected SQLRow row;
127
 
19 ilm 128
    // Language du document
129
    protected SQLRow rowLanguage;
130
 
18 ilm 131
    protected static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
132
 
133
    // single threaded and kill its thread after 3 seconds (to allow the program to exit)
132 ilm 134
    protected static final ExecutorService runnableQueue = new ThreadPoolExecutor(0, 1, 3L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
18 ilm 135
 
132 ilm 136
        @Override
137
        public Thread newThread(Runnable r) {
138
            final Thread res = new Thread(r);
139
            res.setUncaughtExceptionHandler(DEFAULT_HANDLER);
140
 
141
            return res;
142
        }
143
    });
144
 
18 ilm 145
    protected static UncaughtExceptionHandler DEFAULT_HANDLER = new UncaughtExceptionHandler() {
146
        @Override
147
        public void uncaughtException(Thread t, Throwable e) {
19 ilm 148
            ExceptionHandler.handle("Erreur de generation", e);
18 ilm 149
        }
150
    };
151
 
25 ilm 152
    public final SQLElement getElement() {
153
        return this.elt;
18 ilm 154
    }
155
 
182 ilm 156
    public Future<SheetXml> showPrintAndExportAsynchronous(final boolean showDocument, final boolean printDocument, final boolean exportToPDF) {
157
        return showPrintAndExportAsynchronous(showDocument, printDocument, exportToPDF, Collections.emptyList());
158
    }
159
 
25 ilm 160
    /**
161
     * Show, print and export the document to PDF. This method is asynchronous, but is executed in a
162
     * single threaded queue shared with createDocument
132 ilm 163
     */
182 ilm 164
    public Future<SheetXml> showPrintAndExportAsynchronous(final boolean showDocument, final boolean printDocument, final boolean exportToPDF, List<Action> actions) {
25 ilm 165
        final Callable<SheetXml> c = new Callable<SheetXml>() {
166
            @Override
167
            public SheetXml call() throws Exception {
182 ilm 168
                showPrintAndExport(showDocument, printDocument, exportToPDF, actions);
25 ilm 169
                return SheetXml.this;
170
            }
171
        };
172
        return runnableQueue.submit(c);
18 ilm 173
 
25 ilm 174
    }
175
 
182 ilm 176
    public Future<SheetXml> showPrintAndExportAsynchronous(final boolean showDocument, final boolean printDocument, final boolean exportToPDF, final SQLElement element, SQLRow row) {
177
        final Callable<SheetXml> c = new Callable<SheetXml>() {
178
 
179
            @Override
180
            public SheetXml call() throws Exception {
181
                final List<Action> actions = new ArrayList<>();
182
                if (SheetXml.this instanceof AbstractSheetXml) {
183
                    final SQLTable table = element.getTable();
184
                    final Action emailAction = new Action(TranslationManager.getInstance().getTranslationForAction("document.pdf.send.email")) {
185
 
186
                        @Override
187
                        public void run(Object source) {
185 ilm 188
                            EmailTemplate.askTemplate(null, table.getDBRoot(), table.getName(), new ValueListener() {
182 ilm 189
 
190
                                @Override
191
                                public void valueSelected(Object value) {
192
                                    final MouseSheetXmlListeListener l = new MouseSheetXmlListeListener(element, ((AbstractSheetXml) SheetXml.this).getClass());
193
                                    l.sendMail((EmailTemplate) value, (AbstractSheetXml) SheetXml.this, true);
194
                                }
195
                            });
196
 
197
                        }
198
                    };
199
                    actions.add(emailAction);
200
                }
201
                final Action modifyAction = new Action(TranslationManager.getInstance().getTranslationForAction("modify") + " " + element.getName().getVariant(Grammar.DEFINITE_ARTICLE_SINGULAR)) {
202
 
203
                    @Override
204
                    public void run(Object source) {
205
                        if (source instanceof PreviewFrame) {
206
                            ((PreviewFrame) source).dispose();
207
                        }
208
 
209
                        final SQLComponent component = element.createDefaultComponent();
210
                        final EditFrame f = new EditFrame(component, EditMode.MODIFICATION);
211
                        f.selectionId(row.getID());
212
                        FrameUtil.show(f);
213
 
214
                    }
215
                };
216
                actions.add(modifyAction);
217
                showPrintAndExport(showDocument, printDocument, exportToPDF, actions);
218
                return SheetXml.this;
219
            }
220
        };
221
        return runnableQueue.submit(c);
222
 
223
    }
224
 
132 ilm 225
    public static Future<?> submitInQueue(final Runnable r) {
226
 
227
        return runnableQueue.submit(r);
94 ilm 228
    }
229
 
61 ilm 230
    public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF) {
182 ilm 231
        showPrintAndExport(showDocument, printDocument, exportToPDF, Boolean.getBoolean("org.openconcerto.oo.useODSViewer"), false, Collections.emptyList());
61 ilm 232
    }
233
 
182 ilm 234
    public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF, List<Action> actions) {
235
        showPrintAndExport(showDocument, printDocument, exportToPDF, Boolean.getBoolean("org.openconcerto.oo.useODSViewer"), false, actions);
236
    }
237
 
238
    public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF, boolean useODSViewer, boolean exportPDFSynch) {
239
        showPrintAndExport(showDocument, printDocument, exportToPDF, useODSViewer, exportPDFSynch, Collections.emptyList());
240
    }
241
 
25 ilm 242
    /**
243
     * Show, print and export the document to PDF. This method is synchronous
132 ilm 244
     */
182 ilm 245
    public void showPrintAndExport(final boolean showDocument, final boolean printDocument, boolean exportToPDF, boolean useODSViewer, boolean exportPDFSynch, List<Action> actions) {
25 ilm 246
 
247
        final File generatedFile = getGeneratedFile();
248
        final File pdfFile = getGeneratedPDFFile();
249
        if (generatedFile == null || !generatedFile.exists()) {
132 ilm 250
            JOptionPane.showMessageDialog(null, "Fichier généré manquant : " + generatedFile);
18 ilm 251
            return;
252
        }
253
 
254
        try {
61 ilm 255
            if (!useODSViewer) {
174 ilm 256
                if (exportToPDF || printDocument) {
257
                    final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(generatedFile, !showDocument);
18 ilm 258
 
174 ilm 259
                    if (printDocument) {
260
                        Map<String, Object> map = new HashMap<String, Object>();
261
                        map.put("Name", this.printer);
262
                        doc.printDocument(map);
263
                    }
264
                    if (exportToPDF) {
265
                        doc.saveToPDF(pdfFile).get();
266
                    }
267
                    if (!showDocument) {
268
                        doc.close();
269
                    }
270
                } else {
271
                    openDocument(false);
18 ilm 272
                }
273
            } else {
25 ilm 274
                final OpenDocument doc = new OpenDocument(generatedFile);
18 ilm 275
 
25 ilm 276
                if (showDocument) {
182 ilm 277
                    showPreviewDocument(actions);
18 ilm 278
                }
25 ilm 279
                if (printDocument) {
18 ilm 280
                    // Print !
28 ilm 281
                    DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
132 ilm 282
                    printer.print(Arrays.asList(doc));
18 ilm 283
                }
61 ilm 284
 
285
                // FIXME Profiler pour utiliser moins de ram --> ex : demande trop de mémoire pour
286
                // faire
287
                // un grand livre KD
25 ilm 288
                if (exportToPDF) {
18 ilm 289
 
25 ilm 290
                    Thread t = new Thread(new Runnable() {
291
 
292
                        @Override
293
                        public void run() {
67 ilm 294
                            createPDF(generatedFile, pdfFile, doc, getStoragePath());
65 ilm 295
 
67 ilm 296
                        }
25 ilm 297
 
65 ilm 298
                    }, "convert and upload to pdf");
299
 
300
                    t.setDaemon(true);
25 ilm 301
                    t.start();
65 ilm 302
                    if (exportPDFSynch) {
303
                        t.join();
304
                    }
25 ilm 305
                }
18 ilm 306
            }
307
 
308
        } catch (Exception e) {
156 ilm 309
            ExceptionHandler.handle("Impossible de charger le document OpenOffice " + pdfFile.getAbsolutePath() + "(viewer : " + useODSViewer + ")", e);
18 ilm 310
        }
311
    }
312
 
73 ilm 313
    MetaDataSheet meta;
314
 
315
    /**
316
     * MetaData à inclure lors de la génération
317
     *
318
     * @param meta
319
     */
320
    public void setMetaGeneration(MetaDataSheet meta) {
321
        this.meta = meta;
322
    }
323
 
324
    /**
325
     * MetaData à inclure lors de la génération
326
     *
327
     * @param meta
328
     */
329
 
330
    public MetaDataSheet getMetaGeneration() {
331
        return this.meta;
332
    }
333
 
156 ilm 334
    public void createPDF(final File generatedFile, final File pdfFile, final OpenDocument doc, String storagePath) {
80 ilm 335
        if (pdfFile == null) {
336
            throw new IllegalArgumentException("null PDF file");
337
        }
67 ilm 338
        try {
182 ilm 339
            SheetUtils.convert2PDF(doc, pdfFile);
340
        } catch (Exception e) {
80 ilm 341
            ExceptionHandler.handle("Impossible de créer le PDF " + pdfFile.getAbsolutePath(), e);
67 ilm 342
        }
80 ilm 343
        if (!pdfFile.canRead()) {
344
            ExceptionHandler.handle("Le fichier PDF " + pdfFile.getAbsolutePath() + " ne peut être lu.");
345
        }
182 ilm 346
        storeWithStorageEngines(generatedFile, pdfFile, storagePath);
347
    }
348
 
349
    protected void storeWithStorageEngines(final File generatedFile, final File pdfFile, String storagePath) {
67 ilm 350
        List<StorageEngine> engines = StorageEngines.getInstance().getActiveEngines();
351
        for (StorageEngine storageEngine : engines) {
352
            if (storageEngine.isConfigured() && storageEngine.allowAutoStorage()) {
80 ilm 353
                final String path = storagePath;
67 ilm 354
                try {
355
                    storageEngine.connect();
356
                    final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(pdfFile));
357
                    storageEngine.store(inStream, path, pdfFile.getName(), true);
358
                    inStream.close();
359
                    storageEngine.disconnect();
360
                } catch (IOException e) {
80 ilm 361
                    ExceptionHandler.handle("Impossible de sauvegarder le PDF " + pdfFile.getAbsolutePath() + " vers " + path + "(" + storageEngine + ")", e);
67 ilm 362
                }
363
                if (storageEngine instanceof CloudStorageEngine) {
364
                    try {
365
                        storageEngine.connect();
366
                        final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(generatedFile));
367
                        storageEngine.store(inStream, path, generatedFile.getName(), true);
368
                        inStream.close();
369
                        storageEngine.disconnect();
370
                    } catch (IOException e) {
80 ilm 371
                        ExceptionHandler.handle("Impossible de sauvegarder le fichier généré " + generatedFile.getAbsolutePath() + " vers " + path + "(" + storageEngine + ")", e);
67 ilm 372
                    }
373
                }
374
            }
375
        }
376
    }
377
 
25 ilm 378
    public abstract String getDefaultTemplateId();
21 ilm 379
 
25 ilm 380
    /**
381
     * Path of the directory used for storage. Ex: Devis/2010
132 ilm 382
     */
25 ilm 383
    public final String getStoragePath() {
384
        final String res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getStoragePath(this);
385
        if (res != null)
386
            return res;
387
        else
388
            return this.getStoragePathP();
389
    }
390
 
391
    public final File getDocumentOutputDirectory() {
392
        final File res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getDocumentOutputDirectory(this);
393
        if (res != null)
394
            return res;
395
        else
396
            return this.getDocumentOutputDirectoryP();
397
    }
398
 
399
    public final File getPDFOutputDirectory() {
400
        final File res = STORAGE_DIRS == null ? null : STORAGE_DIRS.getPDFOutputDirectory(this);
401
        if (res != null)
402
            return res;
403
        else
404
            return this.getPDFOutputDirectoryP();
405
    }
406
 
407
    protected abstract String getStoragePathP();
408
 
409
    protected abstract File getDocumentOutputDirectoryP();
410
 
411
    protected abstract File getPDFOutputDirectoryP();
412
 
413
    /**
414
     * Name of the generated document (without extension), do not rely on this name.
415
     *
416
     * Use getGeneratedFile().getName() to get the generated file name.
132 ilm 417
     */
25 ilm 418
    public abstract String getName();
419
 
420
    /**
421
     * @return the template id for this template (ex: "sales.quote")
132 ilm 422
     */
25 ilm 423
    public String getTemplateId() {
424
        if (this.row != null && this.row.getTable().getFieldsName().contains("ID_MODELE")) {
151 ilm 425
            if (row.getObject("ID_MODELE") == null || row.isForeignEmpty("ID_MODELE")) {
21 ilm 426
                TypeModeleSQLElement typeModele = Configuration.getInstance().getDirectory().getElement(TypeModeleSQLElement.class);
25 ilm 427
                String modele = typeModele.getTemplateMapping().get(this.row.getTable().getName());
21 ilm 428
                if (modele == null) {
429
                    System.err.println("No default modele in table TYPE_MODELE for table " + this.row.getTable().getName());
430
                    Thread.dumpStack();
25 ilm 431
                    return getDefaultTemplateId();
21 ilm 432
                } else {
433
                    return modele;
434
                }
435
            } else {
90 ilm 436
                SQLRow rowModele = this.row.getForeignRow("ID_MODELE");
21 ilm 437
                return rowModele.getString("NOM");
438
            }
439
        }
25 ilm 440
        return getDefaultTemplateId();
21 ilm 441
    }
442
 
25 ilm 443
    public abstract Future<SheetXml> createDocumentAsynchronous();
18 ilm 444
 
25 ilm 445
    public void createDocument() throws InterruptedException, ExecutionException {
446
        createDocumentAsynchronous().get();
18 ilm 447
    }
448
 
25 ilm 449
    /**
450
     * get the File that is, or must be generated.
451
     *
452
     * @return a file (not null)
132 ilm 453
     */
25 ilm 454
    public abstract File getGeneratedFile();
18 ilm 455
 
25 ilm 456
    public File getGeneratedPDFFile() {
457
        return SheetUtils.getFileWithExtension(getGeneratedFile(), ".pdf");
18 ilm 458
    }
459
 
19 ilm 460
    public SQLRow getRowLanguage() {
461
        return this.rowLanguage;
462
    }
463
 
464
    public String getReference() {
465
        return "";
466
    }
467
 
18 ilm 468
    /**
25 ilm 469
     * Creates the document if needed and returns the generated file (OpenDocument)
132 ilm 470
     */
25 ilm 471
    public File getOrCreateDocumentFile() throws Exception {
472
        File f = getGeneratedFile();
473
        if (!f.exists()) {
474
            return createDocumentAsynchronous().get().getGeneratedFile();
18 ilm 475
        } else {
25 ilm 476
            return f;
18 ilm 477
        }
478
    }
479
 
25 ilm 480
    /**
41 ilm 481
     * Creates the document if needed and returns the generated file (OpenDocument)
482
     *
483
     * @param createRecent true for recreate the pdf document if older than ods
484
     * @return
485
     * @throws Exception
486
     *
132 ilm 487
     */
41 ilm 488
    public File getOrCreatePDFDocumentFile(boolean createRecent) throws Exception {
61 ilm 489
        return getOrCreatePDFDocumentFile(createRecent, Boolean.getBoolean("org.openconcerto.oo.useODSViewer"));
490
    }
491
 
492
    public File getOrCreatePDFDocumentFile(boolean createRecent, boolean useODSViewer) throws Exception {
41 ilm 493
        File f = getGeneratedPDFFile();
494
        if (!f.exists()) {
495
            getOrCreateDocumentFile();
182 ilm 496
            showPrintAndExport(false, false, true, useODSViewer, true, Collections.emptyList());
41 ilm 497
            return f;
498
        } else {
499
            File fODS = getOrCreateDocumentFile();
500
            if (fODS.lastModified() > f.lastModified()) {
182 ilm 501
                showPrintAndExport(false, false, true, useODSViewer, true, Collections.emptyList());
41 ilm 502
            }
503
            return f;
504
        }
505
    }
506
 
507
    /**
25 ilm 508
     * Open the document with the native application
509
     *
510
     * @param synchronous
132 ilm 511
     */
25 ilm 512
    public void openDocument(boolean synchronous) {
513
        Runnable r = new Runnable() {
514
 
515
            @Override
516
            public void run() {
517
                File f;
518
                try {
519
                    f = getOrCreateDocumentFile();
156 ilm 520
                    if (f != null && f.exists()) {
521
                        OOUtils.open(f);
522
                    } else {
523
                        if (!GraphicsEnvironment.isHeadless()) {
524
                            if (f != null) {
525
                                JOptionPane.showMessageDialog(null, "Le fichier " + f.getAbsolutePath() + " est manquant");
526
                            } else {
527
                                JOptionPane.showMessageDialog(null, "Fichier manquant");
528
                            }
529
                        } else {
530
                            if (f != null) {
531
                                throw new FileNotFoundException(f.getAbsolutePath() + " missing");
532
                            } else {
533
                                throw new NullPointerException("null document");
534
                            }
535
                        }
536
                    }
25 ilm 537
                } catch (Exception e) {
538
                    ExceptionHandler.handle("Impossible d'ouvrir le document.", e);
539
                }
18 ilm 540
            }
25 ilm 541
        };
542
        if (synchronous) {
543
            r.run();
18 ilm 544
        } else {
25 ilm 545
            Thread thread = new Thread(r, "openDocument: " + getGeneratedFile().getAbsolutePath());
546
            thread.setDaemon(true);
547
            thread.start();
18 ilm 548
        }
549
 
550
    }
551
 
25 ilm 552
    public void showPreviewDocument() throws Exception {
182 ilm 553
        showPreviewDocument(Collections.emptyList());
174 ilm 554
    }
555
 
182 ilm 556
    public void showPreviewDocument(List<Action> actions) throws Exception {
25 ilm 557
        File f = null;
558
        f = getOrCreateDocumentFile();
182 ilm 559
        PreviewFrame.show(f, actions);
18 ilm 560
    }
561
 
132 ilm 562
    public void printDocument() {
563
        printDocument(null);
18 ilm 564
    }
565
 
132 ilm 566
    public void printDocument(PrinterJob job) {
18 ilm 567
 
568
        try {
25 ilm 569
            final File f = getOrCreateDocumentFile();
570
 
18 ilm 571
            if (!Boolean.getBoolean("org.openconcerto.oo.useODSViewer")) {
572
                final Component doc = ComptaPropsConfiguration.getOOConnexion().loadDocument(f, true);
149 ilm 573
                doc.printDocument(job);
18 ilm 574
                doc.close();
575
            } else {
576
                // Load the spreadsheet.
577
                final OpenDocument doc = new OpenDocument(f);
578
                // Print !
579
                DefaultNXDocumentPrinter printer = new DefaultNXDocumentPrinter();
132 ilm 580
                printer.print(Arrays.asList(doc), job);
18 ilm 581
            }
582
 
583
        } catch (Exception e) {
132 ilm 584
            ExceptionHandler.handle("Impossible d'imprimer le document OpenOffice", e);
18 ilm 585
            e.printStackTrace();
586
        }
587
    }
588
 
589
    public SQLRow getSQLRow() {
590
        return this.row;
591
    }
592
 
593
    /**
594
     * Remplace tous les caracteres non alphanumeriques (seul le _ est autorisé) par un -. Cela
595
     * permet d'avoir toujours un nom de fichier valide.
596
     *
597
     * @param fileName nom du fichier à créer ex:FACTURE_2007/03/001
598
     * @return un nom fichier valide ex:FACTURE_2007-03-001
599
     */
83 ilm 600
    public static String getValidFileName(String fileName) {
25 ilm 601
        final StringBuffer result = new StringBuffer(fileName.length());
18 ilm 602
        for (int i = 0; i < fileName.length(); i++) {
25 ilm 603
            char ch = fileName.charAt(i);
18 ilm 604
 
605
            // Si c'est un caractere alphanumerique
25 ilm 606
            if (Character.isLetterOrDigit(ch) || (ch == '_') || (ch == ' ')) {
607
                result.append(ch);
18 ilm 608
            } else {
609
                result.append('-');
610
            }
611
        }
612
        return result.toString();
613
    }
614
 
615
    public String getPrinter() {
616
        return this.printer;
617
    }
618
 
93 ilm 619
    public void setRefreshFormulasRequired(boolean refreshFormulasRequired) {
620
        this.refreshFormulasRequired = refreshFormulasRequired;
621
    }
622
 
623
    public boolean isRefreshFormulasRequired() {
624
            return refreshFormulasRequired;
625
    }
626
 
18 ilm 627
}