OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Rev 180 | 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;
83 ilm 17
import org.openconcerto.erp.config.Log;
18 ilm 18
import org.openconcerto.erp.core.common.element.StyleSQLElement;
142 ilm 19
import org.openconcerto.erp.core.common.ui.TotalCalculator;
20
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
21
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
22
import org.openconcerto.erp.preferences.DefaultNXProps;
18 ilm 23
import org.openconcerto.openoffice.ODPackage;
24
import org.openconcerto.openoffice.spreadsheet.MutableCell;
25
import org.openconcerto.openoffice.spreadsheet.Sheet;
26
import org.openconcerto.openoffice.spreadsheet.SpreadSheet;
27
import org.openconcerto.sql.Configuration;
28
import org.openconcerto.sql.element.SQLElement;
144 ilm 29
import org.openconcerto.sql.model.SQLBackgroundTableCache;
30
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
18 ilm 31
import org.openconcerto.sql.model.SQLField;
32
import org.openconcerto.sql.model.SQLRow;
33
import org.openconcerto.sql.model.SQLRowAccessor;
142 ilm 34
import org.openconcerto.sql.model.SQLRowValues;
18 ilm 35
import org.openconcerto.sql.model.SQLTable;
36
import org.openconcerto.utils.ExceptionHandler;
37
import org.openconcerto.utils.StreamUtils;
142 ilm 38
import org.openconcerto.utils.Tuple2;
144 ilm 39
import org.openconcerto.utils.cc.ITransformer;
156 ilm 40
import org.openconcerto.utils.io.BOMSkipper;
18 ilm 41
 
42
import java.awt.Point;
156 ilm 43
import java.io.BufferedReader;
18 ilm 44
import java.io.File;
45
import java.io.FileNotFoundException;
46
import java.io.IOException;
47
import java.io.InputStream;
156 ilm 48
import java.io.InputStreamReader;
18 ilm 49
import java.lang.reflect.InvocationTargetException;
67 ilm 50
import java.math.BigDecimal;
142 ilm 51
import java.math.RoundingMode;
156 ilm 52
import java.nio.charset.Charset;
18 ilm 53
import java.text.DateFormat;
54
import java.text.SimpleDateFormat;
55
import java.util.Collection;
56
import java.util.HashMap;
57
import java.util.List;
58
import java.util.Map;
59
 
60
import javax.swing.JOptionPane;
61
import javax.swing.SwingUtilities;
62
 
132 ilm 63
import org.jdom2.Document;
64
import org.jdom2.Element;
65
import org.jdom2.JDOMException;
66
import org.jdom2.input.SAXBuilder;
18 ilm 67
 
68
/**
69
 * Génération d'un document sxc à partir d'un modéle sxc et d'un fichier xml du meme nom (doc.sxc et
70
 * doc.xml) <element location="D4" (type="fill" || type="replace" replacePattern="_" ||
132 ilm 71
 * type="codesMissions" ||type="DescriptifArticle" || type="DateEcheance">
72
 * <field base="Societe" table="AFFAIRE" name="NUMERO"/> </element>
18 ilm 73
 *
74
 *
75
 * @author Administrateur
76
 *
77
 */
78
public class OOgenerationXML {
63 ilm 79
    private static int answer = JOptionPane.NO_OPTION;
18 ilm 80
 
63 ilm 81
    private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
18 ilm 82
 
83
    // Cache pour la recherche des styles
156 ilm 84
    private Map<Sheet, Map<String, Map<Integer, String>>> cacheStyle = new HashMap<>();
85
    private Map<SQLRowAccessor, Map<String, Object>> taxe = new HashMap<>();
86
    private Map<String, Map<Integer, SQLRowAccessor>> cacheForeign = new HashMap<>();
18 ilm 87
 
88
    // Cache pour les SQLRow du tableau
156 ilm 89
    private Map<String, List<? extends SQLRowAccessor>> rowsEltCache = new HashMap<>();
63 ilm 90
    private final OOXMLCache rowRefCache = new OOXMLCache();
91
    private final SQLRow row;
18 ilm 92
 
63 ilm 93
    public OOgenerationXML(SQLRow row) {
94
        this.row = row;
95
    }
18 ilm 96
 
144 ilm 97
    public void setPostProcess(ITransformer<List<SQLRowAccessor>, List<SQLRowAccessor>> postProcess) {
98
        this.rowRefCache.setPostProcess(postProcess);
99
    }
100
 
65 ilm 101
    public synchronized File createDocument(String templateId, String typeTemplate, File outputDirectory, final String expectedFileName, SQLRow rowLanguage) {
73 ilm 102
        return createDocument(templateId, typeTemplate, outputDirectory, expectedFileName, rowLanguage, null);
103
    }
104
 
105
    public synchronized File createDocument(String templateId, String typeTemplate, File outputDirectory, final String expectedFileName, SQLRow rowLanguage, MetaDataSheet meta) {
25 ilm 106
        final String langage = rowLanguage != null ? rowLanguage.getString("CHEMIN") : null;
65 ilm 107
 
18 ilm 108
        cacheStyle.clear();
63 ilm 109
        rowRefCache.clearCache();
18 ilm 110
        rowsEltCache.clear();
111
        taxe.clear();
112
        cacheForeign.clear();
113
 
25 ilm 114
        File fDest = new File(outputDirectory, expectedFileName);
18 ilm 115
 
116
        if (fDest.exists()) {
117
 
118
            if (SwingUtilities.isEventDispatchThread()) {
119
                answer = JOptionPane.showConfirmDialog(null, "Voulez vous regénérer et écraser l'ancien document?", "Génération du document", JOptionPane.YES_NO_OPTION);
120
                Thread.dumpStack();
121
            } else {
122
                try {
123
                    SwingUtilities.invokeAndWait(new Runnable() {
124
                        @Override
125
                        public void run() {
126
 
127
                            answer = JOptionPane.showConfirmDialog(null, "Voulez vous regénérer et écraser l'ancien document?", "Génération du document", JOptionPane.YES_NO_OPTION);
128
                        }
129
                    });
130
                } catch (InterruptedException e) {
131
                    e.printStackTrace();
132
                } catch (InvocationTargetException e) {
133
                    e.printStackTrace();
134
                }
135
            }
136
            if (answer != JOptionPane.YES_OPTION) {
137
                return fDest;
138
            }
139
        }
140
 
141
        SAXBuilder builder = new SAXBuilder();
142
        try {
143
 
65 ilm 144
            if (needAnnexe(templateId, typeTemplate, row, rowLanguage)) {
25 ilm 145
                // check if it exists
146
                final String annexeTemplateId = templateId + "_annexe";
65 ilm 147
                InputStream annexeStream = TemplateManager.getInstance().getTemplate(annexeTemplateId, langage, typeTemplate);
25 ilm 148
                if (annexeStream != null) {
149
                    templateId = annexeTemplateId;
94 ilm 150
                    annexeStream.close();
132 ilm 151
                    System.err.println("OOgenerationXML.createDocument() : modele With annexe " + templateId);
18 ilm 152
                }
153
            }
154
 
132 ilm 155
            System.err.println("OOgenerationXML.createDocument() : using template id : " + templateId);
65 ilm 156
            final InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, langage, typeTemplate);
132 ilm 157
            if (xmlConfiguration == null) {
158
                JOptionPane.showMessageDialog(null, "Fichier de configuration manquant pour " + templateId + " " + ((rowLanguage == null) ? "" : rowLanguage.getString("CHEMIN")) + " "
159
                        + ((typeTemplate == null) ? "" : typeTemplate));
160
                return null;
161
            }
156 ilm 162
 
163
            final BufferedReader xmlConfigurationReader = new BufferedReader(new InputStreamReader(xmlConfiguration, Charset.forName("UTF8")));
164
            BOMSkipper.skip(xmlConfigurationReader);
165
            final Document doc = builder.build(xmlConfigurationReader);
166
            xmlConfigurationReader.close();
94 ilm 167
            xmlConfiguration.close();
18 ilm 168
 
169
            // On initialise un nouvel élément racine avec l'élément racine du document.
170
            Element racine = doc.getRootElement();
171
 
172
            // Liste des <element>
173
            List<Element> listElts = racine.getChildren("element");
174
 
175
            // Création et génération du fichier OO
83 ilm 176
            final InputStream templateStream = TemplateManager.getInstance().getTemplate(templateId, langage, typeTemplate);
177
            if (templateStream == null) {
132 ilm 178
                JOptionPane.showMessageDialog(null,
179
                        "Modèle manquant pour " + templateId + " " + ((rowLanguage == null) ? "" : rowLanguage.getString("CHEMIN")) + " " + ((typeTemplate == null) ? "" : typeTemplate));
83 ilm 180
                return null;
181
            }
182
            final SpreadSheet spreadSheet;
183
            try {
184
                spreadSheet = new ODPackage(templateStream).getSpreadSheet();
94 ilm 185
                templateStream.close();
19 ilm 186
                // On remplit les cellules de la feuille
187
                parseElementsXML(listElts, row, spreadSheet);
18 ilm 188
 
19 ilm 189
                // Liste des <element>
190
                List<Element> listTable = racine.getChildren("table");
18 ilm 191
 
19 ilm 192
                for (Element tableChild : listTable) {
193
                    // On remplit les cellules du tableau
63 ilm 194
                    parseTableauXML(tableChild, spreadSheet, rowLanguage);
19 ilm 195
                }
196
            } catch (Exception e) {
25 ilm 197
                ExceptionHandler.handle("Impossible de remplir le document " + templateId + " " + ((rowLanguage == null) ? "" : rowLanguage.getString("CHEMIN")), e);
174 ilm 198
                e.printStackTrace();
83 ilm 199
                return null;
18 ilm 200
            }
73 ilm 201
 
202
            if (meta != null) {
203
                meta.applyTo(spreadSheet.getPackage().getMeta(true));
204
            }
205
 
18 ilm 206
            // Sauvegarde du fichier
25 ilm 207
            return saveSpreadSheet(spreadSheet, outputDirectory, expectedFileName, templateId, rowLanguage);
18 ilm 208
 
209
        } catch (final JDOMException e) {
210
 
211
            e.printStackTrace();
212
            SwingUtilities.invokeLater(new Runnable() {
213
                public void run() {
25 ilm 214
                    ExceptionHandler.handle("Erreur lors de la génération du fichier " + expectedFileName, e);
18 ilm 215
                }
216
            });
217
        } catch (final IOException e) {
218
 
219
            e.printStackTrace();
220
            SwingUtilities.invokeLater(new Runnable() {
221
                public void run() {
25 ilm 222
                    ExceptionHandler.handle("Erreur lors de la création du fichier " + expectedFileName, e);
18 ilm 223
                }
224
            });
225
        }
226
        return null;
227
    }
