OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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