OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 93 | 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.generationDoc;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.config.Gestion;
18
import org.openconcerto.erp.preferences.PrinterNXProps;
19
import org.openconcerto.erp.preferences.TemplateNXProps;
20
import org.openconcerto.odtemplate.Template;
21
import org.openconcerto.odtemplate.engine.OGNLDataModel;
73 ilm 22
import org.openconcerto.openoffice.ODSingleXMLDocument;
18 ilm 23
import org.jopendocument.link.Component;
24
import org.jopendocument.link.OOConnexion;
57 ilm 25
import org.openconcerto.sql.Configuration;
18 ilm 26
import org.openconcerto.sql.model.SQLRow;
27
import org.openconcerto.utils.ExceptionHandler;
28
import org.openconcerto.utils.FileUtils;
29
 
30
import java.io.BufferedInputStream;
31
import java.io.File;
32
import java.io.FileNotFoundException;
33
import java.io.IOException;
34
import java.io.InputStream;
35
import java.text.DateFormat;
36
import java.text.SimpleDateFormat;
37
import java.util.HashMap;
38
import java.util.Map;
39
 
83 ilm 40
import javax.swing.JFrame;
18 ilm 41
import javax.swing.JOptionPane;
42
 
43
public abstract class AbstractJOOReportsSheet {
44
    private static final String defaultLocationTemplate = SpreadSheetGenerator.defaultLocationTemplate;
93 ilm 45
    protected final DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
46
    protected final DateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yy");
47
    protected final DateFormat yearFormat = new SimpleDateFormat("yyyy");
18 ilm 48
    private String year;
49
    protected String locationTemplate = TemplateNXProps.getInstance().getStringProperty("LocationTemplate");
25 ilm 50
    protected String templateId;
18 ilm 51
    private String printer;
52
    protected boolean askOverwriting = false;
53
 
54
    /**
55
     * @return une Map contenant les valeurs à remplacer dans la template
56
     */
57
    abstract protected Map createMap();
58
 
65 ilm 59
    abstract protected String getName();
18 ilm 60
 
65 ilm 61
    public String getFileName() {
62
        return getValidFileName(getName());
63
    }
64
 
73 ilm 65
    MetaDataSheet meta;
66
 
65 ilm 67
    /**
73 ilm 68
     * MetaData à inclure lors de la génération
69
     *
70
     * @param meta
71
     */
72
    public void setMetaGeneration(MetaDataSheet meta) {
73
        this.meta = meta;
74
    }
75
 
76
    /**
77
     * MetaData à inclure lors de la génération
78
     *
79
     * @param meta
80
     */
81
 
82
    public MetaDataSheet getMetaGeneration() {
83
        return this.meta;
84
    }
85
 
86
    /**
65 ilm 87
     * Remplace tous les caracteres non alphanumeriques (seul le _ est autorisé) par un -. Cela
88
     * permet d'avoir toujours un nom de fichier valide.
89
     *
90
     * @param fileName nom du fichier à créer ex:FACTURE_2007/03/001
91
     * @return un nom fichier valide ex:FACTURE_2007-03-001
92
     */
93
    static String getValidFileName(String fileName) {
94
        final StringBuffer result = new StringBuffer(fileName.length());
95
        for (int i = 0; i < fileName.length(); i++) {
96
            char ch = fileName.charAt(i);
97
 
98
            // Si c'est un caractere alphanumerique
99
            if (Character.isLetterOrDigit(ch) || (ch == '_') || (ch == ' ')) {
100
                result.append(ch);
101
            } else {
102
                result.append('-');
103
            }
104
        }
105
        return result.toString();
106
    }
107
 
67 ilm 108
    public abstract String getDefaultTemplateID();
109
 
110
    public abstract String getDefaultLocationProperty();
111
 
25 ilm 112
    protected void init(String year, String templateId, String attributePrinter) {
18 ilm 113
        this.year = year;
25 ilm 114
        this.templateId = templateId;
18 ilm 115
        this.printer = PrinterNXProps.getInstance().getStringProperty(attributePrinter);
116
    }
117
 
118
    public final void generate(boolean print, boolean show, String printer) {
119
        generate(print, show, printer, false);
120
    }
121
 
122
    /**
123
     * Genere le document OO, le pdf, et ouvre le document OO
124
     *
125
     * @param print
126
     * @param show
127
     * @param printer
128
     */
129
    public void generate(boolean print, boolean show, String printer, boolean overwrite) {
130
 
131
        if (this.locationTemplate.trim().length() == 0) {
132
            this.locationTemplate = defaultLocationTemplate;
133
        }
134
        try {
135
 
136
            String fileName = getFileName();
25 ilm 137
            final InputStream fileTemplate = TemplateManager.getInstance().getTemplate(this.templateId);
67 ilm 138
            File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(getDefaultTemplateID());
25 ilm 139
            File fileOutOO = getDocumentFile();
18 ilm 140
            if (fileOutOO.exists() && overwrite) {
141
                if (this.askOverwriting) {
142
                    int answer = JOptionPane.showConfirmDialog(null, "Voulez vous écraser le document ?", "Remplacement d'un document", JOptionPane.YES_NO_OPTION);
143
                    if (answer == JOptionPane.YES_OPTION) {
57 ilm 144
                        SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, outputDir, fileOutOO, ".odt");
18 ilm 145
                    }
146
                } else {
57 ilm 147
                    SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, outputDir, fileOutOO, ".odt");
18 ilm 148
                }
149
            }
150
 
151
            if (!fileOutOO.exists()) {
152
                fileOutOO.getParentFile().mkdirs();
25 ilm 153
                Template template = new Template(new BufferedInputStream(fileTemplate));
18 ilm 154
 
155
                // creation du document
156
                final Map createMap = createMap();
157
                OGNLDataModel model = new OGNLDataModel(createMap);
158
 
159
                model.putAll(createMap);
25 ilm 160
 
73 ilm 161
                final ODSingleXMLDocument createDocument = template.createDocument(model);
162
                if (this.meta != null) {
163
                    this.meta.applyTo(createDocument.getPackage().getMeta(true));
164
                }
165
                createDocument.saveToPackageAs(fileOutOO);
166
 
18 ilm 167
            }
168
 
169
            // ouverture de OO
170
            if (show || print) {
171
 
172
                try {
173
                    final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
174
                    if (ooConnexion == null) {
175
                        return;
176
                    }
144 ilm 177
                    final Component doc = ooConnexion.loadDocument(fileOutOO, true);
18 ilm 178
 
25 ilm 179
                    if (this.savePDF()) {
67 ilm 180
                        File pdfOutputDir = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(getDefaultTemplateID());
25 ilm 181
                        doc.saveToPDF(new File(pdfOutputDir, fileName + ".pdf"), "writer_pdf_Export");
182
                    }
18 ilm 183
                    if (print) {
184
                        Map<String, Object> map = new HashMap<String, Object>();
185
                        map.put("Name", printer);
186
                        doc.printDocument(map);
187
                    }
73 ilm 188
                    if (!show) {
189
                        doc.close();
190
                    }
18 ilm 191
 
192
                } catch (Exception e) {
193
                    e.printStackTrace();
144 ilm 194
                    ExceptionHandler.handle("Impossible de créer le document PDF", e);
18 ilm 195
                }
144 ilm 196
                if (show) {
197
                    FileUtils.openFile(fileOutOO);
198
                }
18 ilm 199
            }
200
        } catch (FileNotFoundException e) {
201
            e.printStackTrace();
202
            ExceptionHandler.handle("Impossible de trouver le modéle.", e);
203
        } catch (IOException e) {
204
            e.printStackTrace();
205
        } catch (org.openconcerto.odtemplate.TemplateException e) {
206
            e.printStackTrace();
207
        }
