OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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