228
 
229
    /**
230
     * Remplit le tableau
231
     *
232
     * @param tableau
233
     * @param elt
234
     * @param id
235
     * @param sheet
236
     */
63 ilm 237
    private void parseTableauXML(Element tableau, SpreadSheet spreadsheet, SQLRow rowLanguage) {
18 ilm 238
 
239
        if (tableau == null) {
240
            return;
241
        }
242
 
243
        Object o = tableau.getAttributeValue("sheet");
244
        int idSheet = (o == null) ? 0 : Integer.valueOf(o.toString().trim());
245
 
246
        Sheet sheet = spreadsheet.getSheet(idSheet);
247
        // Derniere colonne du tableau permet de ne pas chercher sur toutes les colonnes
248
        // et d'optimiser la recherche
249
        Object oLastColTmp = tableau.getAttributeValue("lastColumn");
250
        int lastColumn = -1;
156 ilm 251
        int endPageLine = Integer.parseInt(tableau.getAttributeValue("endPageLine"));
18 ilm 252
        if (oLastColTmp != null) {
253
            lastColumn = sheet.resolveHint(oLastColTmp.toString() + 1).x + 1;
254
        }
255
 
256
        Map<String, Map<Integer, String>> mapStyle = searchStyle(sheet, lastColumn, endPageLine);
257
 
258
        if (tableau.getAttributeValue("table").equalsIgnoreCase("TVA")) {
142 ilm 259
            fillTaxeDocumentMap(tableau, sheet, mapStyle, false);
18 ilm 260
            return;
261
        }
19 ilm 262
        int nbPage = fillTable(tableau, row, sheet, mapStyle, true, rowLanguage);
156 ilm 263
        int firstLine = Integer.parseInt(tableau.getAttributeValue("firstLine"));
264
        int endLine = Integer.parseInt(tableau.getAttributeValue("endLine"));
18 ilm 265
        Object printRangeObj = sheet.getPrintRanges();
266
 
267
        System.err.println("Nombre de page == " + nbPage);
268
        if (nbPage == 1) {
19 ilm 269
            fillTable(tableau, row, sheet, mapStyle, false, rowLanguage);
18 ilm 270
        } else {
271
            if (printRangeObj != null) {
272
                String s = printRangeObj.toString();
273
                String[] range = s.split(":");
274
 
275
                for (int i = 0; i < range.length; i++) {
276
                    String string = range[i];
277
                    range[i] = string.subSequence(string.indexOf('.') + 1, string.length()).toString();
278
                }
279
 
280
                int rowEnd = -1;
281
                if (range.length > 1) {
282
                    rowEnd = sheet.resolveHint(range[1]).y + 1;
19 ilm 283
                    int rowEndNew = rowEnd * (nbPage);
18 ilm 284
                    String sNew = s.replaceAll(String.valueOf(rowEnd), String.valueOf(rowEndNew));
285
                    sheet.setPrintRanges(sNew);
286
                    System.err.println(" ******  Replace print ranges; Old:" + rowEnd + "--" + s + " New:" + rowEndNew + "--" + sNew);
287
                }
288
            }
289
 
290
            // le nombre d'éléments ne tient pas dans le tableau du modéle
291
            // On duplique la premiere page sans ce qui se trouve apres le tableau
292
            sheet.duplicateFirstRows(endLine, 1);
293
 
294
            // On agrandit le tableau pour qu'il remplisse la premiere page
295
            int lineToAdd = endPageLine - endLine;
296
            String repeatedCount = tableau.getAttributeValue("repeatedCount");
297
            if (repeatedCount != null && repeatedCount.trim().length() > 0) {
156 ilm 298
                int count = Integer.parseInt(repeatedCount);
18 ilm 299
                sheet.duplicateRows(firstLine, lineToAdd / count, count);
300
                final int rest = lineToAdd % count;
301
                // Si le nombre de ligne ne termine pas à la fin de la page
302
                if (rest != 0) {
303
                    sheet.insertDuplicatedRows(firstLine + lineToAdd - rest, rest);
304
                }
305
            } else {
306
                sheet.insertDuplicatedRows(firstLine, lineToAdd);
307
            }
308
 
309
            // On duplique la premiere page si on a besoin de plus de deux pages
310
            System.err.println("nbPage == " + nbPage);
311
            if (nbPage > 2) {
312
                sheet.duplicateFirstRows(endPageLine, nbPage - 2);
313
            }
19 ilm 314
            String pageRef = tableau.getAttributeValue("pageRef");
315
            if (pageRef != null && pageRef.trim().length() > 0) {
132 ilm 316
                int nbPageRef = nbPage;
317
                String pageAdd = tableau.getAttributeValue("pageRefAdditional");
318
                if (pageAdd != null && pageAdd.trim().length() > 0) {
319
                    nbPageRef += Integer.valueOf(pageAdd);
320
 
321
                }
19 ilm 322
                MutableCell<SpreadSheet> cell = sheet.getCellAt(pageRef);
132 ilm 323
                String pageStart = tableau.getAttributeValue("pageRefStart");
324
                int start = 1;
325
                if (pageStart != null && pageStart.trim().length() > 0) {
326
                    cell.setValue("Page " + pageStart + "/" + nbPageRef);
327
                    start = Integer.valueOf(pageStart);
328
                } else {
329
                    cell.setValue("Page 1/" + nbPageRef);
330
                }
331
                for (int i = 1; i < nbPageRef; i++) {
19 ilm 332
                    MutableCell<SpreadSheet> cell2 = sheet.getCellAt(cell.getX(), cell.getY() + (endPageLine * i));
132 ilm 333
                    cell2.setValue("Page " + (i + start) + "/" + nbPageRef);
19 ilm 334
                }
132 ilm 335
                if (pageAdd != null && pageAdd.trim().length() > 0) {
156 ilm 336
                    int pAdd = Integer.parseInt(pageAdd);
132 ilm 337
                    for (int i = 0; i < pAdd; i++) {
338
                        Sheet s = sheet.getSpreadSheet().getSheet(idSheet + i + 1);
339
                        MutableCell<SpreadSheet> cell2 = s.getCellAt(pageRef);
340
                        cell2.setValue("Page " + (nbPageRef - (pAdd - i) + 1) + "/" + nbPageRef);
341
                    }
342
                }
343
 
19 ilm 344
            }
345
            fillTable(tableau, row, sheet, mapStyle, false, rowLanguage);
18 ilm 346
        }
347
 
348
    }
