OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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