208
    }
209
 
210
    protected boolean savePDF() {
211
        return false;
212
    }
213
 
214
    public void showDocument() {
25 ilm 215
        File fileOutOO = getDocumentFile();
18 ilm 216
        if (fileOutOO.exists()) {
217
            try {
218
                final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
219
                if (ooConnexion == null) {
220
                    return;
221
                }
222
                ooConnexion.loadDocument(fileOutOO, false);
83 ilm 223
            } catch (LinkageError e) {
224
                JOptionPane.showMessageDialog(new JFrame(), "Merci d'installer OpenOffice ou LibreOffice");
18 ilm 225
            } catch (Exception e) {
226
                e.printStackTrace();
227
                ExceptionHandler.handle("Impossible de charger le document OpenOffice", e);
228
            }
229
        } else {
230
            generate(false, true, "");
231
        }
232
    }
233
 
25 ilm 234
    private File getDocumentFile() {
67 ilm 235
        File outputDir = DocumentLocalStorageManager.getInstance().getDocumentOutputDirectory(getDefaultTemplateID());
25 ilm 236
        return new File(outputDir, getFileName() + ".odt");
237
    }
238
 
18 ilm 239
    public void printDocument() {
25 ilm 240
        File fileOutOO = getDocumentFile();
18 ilm 241
        if (fileOutOO.exists()) {
242
            try {
243
                final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
244
                if (ooConnexion == null) {
245
                    return;
246
                }
247
                final Component doc = ooConnexion.loadDocument(fileOutOO, true);
248
                Map<String, Object> map = new HashMap<String, Object>();
249
                map.put("Name", printer);
250
                doc.printDocument(map);
251
                doc.close();
83 ilm 252
            } catch (LinkageError e) {
253
                JOptionPane.showMessageDialog(new JFrame(), "Merci d'installer OpenOffice ou LibreOffice");
18 ilm 254
            } catch (Exception e) {
255
                e.printStackTrace();
256
                ExceptionHandler.handle("Impossible de charger le document OpenOffice", e);
257
            }
258
        } else {
259
            generate(true, false, this.printer);
260
        }
261
    }