349
 
350
    /**
351
     * Remplit le tableau d'éléments avec les données
352
     *
353
     * @param tableau Element Xml contenant les informations sur le tableau
354
     * @param elt SQLElement (ex : Bon de livraison)
355
     * @param id id de l'élément de la table
356
     * @param sheet feuille calc à remplir
357
     * @param mapStyle styles trouvés dans la page
358
     * @param test remplir ou non avec les valeurs
359
     * @return le nombre de page
360
     */
361
 
63 ilm 362
    protected SQLRowAccessor getForeignRow(SQLRowAccessor row, SQLField field) {
18 ilm 363
        Map<Integer, SQLRowAccessor> c = cacheForeign.get(field.getName());
364
 
365
        int i = row.getInt(field.getName());
366
 
367
        if (c != null && c.get(i) != null) {
368
            return c.get(i);
369
        } else {
370
 
371
            SQLRowAccessor foreign = row.getForeign(field.getName());
372
 
373
            if (c == null) {
156 ilm 374
                Map<Integer, SQLRowAccessor> map = new HashMap<>();
18 ilm 375
                map.put(i, foreign);
376
                cacheForeign.put(field.getName(), map);
377
            } else {
378
                c.put(i, foreign);
379
            }
380
 
381
            return foreign;
382
        }
383
 
384
    }
385
 
142 ilm 386
    private void fillTaxe(Element tableau, List<? extends SQLRowAccessor> rows) {
387
        // getValuesFromElement(boolean achat, String fieldTotalHT, SQLRow row, SQLTable foreign,
388
        // BigDecimal portHT, SQLRow rowTVAPort, SQLTable tableEchantillon,
389
        // SQLRow defaultCompte) {
390
        SQLTable tableElt = Configuration.getInstance().getRoot().findTable(tableau.getAttributeValue("table"));
144 ilm 391
        SQLBackgroundTableCacheItem cacheItem = SQLBackgroundTableCache.getInstance().getCacheForTable(tableElt.getTable("COMPTE_PCE"));
392
        SQLBackgroundTableCacheItem prefsCpt = SQLBackgroundTableCache.getInstance().getCacheForTable(tableElt.getTable("PREFS_COMPTE"));
142 ilm 393
        if (tableElt.contains("ID_TAXE") && tableElt.contains("T_PA_HT")) {
394
            boolean achat = tableElt.contains("T_PA_TTC");
156 ilm 395
            TotalCalculator calc = new TotalCalculator("T_PA_HT", achat ? "T_PA_HT" : "T_PV_HT", null, achat, null, null);
142 ilm 396
            String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
397
            Boolean bServiceActive = Boolean.valueOf(val);
398
 
399
            calc.setServiceActive(bServiceActive != null && bServiceActive);
400
            if (row.getTable().contains("ID_COMPTE_PCE_SERVICE") && !row.isForeignEmpty("ID_COMPTE_PCE_SERVICE")) {
144 ilm 401
                SQLRowAccessor serviceCompte = cacheItem.getRowFromId(row.getForeignID("ID_COMPTE_PCE_SERVICE"));
142 ilm 402
                if (!serviceCompte.isUndefined()) {
403
                    calc.setRowDefaultCptService(serviceCompte);
404
                }
405
            }
406
            if (row.getTable().contains("ID_COMPTE_PCE_VENTE") && !row.isForeignEmpty("ID_COMPTE_PCE_VENTE")) {
144 ilm 407
                SQLRowAccessor produitCompte = cacheItem.getRowFromId(row.getForeignID("ID_COMPTE_PCE_VENTE"));
142 ilm 408
                if (!produitCompte.isUndefined()) {
409
                    calc.setRowDefaultCptProduit(produitCompte);
410
                }
411
            }
412
            long remise = 0;
413
            BigDecimal totalAvtRemise = BigDecimal.ZERO;
414
            SQLTable tableEchantillon = null;
415
            if (row.getTable().contains("REMISE_HT")) {
416
                remise = row.getLong("REMISE_HT");
417
                if (remise != 0) {
418
                    for (SQLRowAccessor sqlRow : rows) {
419
                        calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), 1, false);
420
                    }
421
 
422
                    if (tableEchantillon != null) {
423
                        List<SQLRow> rowsEch = row.getReferentRows(tableEchantillon);
424
                        for (SQLRow sqlRow : rowsEch) {
144 ilm 425
                            calc.addEchantillon((BigDecimal) sqlRow.getObject("T_PV_HT"), TaxeCache.getCache().getRowFromId(sqlRow.getForeignID("ID_TAXE")));
142 ilm 426
                        }
427
                    }
428
                    calc.checkResult();
429
                    totalAvtRemise = calc.getTotalHT();
430
                }
431
            }
