OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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