262
 
263
    public void fastPrintDocument() {
25 ilm 264
        final File f = getDocumentFile();
18 ilm 265
        if (!f.exists()) {
266
            generate(true, false, this.printer);
267
        } else {
268
            try {
269
                final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
270
                if (ooConnexion == null) {
271
                    return;
272
                }
273
                final Component doc = ooConnexion.loadDocument(f, true);
274
                Map<String, Object> map = new HashMap<String, Object>();
275
                map.put("Name", this.printer);
276
                Map<String, Object> map2 = new HashMap<String, Object>();
277
                map2.put("CopyCount", 1);
278
                doc.printDocument(map, map2);
279
                doc.close();
83 ilm 280
            } catch (LinkageError e) {
281
                JOptionPane.showMessageDialog(new JFrame(), "Merci d'installer OpenOffice ou LibreOffice");
18 ilm 282
            } catch (Exception e) {
283
 
284
                ExceptionHandler.handle("Impossible de charger le document OpentOffice", e);
285
                e.printStackTrace();
286
            }
287
        }
288
    }
289
 
290
    protected String getInitiales(SQLRow row) {
291
        String init = "";
292
        if (row != null) {
293
            final String stringPrenom = row.getString("PRENOM");
294
            if (stringPrenom != null && stringPrenom.trim().length() != 0) {
295
                init += stringPrenom.trim().charAt(0);
296
            }
297
            final String stringNom = row.getString("NOM");
298
            if (stringNom != null && stringNom.trim().length() != 0) {
299
                init += stringNom.trim().charAt(0);
300
            }
301
        }
302
        return init;
303
    }
304
 
305
    public void exportToPdf() {
306
        // Export vers PDF
25 ilm 307
        final String fileName = getFileName();
308
        final File fileOutOO = getDocumentFile();
309
        final File outputPDFDirectory = DocumentLocalStorageManager.getInstance().getPDFOutputDirectory(this.templateId);
310
        final File fileOutPDF = new File(outputPDFDirectory, fileName + ".pdf");
18 ilm 311
 
312
        if (!fileOutOO.exists()) {
313
            generate(false, false, "");
314
        }
315
        try {
316
            final OOConnexion ooConnexion = ComptaPropsConfiguration.getOOConnexion();
317
            if (ooConnexion == null) {
318
                return;
319
            }
320
            final Component doc = ooConnexion.loadDocument(fileOutOO, true);
321
            doc.saveToPDF(fileOutPDF, "writer_pdf_Export");
322
            doc.close();
83 ilm 323
        } catch (LinkageError e) {
324
            JOptionPane.showMessageDialog(new JFrame(), "Merci d'installer OpenOffice ou LibreOffice");
18 ilm 325
        } catch (Exception e) {
326
            e.printStackTrace();
327
            ExceptionHandler.handle("Impossible de charger le document OpenOffice", e);
328
        }
329
        // Ouverture
330
        int result = JOptionPane.showOptionDialog(null, "Ouvrir le pdf ?", "Ouverture du PDF", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
331
 
332
        if (result == JOptionPane.YES_OPTION) {
25 ilm 333
            Gestion.openPDF(fileOutPDF);
18 ilm 334
        } else {
335
            try {
336
                FileUtils.openFile(fileOutPDF.getParentFile());
337
            } catch (IOException e) {
338
                // TODO Auto-generated catch block
339
                e.printStackTrace();
340
                JOptionPane.showMessageDialog(null, "Impossible d'ouvrir le dossier : " + fileOutPDF.getParentFile() + ".");
341
            }
342
        }
343
 
344
    }
345
 
93 ilm 346
    public String getYear() {
347
        return year;
348
    }
18 ilm 349
}