OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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