432
 
433
            calc.initValues();
434
            long valRemiseHTReel = remise;
435
            if (row.getFields().contains("POURCENT_FACTURABLE") && row.getFields().contains("MONTANT_FACTURABLE")) {
436
                BigDecimal montantFact = row.getBigDecimal("MONTANT_FACTURABLE");
437
                BigDecimal percentFact = row.getBigDecimal("POURCENT_FACTURABLE");
438
 
439
                if (montantFact != null && montantFact.signum() > 0) {
440
                    valRemiseHTReel = 0;
441
                } else if (percentFact != null && percentFact.signum() > 0) {
442
                    valRemiseHTReel = percentFact.movePointLeft(2).multiply(new BigDecimal(remise)).setScale(0, RoundingMode.HALF_UP).longValue();
443
                }
444
 
445
            }
446
            calc.setRemise(valRemiseHTReel, totalAvtRemise);
447
 
174 ilm 448
            // Fix TVA si nécessaire pour facture fournisseur
449
            if (row.getTable().contains("TVA_ADJUSTMENT")) {
450
                BigDecimal tvaFix = row.getBigDecimal("TVA_ADJUSTMENT");
451
                calc.addTVAAdjust(tvaFix);
452
            }
453
 
142 ilm 454
            for (int i = 0; i < rows.size(); i++) {
455
                SQLRowAccessor sqlRow = rows.get(i);
456
                calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), i, i == rows.size() - 1);
457
            }
458
 
459
            if (tableEchantillon != null) {
460
                List<SQLRow> rowsEch = row.getReferentRows(tableEchantillon);
461
                for (SQLRow sqlRow : rowsEch) {
144 ilm 462
                    calc.addEchantillon((BigDecimal) sqlRow.getObject("T_PV_HT"), TaxeCache.getCache().getRowFromId(sqlRow.getForeignID("ID_TAXE")));
142 ilm 463
                }
464
            }
465
            SQLRowAccessor rowTVAPort = null;
466
            if (row.getTable().contains("ID_TAXE_PORT")) {
144 ilm 467
                rowTVAPort = TaxeCache.getCache().getRowFromId(row.getForeignID("ID_TAXE_PORT"));
142 ilm 468
            }
469
            if (rowTVAPort != null && !rowTVAPort.isUndefined()) {
470
                SQLRowValues rowValsPort = new SQLRowValues(tableElt);
471
                rowValsPort.put("T_PV_HT", BigDecimal.valueOf(row.getLong("PORT_HT")).movePointLeft(2));
472
                rowValsPort.put("QTE", 1);
473
                rowValsPort.put("ID_TAXE", rowTVAPort.getIDNumber());
474
 
144 ilm 475
                final SQLRow rowPrefsCompte = prefsCpt.getRowFromId(2);
142 ilm 476
                SQLRow rowDefaultCptPort;
477
                if (rowTVAPort.getFloat("TAUX") > 0) {
144 ilm 478
                    rowDefaultCptPort = cacheItem.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_SOUMIS"));
142 ilm 479
                    if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
480
                        try {
481
                            rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteSoumisTVA");
482
                        } catch (Exception e) {
483
                            e.printStackTrace();
484
                        }
485
                    }
486
                } else {
144 ilm 487
                    rowDefaultCptPort = cacheItem.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_NON_SOUMIS"));
142 ilm 488
                    if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
489
                        try {
490
                            rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteNonSoumisTVA");
491
                        } catch (Exception e) {
492
                            e.printStackTrace();
493
                        }
494
                    }
495
                }
149 ilm 496
                rowValsPort.putRowValues("ID_ARTICLE").put("ID_COMPTE_PCE", rowDefaultCptPort.getID()).put("ID_COMPTE_PCE_ACHAT", rowDefaultCptPort.getID());
142 ilm 497
 
498
                calc.addLine(rowValsPort, rowValsPort.getForeign("ID_ARTICLE"), 1, false);
499
            }
174 ilm 500
            if (row.getTable().contains("FRAIS_DOCUMENT_HT") && row.getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
501
                BigDecimal fraisDoc = BigDecimal.valueOf(row.getLong("FRAIS_DOCUMENT_HT")).movePointLeft(2);
502
                SQLRowAccessor tvafraisDoc = row.getForeign("ID_TAXE_FRAIS_DOCUMENT");
503
                if (tvafraisDoc != null && fraisDoc.signum() != 0 && !tvafraisDoc.isUndefined()) {
504
                    SQLRowValues rowValsfraisDoc = new SQLRowValues(tableElt);
505
                    rowValsfraisDoc.put("T_PV_HT", fraisDoc);
506
                    rowValsfraisDoc.put("QTE", 1);
507
                    rowValsfraisDoc.put("ID_TAXE", tvafraisDoc.getIDNumber());
508
                    rowValsfraisDoc.put("SERVICE", Boolean.TRUE);
509
                    rowValsfraisDoc.put("ID_FAMILLE_ARTICLE", null);
510
                    calc.addLine(rowValsfraisDoc, null, 1, false);
511
                }
512
            }
513
 
142 ilm 514
            calc.checkResult();
515
            Map<SQLRowAccessor, Tuple2<BigDecimal, BigDecimal>> taxeCalc = calc.getMapHtTVARowTaux();
516
            for (SQLRowAccessor sqlRow : taxeCalc.keySet()) {
517
                Tuple2<BigDecimal, BigDecimal> v = taxeCalc.get(sqlRow);
156 ilm 518
                Map<String, Object> m = new HashMap<>();
142 ilm 519
                m.put("MONTANT_HT", v.get0());
520
                m.put("MONTANT_TVA", v.get1());
521
                taxe.put(sqlRow, m);
522
            }
523
        }
524
    }
525
 
