OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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