63 ilm 526
    private int fillTable(Element tableau, SQLRow row, Sheet sheet, Map<String, Map<Integer, String>> mapStyle, boolean test, SQLRow rowLanguage) {
18 ilm 527
 
528
        if (tableau == null) {
529
            return 1;
530
        }
531
 
532
        int nbPage = 1;
533
        int nbCellules = 0;
534
 
63 ilm 535
        OOXMLTableElement tableElement = new OOXMLTableElement(tableau, row, this.rowRefCache);
18 ilm 536
        int currentLineTmp = tableElement.getFirstLine();
537
        int currentLine = tableElement.getFirstLine();
538
 
144 ilm 539
        StyleSQLElement styleElt = Configuration.getInstance().getDirectory().getElement(StyleSQLElement.class);
18 ilm 540
 
541
        String ref = tableau.getAttributeValue("table") + "_" + row.getTable().getName() + row.getID();
542
        if (rowsEltCache.get(ref) == null) {
543
            rowsEltCache.put(ref, tableElement.getRows());
544
        }
545
        List<Element> listElts = tableau.getChildren("element");
546
 
142 ilm 547
        fillTaxe(tableau, rowsEltCache.get(ref));
18 ilm 548
        // on remplit chaque ligne à partir des rows recuperées
21 ilm 549
        int numeroRef = 0;
18 ilm 550
        for (SQLRowAccessor rowElt : rowsEltCache.get(ref)) {
83 ilm 551
 
18 ilm 552
            final boolean included = isIncluded(tableElement.getFilterId(), tableElement.getForeignTableWhere(), tableElement.getFilterId(), tableElement.getFieldWhere(), rowElt);
83 ilm 553
            String styleName = null;
554
            if (tableElement.getSQLElement().getTable().contains("ID_STYLE")) {
144 ilm 555
                styleName = styleElt.getAllStyleByIds().get(rowElt.getForeignID("ID_STYLE"));
83 ilm 556
            }
18 ilm 557
 
83 ilm 558
            if ((included || tableElement.getTypeStyleWhere()) && (styleName == null || !styleName.equalsIgnoreCase("Invisible"))) {
18 ilm 559
 
83 ilm 560
                numeroRef++;
561
 
18 ilm 562
                if (included && tableElement.getTypeStyleWhere()) {
563
                    styleName = "Titre 1";
564
                }
565
 
566
                if (!included) {
567
                    styleName = "Normal";
568
                }
569
 
73 ilm 570
                // Blank Line Style
18 ilm 571
                boolean first = true;
19 ilm 572
                int toAdd = 0;
73 ilm 573
                if (styleName != null && tableElement.getListBlankLineStyle().contains(styleName) && first) {
83 ilm 574
 
73 ilm 575
                    toAdd++;
576
                    currentLine++;
577
                    first = false;
578
                }
21 ilm 579
 
73 ilm 580
                // Cache des valeurs
156 ilm 581
                Map<Element, Object> mapValues = new HashMap<>();
18 ilm 582
 
73 ilm 583
                // Test si l'ensemble des donnees tient sur la page courante
156 ilm 584
                Map<String, Integer> tmpMapNbCel = new HashMap<>();
73 ilm 585
                int tmpNbCellule = fillTableLine(sheet, mapStyle, true, rowLanguage, tableElement, currentLine, listElts, numeroRef, rowElt, tmpMapNbCel, styleName, mapValues);
586
                for (String s : tmpMapNbCel.keySet()) {
587
                    tmpNbCellule = Math.max(tmpNbCellule, tmpMapNbCel.get(s));
21 ilm 588
                }
73 ilm 589
                if ((currentLine + tmpNbCellule) > (tableElement.getEndPageLine() * nbPage)) {
590
                    toAdd += (tableElement.getEndPageLine() * nbPage) - currentLine;
591
                    currentLine = currentLineTmp + tableElement.getEndPageLine();
592
                    currentLineTmp = currentLine;
593
                    nbPage++;
594
                }
18 ilm 595
 
73 ilm 596
                // Remplissage reel des cellules
156 ilm 597
                Map<String, Integer> mapNbCel = new HashMap<>();
73 ilm 598
                int nbCellule = fillTableLine(sheet, mapStyle, test, rowLanguage, tableElement, currentLine, listElts, numeroRef, rowElt, mapNbCel, styleName, mapValues);
21 ilm 599
 
18 ilm 600
                for (String s : mapNbCel.keySet()) {
601
                    nbCellule = Math.max(nbCellule, mapNbCel.get(s));
602
                }
603
                currentLine += nbCellule;
19 ilm 604
                nbCellules += (nbCellule + toAdd);
18 ilm 605
            }
606
        }
73 ilm 607
 
608
        // Nb page entiere
18 ilm 609
        int d = nbCellules / (tableElement.getEndPageLine() - tableElement.getFirstLine());
73 ilm 610
        // Nb cellule restant
18 ilm 611
        int r = nbCellules % (tableElement.getEndPageLine() - tableElement.getFirstLine());
612
 
613
        if (d == 0) {
614
            d++;
615
            if (nbCellules > (tableElement.getEndLine() - tableElement.getFirstLine() + 1)) {
616
                d++;
617
            }
618
        } else {
619
            if (r > (tableElement.getEndLine() - tableElement.getFirstLine() + 1)) {
620
                d += 2;
621
            } else {
622
                d++;
623
            }
624
        }
625
        return d;
626
    }
627
 
73 ilm 628
    private int fillTableLine(Sheet sheet, Map<String, Map<Integer, String>> mapStyle, boolean test, SQLRow rowLanguage, OOXMLTableElement tableElement, int currentLine, List<Element> listElts,
629
            int numeroRef, SQLRowAccessor rowElt, Map<String, Integer> mapNbCel, String styleName, Map<Element, Object> mapValues) {
630
        int nbCellule = 1;
631
        int tableLine = 1;
132 ilm 632
 
633
        // Application du style sur toute la ligne (exemple pour mettre une couleur en fond)
634
        if (styleName != null && styleName.trim().length() > 0 && mapStyle != null && mapStyle.containsKey(styleName)) {
635
            Map<Integer, String> mapLineStyle = mapStyle.get(styleName);
636
            if (mapLineStyle != null) {
637
                for (Integer col : mapLineStyle.keySet()) {
638
                    if (!test && sheet.isCellValid(col, currentLine - 1)) {
639
                        sheet.getCellAt(col, currentLine - 1).setStyleName(mapLineStyle.get(col));
640
                    }
641
                }
642
            }
643
        }
644
 
73 ilm 645
        // on remplit chaque cellule de la ligne
646
        for (Element e : listElts) {
647
 
648
            OOXMLTableField tableField = new OOXMLTableField(e, rowElt, tableElement.getSQLElement(), rowElt.getID(), tableElement.getTypeStyleWhere() ? -1 : tableElement.getFilterId(), rowLanguage,
649
                    numeroRef, this.rowRefCache);
650
 
651
            if (mapNbCel.get(e.getAttributeValue("location").trim()) != null) {
652
                nbCellule = mapNbCel.get(e.getAttributeValue("location").trim());
653
            } else {
654
                nbCellule = 1;
655
            }
656
            int line = tableField.getLine();
657
            if (tableField.getLine() > 1) {
658
                line = Math.max(nbCellule + ((tableLine == tableField.getLine()) ? 0 : 1), tableField.getLine());
659
            }
660
            tableLine = tableField.getLine();
661
            String loc = e.getAttributeValue("location").trim() + (currentLine + (line - 1));
662
 
663
            // Cellule pour un style défini
664
            List<String> listBlankStyle = tableField.getBlankStyle();
665
 
666
            // nbCellule = Math.max(nbCellule, tableField.getLine());
667
 
668
            if (styleName == null || !listBlankStyle.contains(styleName)) {
669
 
670
                try {
671
                    Object value = mapValues.get(e);
672
                    if (value == null) {
673
                        value = tableField.getValue();
674
                        mapValues.put(e, value);
675
                    }
676
                    // if (value != null && value.toString().trim().length() > 0) {
677
                    if (tableField.isNeeding2Lines() && tableField.getLine() == 1) {
678
                        loc = e.getAttributeValue("location").trim() + (currentLine + 1);
679
                        styleName = null;
680
                    }
681
                    final Point resolveHint = sheet.resolveHint(loc);
682
                    if (test || sheet.isCellValid(resolveHint.x, resolveHint.y)) {
683
 
684
                        String styleNameTmp = styleName;
685
                        if (tableField.getStyle().trim().length() > 0) {
686
                            styleNameTmp = tableField.getStyle();
687
                        }
688
 
689
                        Map<Integer, String> mTmp = styleName == null ? null : mapStyle.get(styleNameTmp);
690
                        String styleOO = null;
691
                        if (mTmp != null) {
692
 
693
                            Object oTmp = mTmp.get(Integer.valueOf(resolveHint.x));
694
                            styleOO = oTmp == null ? null : oTmp.toString();
695
                        }
696
 
697
                        // Test pour ne pas supprimer le style sur la derniere cellule du
698
                        // tableau et donc enlever la ligne de bas de tableau
699
                        if (tableField.isLineOption() && value != null && value.toString().trim().length() == 0) {
700
                            value = null;
701
                            styleOO = null;
702
                        }
703
 
132 ilm 704
                        int tmpCelluleAffect = fill(test ? "A1" : loc, value, sheet, tableField.isTypeReplace(), null, styleOO, test, tableField.isMultilineAuto(), tableField.isKeepingEmptyLines());
73 ilm 705
                        // tmpCelluleAffect = Math.max(tmpCelluleAffect,
706
                        // tableField.getLine());
707
                        if (tableField.getLine() != 1 && (!tableField.isLineOption() || (value != null && value.toString().trim().length() > 0))) {
708
                            if (nbCellule >= tableField.getLine()) {
709
                                tmpCelluleAffect = tmpCelluleAffect + nbCellule;
710
                            } else {
711
                                tmpCelluleAffect += tableField.getLine() - 1;
712
                            }
713
                        }
714
 
715
                        if (tableField.isNeeding2Lines()) {
716
                            nbCellule = Math.max(nbCellule, 2);
717
                        } else {
718
                            nbCellule = Math.max(nbCellule, tmpCelluleAffect);
719
                        }
720
                    } else {
721
                        System.err.println("Cell not valid at " + loc);
722
                    }
723
                    // }
724
                } catch (IndexOutOfBoundsException indexOut) {
725
                    System.err.println("Cell not valid at " + loc);
726
                }
727
            }
728
            mapNbCel.put(e.getAttributeValue("location").trim(), nbCellule);
729
        }
730
        return nbCellule;
731
    }
732
 
142 ilm 733
    private void fillTaxeDocumentMap(Element tableau, Sheet sheet, Map<String, Map<Integer, String>> mapStyle, boolean test) {
18 ilm 734
 
156 ilm 735
        int line = Integer.parseInt(tableau.getAttributeValue("firstLine"));
18 ilm 736
        List<Element> listElts = tableau.getChildren("element");
737
 
738
        for (SQLRowAccessor rowTaxe : taxe.keySet()) {
739
 
740
            Map<String, Object> m = taxe.get(rowTaxe);
741
            // on remplit chaque cellule de la ligne
742
            for (Element e : listElts) {
743
 
744
                String loc = e.getAttributeValue("location").trim() + line;
745
                String name = e.getAttributeValue("name");
746
                String typeComp = e.getAttributeValue("type");
747
                if (name == null) {
748
                    System.err.println("OOgenerationXML.fillTaxe() --> name == null");
749
                } else {
750
                    Object value = m.get(name);
83 ilm 751
                    if (name.equalsIgnoreCase("MONTANT_HT")) {
752
                        value = ((BigDecimal) m.get("MONTANT_HT"));
753
                    } else if (name.equalsIgnoreCase("MONTANT_TVA")) {
67 ilm 754
                        // value = Math.round(((Long) m.get("MONTANT_HT") * rowTaxe.getFloat("TAUX")
755
                        // / 100.0));
142 ilm 756
                        value = ((BigDecimal) m.get("MONTANT_TVA"));
757
                        // value = ((BigDecimal) m.get("MONTANT_HT")).multiply(new
758
                        // BigDecimal(rowTaxe.getFloat("TAUX")),
759
                        // DecimalUtils.HIGH_PRECISION).movePointLeft(2);
18 ilm 760
                    } else if (name.equalsIgnoreCase("NOM")) {
142 ilm 761
                        value = TaxeCache.getCache().getRowFromId(rowTaxe.getID()).getString("NOM");
18 ilm 762
                        // TODO prefix et suffix
763
                        String prefix = e.getAttributeValue("prefix");
764
                        if (prefix != null) {
765
                            value = prefix + value;
766
                        }
767
                        String suffix = e.getAttributeValue("suffix");
768
                        if (suffix != null) {
769
                            value = value + suffix;
770
                        }
771
                    }
67 ilm 772
                    // if (typeComp != null && typeComp.equalsIgnoreCase("Devise")) {
773
                    // if (value != null && value instanceof Long)
774
                    // value = Double.valueOf(GestionDevise.currencyToString((Long) value, false));
775
                    // }
132 ilm 776
                    fill(test ? "A1" : loc, value, sheet, false, null, null, test, false, false);
18 ilm 777
                }
778
            }
779
            line++;
780
        }
781
    }
782
 
783
    /**
784
     * Parse l'ensemble des éléments du fichier et insere les valeurs dans le fichier sxc
785
     *
786
     * @param elts
787
     * @param sqlElt
788
     * @param id
789
     */
63 ilm 790
    private void parseElementsXML(List<Element> elts, SQLRow row, SpreadSheet spreadSheet) {
65 ilm 791
        final SQLElement sqlElt = Configuration.getInstance().getDirectory().getElement(row.getTable());
18 ilm 792
        for (Element elt : elts) {
65 ilm 793
            final OOXMLElement OOElt = new OOXMLElement(elt, sqlElt, row.getID(), row, null, this.rowRefCache);
794
            final Object result = OOElt.getValue();
18 ilm 795
            if (result != null) {
796
                Object o = elt.getAttributeValue("sheet");
797
                int sheet = (o == null) ? 0 : Integer.valueOf(o.toString().trim());
132 ilm 798
                fill(elt.getAttributeValue("location"), result, spreadSheet.getSheet(sheet), OOElt.isTypeReplace(), OOElt.getReplacePattern(), null, false, OOElt.isMultilineAuto(),
799
                        OOElt.isKeepingEmptyLines());
18 ilm 800
            }
801
        }
802
    }
803
 
804
    private static boolean isIncluded(int filterID, String foreignTable, int id, String fieldWhere, SQLRowAccessor rowElt) {
805
 
91 ilm 806
        if (rowElt.getTable().getName().equals("FICHE_PAYE_ELEMENT")) {
807
            if (!rowElt.getBoolean("IMPRESSION")) {
808
                return false;
809
            }
810
            if (!rowElt.getBoolean("IN_PERIODE")) {
811
                return false;
812
            }
813
        }
814
 
815
        if (fieldWhere != null && fieldWhere.trim().length() > 0 && rowElt.getTable().contains(fieldWhere) && rowElt.getTable().getField(fieldWhere).getType().getJavaType() == Boolean.class) {
816
            return rowElt.getBoolean(fieldWhere);
817
        }
818
 
18 ilm 819
        // No filter
820
        if (filterID <= 1) {
821
            return true;
822
        } else {
823
            // Filter id in foreign table (FICHE_RENDEZ_VOUS<-POURCENT_SERVICE[ID_VERIFICATEUR]
824
            if (foreignTable != null) {
825
                boolean b = false;
826
                SQLTable table = Configuration.getInstance().getRoot().findTable(foreignTable);
827
                Collection<? extends SQLRowAccessor> set = rowElt.getReferentRows(table);
828
                for (SQLRowAccessor row : set) {
829
                    b = b || (row.getInt(fieldWhere) == filterID);
830
                }
831
                return b;
832
            } else {
833
                return (filterID == id);
834
            }
835
        }
836
    }
837
 
838
    /**
839
     * Permet de remplir une cellule
840
     *
841
     * @param location position de la cellule exemple : A3
842
     * @param value valeur à insérer dans la cellule
843
     * @param sheet feuille sur laquelle on travaille
844
     * @param replace efface ou non le contenu original de la cellule
845
     * @param styleOO style à appliquer
846
     */
132 ilm 847
    private int fill(String location, Object value, Sheet sheet, boolean replace, String replacePattern, String styleOO, boolean test, boolean controleMultiline, boolean keepEmptyLines) {
18 ilm 848
 
849
        int nbCellule = (test && styleOO == null) ? 2 : 1;
850
        // est ce que la cellule est valide
851
        if (test || sheet.isCellValid(sheet.resolveHint(location).x, sheet.resolveHint(location).y)) {
852
 
853
            MutableCell cell = sheet.getCellAt(location);
854
 
855
            // on divise en 2 cellules si il y a des retours à la ligne
856
            if (controleMultiline && value != null && value.toString().indexOf('\n') >= 0) {
857
                String[] values = value.toString().split("\n");
858
 
132 ilm 859
                Point p = sheet.resolveHint(location);
860
                int y = 0;
861
                for (String string : values) {
862
                    if (string != null && (keepEmptyLines || string.trim().length() != 0)) {
863
                        try {
864
                            if (!test) {
18 ilm 865
                                MutableCell c = sheet.getCellAt(p.x, p.y + y);
866
                                setCellValue(c, string, replace, replacePattern);
867
                                if (styleOO != null) {
21 ilm 868
                                    c.setStyleName(styleOO);
18 ilm 869
                                }
132 ilm 870
                            }
871
                            y++;
872
                        } catch (IllegalArgumentException e) {
83 ilm 873
 
132 ilm 874
                            ExceptionHandler.handle("La cellule " + location + " n'existe pas ou est fusionnée.", e);
18 ilm 875
                        }
876
                    }
877
 
878
                    // String firstPart = value.toString().substring(0,
879
                    // value.toString().indexOf('\n'));
880
                    // String secondPart = value.toString().substring(value.toString().indexOf('\n')
881
                    // + 1, value.toString().length());
882
                    // secondPart = secondPart.replace('\n', ',');
883
                    // // System.err.println("Set cell value 1 " + value);
884
                    // setCellValue(cell, firstPart, replace, replacePattern);
885
                    // if (styleOO != null) {
886
                    // cell.setStyleName(styleOO);
887
                    // }
888
                    //
889
                    // Point p = sheet.resolveHint(location);
890
                    // System.err.println("Get Cell At " + p.x + " : " + p.y);
891
 
892
                }
132 ilm 893
                nbCellule = y;
18 ilm 894
            } else {
73 ilm 895
                nbCellule = 1;
18 ilm 896
                if (!test) {
897
                    // application de la valeur
898
                    // System.err.println("Set cell value 2 " + value);
899
                    setCellValue(cell, value, replace, replacePattern);
900
 
901
                    // Application du style
902
                    if (styleOO != null) {
903
                        cell.setStyleName(styleOO);
904
                    }
905
                }
906
            }
907
        }
908
        return nbCellule;
909
    }
910
 
911
    /**
912
     * remplit une cellule
913
     *
914
     * @param cell
915
     * @param value
916
     * @param replace
917
     */
63 ilm 918
    private void setCellValue(MutableCell cell, Object value, boolean replace, String replacePattern) {
18 ilm 919
        if (value == null) {
19 ilm 920
            return;
921
            // value = "";
18 ilm 922
        }
923
 
924
        if (replace) {
925
            if (replacePattern != null) {
926
                cell.replaceBy(replacePattern, value.toString());
927
            } else {
928
                cell.replaceBy("_", value.toString());
929
            }
930
        } else {
931
            cell.setValue(value);
932
        }
933
    }
934
 
935
    /**
936
     * Sauver le document au format OpenOffice. Si le fichier existe déjà, le fichier existant sera
937
     * renommé sous la forme nomFic_1.sxc.
938
     *
939
     * @param ssheet SpreadSheet à sauvegarder
940
     * @param pathDest répertoire de destination du fichier
941
     * @param fileName nom du fichier à créer
942
     * @return un File pointant sur le fichier créé
943
     * @throws IOException
944
     */
945
 
25 ilm 946
    private static File saveSpreadSheet(SpreadSheet ssheet, File pathDest, String fileName, String templateId, SQLRow rowLanguage) throws IOException {
947
        final String langage = rowLanguage != null ? rowLanguage.getString("CHEMIN") : null;
18 ilm 948
        // Test des arguments
949
        if (ssheet == null || pathDest == null || fileName.trim().length() == 0) {
950
            throw new IllegalArgumentException();
951
        }
952
 
953
        // Renommage du fichier si il existe déja
954
        File fDest = new File(pathDest, fileName + ".ods");
955
 
956
        if (!pathDest.exists()) {
957
            pathDest.mkdirs();
958
        }
959
 
57 ilm 960
        fDest = SheetUtils.convertToOldFile(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete(), fileName, pathDest, fDest);
18 ilm 961
 
962
        // Sauvegarde
963
        try {
964
            ssheet.saveAs(fDest);
965
        } catch (FileNotFoundException e) {
966
            final File file = fDest;
967
            SwingUtilities.invokeLater(new Runnable() {
968
                public void run() {
969
                    try {
970
                        JOptionPane.showMessageDialog(null, "Le fichier " + file.getCanonicalPath() + " n'a pu être créé. \n Vérifiez qu'il n'est pas déjà ouvert.");
971
                    } catch (IOException e) {
972
                        e.printStackTrace();
973
                    }
974
                }
975
            });
976
 
977
            e.printStackTrace();
978
        }
979
 
980
        // Copie de l'odsp
156 ilm 981
        File odspOut = new File(pathDest, fileName + ".odsp");
982
        try (final InputStream odspIn = TemplateManager.getInstance().getTemplatePrintConfiguration(templateId, langage, null);) {
18 ilm 983
            if (odspIn != null) {
984
                StreamUtils.copy(odspIn, odspOut);
985
            }
986
        } catch (FileNotFoundException e) {
94 ilm 987
            System.err.println("OOgenerationXML.saveSpreadSheet() : Le fichier odsp n'existe pas.");
18 ilm 988
        }
989
        return fDest;
990
    }
991
 
992
    /**
993
     * parcourt l'ensemble de la feuille pour trouver les style définit
994
     */
63 ilm 995
    private Map<String, Map<Integer, String>> searchStyle(Sheet sheet, int colEnd, int rowEnd) {
18 ilm 996
 
997
        if (cacheStyle.get(sheet) != null) {
998
            return cacheStyle.get(sheet);
999
        }
1000
 
1001
        Map<String, Map<Integer, String>> mapStyleDef = StyleSQLElement.getMapAllStyle();
1002
 
1003
        // on parcourt chaque ligne de la feuille pour recuperer les styles
1004
        int columnCount = (colEnd == -1) ? sheet.getColumnCount() : (colEnd + 1);
1005
        System.err.println("End column search : " + columnCount);
1006
 
1007
        int rowCount = (rowEnd > 0) ? rowEnd : sheet.getRowCount();
1008
        System.err.println("End row search : " + rowCount);
1009
        for (int i = 0; i < rowCount; i++) {
1010
            int x = 0;
156 ilm 1011
            Map<Integer, String> mapCellStyle = new HashMap<>();
18 ilm 1012
            String style = "";
1013
 
1014
            for (int j = 0; j < columnCount; j++) {
1015
 
1016
                try {
1017
                    if (sheet.isCellValid(j, i)) {
1018
 
1019
                        MutableCell c = sheet.getCellAt(j, i);
1020
                        String cellStyle = c.getStyleName();
1021
 
1022
                        try {
1023
                            if (mapStyleDef.containsKey(c.getValue().toString())) {
1024
                                style = c.getValue().toString();
1025
                            }
1026
                        } catch (IllegalStateException e) {
1027
                            e.printStackTrace();
1028
                        }
1029
                        mapCellStyle.put(Integer.valueOf(x), cellStyle);
1030
                        if (style.trim().length() != 0) {
1031
                            c.clearValue();
1032
                            if (!style.trim().equalsIgnoreCase("Normal") && mapStyleDef.get("Normal") != null) {
1033
                                String styleCell = mapStyleDef.get("Normal").get(Integer.valueOf(x));
1034
                                if (styleCell != null && styleCell.length() != 0) {
1035
                                    c.setStyleName(styleCell);
1036
                                }
1037
                            }
1038
                        }
1039
                    }
1040
                } catch (IndexOutOfBoundsException e) {
1041
                    System.err.println("Index out of bounds Exception");
1042
                }
1043
                x++;
1044
            }
1045
 
1046
            if (style.length() > 0) {
1047
                mapStyleDef.put(style, mapCellStyle);
1048
            }
1049
        }
1050
        cacheStyle.put(sheet, mapStyleDef);
1051
        return mapStyleDef;
1052
    }
1053
 
65 ilm 1054
    public boolean needAnnexe(String templateId, String typeTemplate, SQLRow row, SQLRow rowLanguage) {
25 ilm 1055
        final String langage = rowLanguage != null ? rowLanguage.getString("CHEMIN") : null;
1056
        final SAXBuilder builder = new SAXBuilder();
18 ilm 1057
        try {
65 ilm 1058
            final InputStream xmlConfiguration = TemplateManager.getInstance().getTemplateConfiguration(templateId, langage, typeTemplate);
25 ilm 1059
            final Document doc = builder.build(xmlConfiguration);
94 ilm 1060
            xmlConfiguration.close();
65 ilm 1061
            final InputStream template = TemplateManager.getInstance().getTemplate(templateId, langage, typeTemplate);
25 ilm 1062
            final SpreadSheet spreadSheet = new ODPackage(template).getSpreadSheet();
94 ilm 1063
            template.close();
18 ilm 1064
 
1065
            // On initialise un nouvel élément racine avec l'élément racine du document.
1066
            Element racine = doc.getRootElement();
1067
 
1068
            List<Element> listTable = racine.getChildren("table");
1069
 
1070
            Element tableau;
156 ilm 1071
            if (listTable.isEmpty()) {
18 ilm 1072
                return false;
1073
            } else {
1074
                if (listTable.get(0).getAttributeValue("table").equalsIgnoreCase("TVA")) {
1075
                    tableau = listTable.get(1);
1076
                } else {
1077
                    tableau = listTable.get(0);
1078
                }
1079
            }
1080
            final Sheet sheet = spreadSheet.getSheet(0);
1081
 
1082
            Object oLastColTmp = tableau.getAttributeValue("lastColumn");
1083
            int lastColumn = -1;
156 ilm 1084
            int endPageLine = Integer.parseInt(tableau.getAttributeValue("endPageLine"));
18 ilm 1085
            if (oLastColTmp != null) {
1086
                lastColumn = sheet.resolveHint(oLastColTmp.toString() + 1).x + 1;
1087
            }
1088
 
1089
            Map<String, Map<Integer, String>> mapStyle = searchStyle(sheet, lastColumn, endPageLine);
1090
 
19 ilm 1091
            int nbPage = fillTable(tableau, row, sheet, mapStyle, true, rowLanguage);
18 ilm 1092
 
1093
            return nbPage > 1;
83 ilm 1094
        } catch (Throwable e) {
1095
            Log.get().severe(e.getMessage());
18 ilm 1096
            e.printStackTrace();
1097
        }
1098
        return false;
1099
    }
1100
 
63 ilm 1101
    protected String getStringProposition(SQLRow rowProp) {
18 ilm 1102
        return "Notre proposition " + rowProp.getString("NUMERO") + " du " + dateFormat.format(rowProp.getObject("DATE"));
1103
    }
1104
 
1105
    public static void main(String[] args) {
1106
        ComptaPropsConfiguration conf = ComptaPropsConfiguration.create();
1107
        System.err.println("Conf created");
1108
        Configuration.setInstance(conf);
1109
        conf.setUpSocieteDataBaseConnexion(36);
1110
        System.err.println("Connection Set up");
1111
        SQLElement elt = Configuration.getInstance().getDirectory().getElement("DEVIS");
1112
 
1113
        System.err.println("Start Genere");
19 ilm 1114
        // genere("Devis", "C:\\", "Test", elt.getTable().getRow(19));
18 ilm 1115
        System.err.println("Stop genere");
1116
    }
1117
}