OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 142 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
132 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.core.sales.pos;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.config.MainFrame;
18
import org.openconcerto.erp.core.common.ui.TotalCalculator;
19
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
20
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
21
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
22
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
23
import org.openconcerto.erp.core.sales.pos.io.TicketPrinter;
24
import org.openconcerto.erp.core.sales.pos.model.Article;
25
import org.openconcerto.erp.core.sales.pos.model.Paiement;
26
import org.openconcerto.erp.core.sales.pos.model.ReceiptCode;
27
import org.openconcerto.erp.core.sales.pos.model.Ticket;
28
import org.openconcerto.erp.core.sales.pos.model.TicketLine;
29
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
30
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
31
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
32
import org.openconcerto.erp.generationEcritures.GenerationMvtTicketCaisse;
33
import org.openconcerto.erp.generationEcritures.GenerationMvtVirement;
34
import org.openconcerto.erp.generationEcritures.GenerationReglementVenteNG;
35
import org.openconcerto.erp.model.PrixTTC;
36
import org.openconcerto.erp.preferences.DefaultNXProps;
37
import org.openconcerto.sql.Configuration;
38
import org.openconcerto.sql.element.SQLElement;
39
import org.openconcerto.sql.model.SQLBase;
40
import org.openconcerto.sql.model.SQLRow;
41
import org.openconcerto.sql.model.SQLRowAccessor;
42
import org.openconcerto.sql.model.SQLRowValues;
43
import org.openconcerto.sql.model.SQLSelect;
44
import org.openconcerto.sql.model.SQLSelectHandlerBuilder;
45
import org.openconcerto.sql.model.SQLTable;
46
import org.openconcerto.sql.model.Where;
47
import org.openconcerto.sql.users.UserManager;
48
import org.openconcerto.sql.utils.SQLUtils;
49
import org.openconcerto.utils.DecimalUtils;
50
import org.openconcerto.utils.DesktopEnvironment;
51
import org.openconcerto.utils.ExceptionHandler;
52
import org.openconcerto.utils.Pair;
53
import org.openconcerto.utils.i18n.TranslationManager;
54
 
55
import java.io.File;
56
import java.io.FileOutputStream;
57
import java.io.IOException;
58
import java.math.BigDecimal;
59
import java.math.RoundingMode;
60
import java.sql.SQLException;
61
import java.util.ArrayList;
62
import java.util.Date;
63
import java.util.List;
64
import java.util.Locale;
65
 
66
import javax.swing.JFrame;
67
import javax.swing.JOptionPane;
68
import javax.swing.SwingUtilities;
69
 
70
import org.jdom2.Document;
71
import org.jdom2.Element;
72
import org.jdom2.input.SAXBuilder;
73
import org.jdom2.output.Format;
74
import org.jdom2.output.XMLOutputter;
75
 
76
public class POSConfiguration {
77
    private static final String POS_CONFIGURATION_FILENAME = "pos.xml";
78
    private static POSConfiguration instance;
79
    private int screenWidth, screenHeight;
80
    private TicketPrinterConfiguration ticketPrinterConf1, ticketPrinterConf2;
81
    private int userID = 2;
82
    private int companyID = 42;
83
    private int posID = 2;
84
    private int scanDelay = 80;
85
 
86
    private List<TicketLine> headerLines = new ArrayList<TicketLine>();
87
    private List<TicketLine> footerLines = new ArrayList<TicketLine>();
88
    // Terminal CB
89
    private String creditCardPort = "";
90
    // LCD
91
    private String LCDSerialPort = "";
92
    private String LCDLine1 = "Bienvenue";
93
    private String LCDLine2 = "ILM Informatique";
94
 
95
    public static synchronized POSConfiguration getInstance() {
96
        if (instance == null) {
97
            instance = new POSConfiguration();
98
            instance.loadConfiguration();
99
        }
100
        return instance;
101
    }
102
 
103
    private POSConfiguration() {
104
        ticketPrinterConf1 = new TicketPrinterConfiguration();
105
        ticketPrinterConf2 = new TicketPrinterConfiguration();
106
        // Desactivate second printer by default
107
        ticketPrinterConf2.setCopyCount(0);
108
    }
109
 
110
    public TicketPrinterConfiguration getTicketPrinterConfiguration1() {
111
        return ticketPrinterConf1;
112
    }
113
 
114
    public TicketPrinterConfiguration getTicketPrinterConfiguration2() {
115
        return ticketPrinterConf2;
116
    }
117
 
118
    public boolean isConfigurationFileCreated() {
119
        File file = getConfigFile();
120
        if (file == null) {
121
            return false;
122
        }
123
        return file.exists();
124
    }
125
 
126
    // Screen
127
    public int getScreenWidth() {
128
        return screenWidth;
129
    }
130
 
131
    public int getScreenHeight() {
132
        return screenHeight;
133
    }
134
 
135
    // Database connection
136
    public int getUserID() {
137
        return userID;
138
    }
139
 
140
    public void setUserID(int userID) {
141
        this.userID = userID;
142
    }
143
 
144
    public int getCompanyID() {
145
        return companyID;
146
    }
147
 
148
    public void setCompanyID(int companyID) {
149
        this.companyID = companyID;
150
    }
151
 
152
    // POS id
153
    public int getPosID() {
154
        return posID;
155
    }
156
 
157
    public void setPosID(int posID) {
158
        this.posID = posID;
159
    }
160
 
161
    public int getScanDelay() {
162
        return scanDelay;
163
    }
164
 
165
    /**
166
     * Set barcode scanner delay
167
     */
168
    public void setScanDelay(int ms) {
169
        this.scanDelay = ms;
170
    }
171
 
172
    public String getCreditCardPort() {
173
        return creditCardPort;
174
    }
175
 
176
    /**
177
     * Set the serial port of the credit card device
178
     */
179
    public void setCreditCardPort(String creditCardPort) {
180
        this.creditCardPort = creditCardPort;
181
    }
182
 
183
    public static File getConfigFile(final String appName, final File wd) {
184
        final File wdFile = new File(wd + "/Configuration", POS_CONFIGURATION_FILENAME);
185
        final File confFile;
186
        if (wdFile.isFile()) {
187
            confFile = wdFile;
188
        } else {
189
            final File preferencesFolder = DesktopEnvironment.getDE().getPreferencesFolder(appName);
190
            if (!preferencesFolder.exists()) {
191
                preferencesFolder.mkdir();
192
            }
193
            confFile = new File(preferencesFolder, POS_CONFIGURATION_FILENAME);
194
        }
195
        return confFile;
196
    }
197
 
198
    public static File getConfigFile() {
199
        return getConfigFile(ComptaPropsConfiguration.APP_NAME, new File("."));
200
    }
201
 
202
    public void createConnexion() {
203
        final ComptaPropsConfiguration conf = ComptaPropsConfiguration.create();
204
        TranslationManager.getInstance().addTranslationStreamFromClass(MainFrame.class);
205
        TranslationManager.getInstance().setLocale(Locale.getDefault());
206
 
207
        Configuration.setInstance(conf);
208
        try {
209
            conf.getBase();
210
        } catch (Exception e) {
211
            e.printStackTrace();
212
        }
213
 
214
        try {
215
            UserManager.getInstance().setCurrentUser(getUserID());
216
            final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
217
            comptaPropsConfiguration.setUpSocieteDataBaseConnexion(getCompanyID());
218
        } catch (Exception e) {
219
            JOptionPane.showMessageDialog(new JFrame(), "Impossible de configurer la connexion à la base de donnée.\n ID société: " + getCompanyID() + " \n ID utilisateur: " + getUserID());
220
            e.printStackTrace();
221
            System.exit(2);
222
        }
223
    }
224
 
225
    public void commitAll(final List<Ticket> tickets) {
226
        // createConnexion();
227
        try {
228
            SQLUtils.executeAtomic(Configuration.getInstance().getSystemRoot().getDataSource(), new SQLUtils.SQLFactory<Object>() {
229
                @Override
230
                public Object create() throws SQLException {
231
                    SQLElement elt = Configuration.getInstance().getDirectory().getElement("TICKET_CAISSE");
232
                    SQLElement eltFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
233
                    SQLElement eltEnc = Configuration.getInstance().getDirectory().getElement("ENCAISSER_MONTANT");
234
                    SQLElement eltMode = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
235
                    SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("ARTICLE");
236
                    int imported = 0;
237
                    for (Ticket ticket : tickets) {
238
                        SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
239
                        sel.addSelect(elt.getTable().getField("NUMERO"));
240
                        sel.setWhere(new Where(elt.getTable().getField("NUMERO"), "=", ticket.getCode()));
241
                        List<?> l = Configuration.getInstance().getBase().getDataSource().executeCol(sel.asString());
242
                        if (l != null && l.size() == 0) {
243
 
244
                            SQLRowValues rowVals = new SQLRowValues(elt.getTable());
245
                            rowVals.put("NUMERO", ticket.getCode());
246
                            rowVals.put("DATE", ticket.getCreationDate());
247
                            rowVals.put("ID_CAISSE", getPosID());
248
 
249
                            TotalCalculator calc = new TotalCalculator("T_PA_HT", "T_PV_HT", null);
250
 
251
                            String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
252
                            Boolean bServiceActive = Boolean.valueOf(val);
253
                            calc.setServiceActive(bServiceActive != null && bServiceActive);
254
 
255
                            // Articles
256
                            for (Pair<Article, Integer> item : ticket.getArticles()) {
257
                                SQLRowValues rowValsElt = new SQLRowValues(eltFact.getTable());
258
                                final Article article = item.getFirst();
259
                                final Integer nb = item.getSecond();
260
                                rowValsElt.put("QTE", nb);
261
                                rowValsElt.put("PV_HT", article.getPriceWithoutTax());
262
                                Float tauxFromId = TaxeCache.getCache().getTauxFromId(article.getIdTaxe());
263
                                BigDecimal tauxTVA = new BigDecimal(tauxFromId).movePointLeft(2).add(BigDecimal.ONE);
264
 
265
                                final BigDecimal valueHT = article.getPriceWithoutTax().multiply(new BigDecimal(nb), DecimalUtils.HIGH_PRECISION);
266
 
267
                                rowValsElt.put("T_PV_HT", valueHT);
268
                                rowValsElt.put("T_PV_TTC", valueHT.multiply(tauxTVA, DecimalUtils.HIGH_PRECISION));
269
                                rowValsElt.put("ID_TAXE", article.getIdTaxe());
270
                                rowValsElt.put("CODE", article.getCode());
271
                                rowValsElt.put("NOM", article.getName());
272
                                rowValsElt.put("ID_TICKET_CAISSE", rowVals);
273
                                rowValsElt.put("ID_ARTICLE", article.getId());
274
                                calc.addLine(rowValsElt, eltArticle.getTable().getRow(article.getId()), 0, false);
275
                            }
276
                            calc.checkResult();
277
                            long longValueTotalHT = calc.getTotalHT().movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue();
278
                            rowVals.put("TOTAL_HT", longValueTotalHT);
279
 
280
                            long longValueTotal = calc.getTotalTTC().movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue();
281
                            rowVals.put("TOTAL_TTC", longValueTotal);
282
                            long longValueTotalTVA = calc.getTotalTVA().movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue();
283
                            rowVals.put("TOTAL_TVA", longValueTotalTVA);
284
 
285
                            // Paiements
286
                            for (Paiement paiement : ticket.getPaiements()) {
287
                                if (paiement.getMontantInCents() > 0) {
288
                                    SQLRowValues rowValsElt = new SQLRowValues(eltEnc.getTable());
289
                                    SQLRowValues rowValsEltMode = new SQLRowValues(eltMode.getTable());
290
                                    if (paiement.getType() == Paiement.CB) {
291
                                        rowValsEltMode.put("ID_TYPE_REGLEMENT", TypeReglementSQLElement.CB);
292
                                    } else if (paiement.getType() == Paiement.CHEQUE) {
293
                                        rowValsEltMode.put("ID_TYPE_REGLEMENT", TypeReglementSQLElement.CHEQUE);
294
                                    } else if (paiement.getType() == Paiement.ESPECES) {
295
                                        rowValsEltMode.put("ID_TYPE_REGLEMENT", TypeReglementSQLElement.ESPECE);
296
                                    }
297
 
298
                                    rowValsElt.put("ID_MODE_REGLEMENT", rowValsEltMode);
299
                                    try {
300
                                        rowValsElt.put("ID_CLIENT", getClientCaisse().getID());
301
                                    } catch (SQLException e) {
302
                                        e.printStackTrace();
303
                                    }
304
                                    long montant = Long.valueOf(paiement.getMontantInCents());
305
                                    if (ticket.getPaiements().size() == 1 && paiement.getType() == Paiement.ESPECES) {
306
                                        montant = longValueTotal;
307
                                    }
308
                                    rowValsElt.put("MONTANT", montant);
309
                                    rowValsElt.put("NOM", "Ticket " + ticket.getCode());
310
                                    rowValsElt.put("DATE", ticket.getCreationDate());
311
                                    rowValsElt.put("ID_TICKET_CAISSE", rowVals);
312
                                }
313
                            }
314
 
315
                            SQLRow rowFinal = rowVals.insert();
316
                            imported++;
317
                            GenerationMvtTicketCaisse mvt = new GenerationMvtTicketCaisse(rowFinal);
318
                            final Integer idMvt;
319
                            try {
320
                                idMvt = mvt.genereMouvement().call();
321
 
322
                                SQLRowValues valTicket = rowFinal.asRowValues();
323
                                valTicket.put("ID_MOUVEMENT", Integer.valueOf(idMvt));
324
                                rowFinal = valTicket.update();
325
 
326
                                // msie à jour du mouvement
327
                                List<SQLRow> rowsEnc = rowFinal.getReferentRows(eltEnc.getTable());
328
                                long totalEnc = 0;
329
                                for (SQLRow sqlRow : rowsEnc) {
330
                                    long montant = sqlRow.getLong("MONTANT");
331
                                    PrixTTC ttc = new PrixTTC(montant);
332
                                    totalEnc += montant;
333
                                    new GenerationReglementVenteNG(
334
                                            "Règlement " + sqlRow.getForeignRow("ID_MODE_REGLEMENT").getForeignRow("ID_TYPE_REGLEMENT").getString("NOM") + " Ticket " + rowFinal.getString("NUMERO"),
335
                                            getClientCaisse(), ttc, sqlRow.getDate("DATE").getTime(), sqlRow.getForeignRow("ID_MODE_REGLEMENT"), rowFinal, rowFinal.getForeignRow("ID_MOUVEMENT"),
336
                                            false);
337
                                }
338
                                if (totalEnc > longValueTotal) {
339
                                    final SQLTable table = Configuration.getInstance().getDirectory().getElement("TYPE_REGLEMENT").getTable();
340
                                    int idComptePceCaisse = table.getRow(TypeReglementSQLElement.ESPECE).getInt("ID_COMPTE_PCE_CLIENT");
341
                                    if (idComptePceCaisse == table.getUndefinedID()) {
342
                                        idComptePceCaisse = ComptePCESQLElement.getId(ComptePCESQLElement.getComptePceDefault("VenteEspece"));
343
                                    }
344
                                    new GenerationMvtVirement(idComptePceCaisse, getClientCaisse().getInt("ID_COMPTE_PCE"), 0, totalEnc - longValueTotal,
345
                                            "Rendu sur règlement " + " Ticket " + rowFinal.getString("NUMERO"), new Date(), JournalSQLElement.CAISSES, " Ticket " + rowFinal.getString("NUMERO"))
346
                                                    .genereMouvement();
347
                                }
348
                            } catch (Exception exn) {
349
                                exn.printStackTrace();
350
                                throw new SQLException(exn);
351
                            }
352
                            updateStock(rowFinal.getID());
353
 
354
                        }
355
                    }
356
                    // mark imported
357
                    for (Ticket ticket : tickets) {
358
                        final ReceiptCode code = ticket.getReceiptCode();
359
                        try {
360
                            // it's OK if some files cannot be moved, the next call will try again
361
                            // (the above code doesn't import duplicates)
362
                            code.markImported();
363
                        } catch (IOException e) {
364
                            e.printStackTrace();
365
                        }
366
                    }
367
                    // archive to avoid parsing more and more receipts
368
                    try {
369
                        // it's OK if some files cannot be moved, the next call will try again
370
                        ReceiptCode.archiveCompletelyImported();
371
                    } catch (IOException e) {
372
                        e.printStackTrace();
373
                    }
374
                    final String count = imported + "/" + tickets.size();
375
                    SwingUtilities.invokeLater(new Runnable() {
376
 
377
                        @Override
378
                        public void run() {
379
                            JOptionPane.showMessageDialog(null, count + " ticket(s) importé(s). Clôture de la caisse terminée.");
380
                        }
381
                    });
382
                    return null;
383
                }
384
            });
385
        } catch (Exception exn) {
386
            ExceptionHandler.handle("Une erreur est survenue pendant la clôture.", exn);
387
        }
388
 
389
    }
390
 
391
    private SQLRow rowClient = null;
392
 
393
    private SQLRow getClientCaisse() throws SQLException {
394
        if (rowClient == null) {
395
            SQLElement elt = Configuration.getInstance().getDirectory().getElement("CLIENT");
396
            SQLSelect sel = new SQLSelect();
397
            sel.addSelectStar(elt.getTable());
398
            sel.setWhere(new Where(elt.getTable().getField("NOM"), "=", "Caisse OpenConcerto"));
399
            @SuppressWarnings("unchecked")
400
            List<SQLRow> l = (List<SQLRow>) elt.getTable().getBase().getDataSource().execute(sel.asString(), new SQLSelectHandlerBuilder(sel).createHandler());
401
            if (l.size() > 0) {
402
                rowClient = l.get(0);
403
            } else {
404
                SQLRowValues rowValues = new SQLRowValues(elt.getTable());
405
                rowValues.put("NOM", "Caisse OpenConcerto");
406
                SQLRowValues rowValuesMode = new SQLRowValues(elt.getTable().getTable("MODE_REGLEMENT"));
407
                rowValuesMode.put("ID_TYPE_REGLEMENT", TypeReglementSQLElement.CB);
408
                rowValues.put("ID_MODE_REGLEMENT", rowValuesMode);
409
 
410
                // Select Compte client par defaut
411
                final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
412
                final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
413
                final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
414
 
415
                int idDefaultCompteClient = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT");
416
                if (idDefaultCompteClient <= 1) {
417
                    try {
418
                        idDefaultCompteClient = ComptePCESQLElement.getIdComptePceDefault("Clients");
419
                    } catch (Exception e) {
420
                        e.printStackTrace();
421
                    }
422
                }
423
 
424
                rowValues.put("ID_COMPTE_PCE", idDefaultCompteClient);
425
                rowClient = rowValues.insert();
426
            }
427
        }
428
        return rowClient;
429
 
430
    }
431
 
432
    private void updateStock(int id) throws SQLException {
433
        final SQLRow row = getClientCaisse().getTable().getTable("TICKET_CAISSE").getRow(id);
434
        StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
435
            @Override
436
            public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
437
                return "Ticket N°" + rowOrigin.getString("NUMERO");
438
            }
439
        }, row, row.getReferentRows(getClientCaisse().getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT")), TypeStockUpdate.REAL_DELIVER);
440
        stockUpdater.update();
441
    }
442
 
443
    public List<Ticket> allTickets() {
444
        final List<Ticket> l = new ArrayList<Ticket>();
445
        for (final File f : ReceiptCode.getReceiptsToImport(getPosID())) {
446
            final Ticket ticket = Ticket.parseFile(f);
447
            if (ticket != null) {
448
                l.add(ticket);
449
            }
450
        }
451
        return l;
452
    }
453
 
454
    public List<TicketLine> getHeaderLines() {
455
        return headerLines;
456
    }
457
 
458
    public void setHeaderLines(List<TicketLine> headerLines) {
459
        this.headerLines = headerLines;
460
    }
461
 
462
    public List<TicketLine> getFooterLines() {
463
        return footerLines;
464
    }
465
 
466
    public void setFooterLines(List<TicketLine> footerLines) {
467
        this.footerLines = footerLines;
468
    }
469
 
470
    private void loadConfiguration() {
471
        if (!isConfigurationFileCreated()) {
472
            System.err.println("POSConfiguration.loadConfigurationFromXML() configuration not loaded. " + getConfigFile().getAbsolutePath() + " missing.");
473
            return;
474
        }
475
 
476
        final SAXBuilder builder = new SAXBuilder();
477
        File file = getConfigFile();
478
 
479
        try {
480
            System.out.println("POSConfiguration.loadConfigurationFromXML() loading " + file.getAbsolutePath());
481
            Document document = builder.build(file);
482
            // config
483
            final Element rootElement = document.getRootElement();
484
            setUserID(Integer.valueOf(rootElement.getAttributeValue("userID", "2")));
485
            setCompanyID(Integer.valueOf(rootElement.getAttributeValue("societeID", "42")));
486
            setPosID(Integer.valueOf(rootElement.getAttributeValue("caisseID", "2")));
487
            setScanDelay(Integer.valueOf(rootElement.getAttributeValue("scanDelay", "80")));
488
            // screen
489
            final List<Element> children = rootElement.getChildren("screen");
490
            if (children != null) {
491
                for (Element e : children) {
492
                    this.screenWidth = Integer.valueOf(e.getAttributeValue("width", "0"));
493
                    this.screenHeight = Integer.valueOf(e.getAttributeValue("height", "0"));
494
                }
495
            }
496
            // credit card
497
            final List<Element> childrenCreditCard = rootElement.getChildren("creditcard");
498
            if (childrenCreditCard != null) {
499
                for (Element e : childrenCreditCard) {
500
                    this.creditCardPort = e.getAttributeValue("port", "");
501
                }
502
            }
503
            // credit card
504
            final List<Element> childrenLCD = rootElement.getChildren("lcd");
505
            if (childrenLCD != null) {
506
                for (Element e : childrenLCD) {
507
                    this.LCDSerialPort = e.getAttributeValue("port", "");
508
                    this.LCDLine1 = e.getAttributeValue("line1", "");
509
                    this.LCDLine2 = e.getAttributeValue("line2", "");
510
                }
511
            }
512
 
513
            // header
514
            final List<Element> headers = rootElement.getChildren("header");
515
            if (headers != null) {
516
                for (Element header : headers) {
517
                    this.headerLines.add(new TicketLine(header.getValue(), header.getAttributeValue("style")));
518
                }
519
            }
520
            // footer
521
            final List<Element> footers = rootElement.getChildren("footer");
522
            if (footers != null) {
523
                for (Element header : footers) {
524
                    this.footerLines.add(new TicketLine(header.getValue(), header.getAttributeValue("style")));
525
                }
526
            }
527
            // ticket printers
528
            final List<Element> printers = rootElement.getChildren("ticketPrinter");
529
            if (printers.size() > 0) {
530
                configureTicketPrinter(this.ticketPrinterConf1, printers.get(0));
531
            }
532
            if (printers.size() > 1) {
533
                configureTicketPrinter(this.ticketPrinterConf2, printers.get(1));
534
            }
535
        } catch (Exception e) {
536
            e.printStackTrace();
537
        }
538
 
539
    }
540
 
541
    private void configureTicketPrinter(TicketPrinterConfiguration conf, Element element) {
542
        conf.setType(element.getAttributeValue("type"));
543
        conf.setName(element.getAttributeValue("name"));
544
        conf.setCopyCount(Integer.parseInt(element.getAttributeValue("copyCount")));
545
        conf.setTicketWidth(Integer.parseInt(element.getAttributeValue("ticketWidth")));
546
        conf.setFolder(element.getAttributeValue("folder", ""));
547
    }
548
 
549
    private Element getElementFromConfiguration(TicketPrinterConfiguration conf) {
550
        final Element element = new Element("ticketPrinter");
551
        element.setAttribute("type", conf.getType());
552
        element.setAttribute("name", conf.getName());
553
        element.setAttribute("copyCount", String.valueOf(conf.getCopyCount()));
554
        element.setAttribute("ticketWidth", String.valueOf(conf.getTicketWidth()));
555
        element.setAttribute("folder", conf.getFolder());
556
        return element;
557
    }
558
 
559
    public void saveConfiguration() {
560
        final File file = getConfigFile();
561
        final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
562
        try {
563
            System.out.println("Saving:" + file.getAbsolutePath());
564
            final FileOutputStream fileOutputStream = new FileOutputStream(file);
565
            final Document doc = new Document();
566
            final Element configElement = new Element("config");
567
            configElement.setAttribute("userID", String.valueOf(this.userID));
568
            configElement.setAttribute("societeID", String.valueOf(this.companyID));
569
            configElement.setAttribute("caisseID", String.valueOf(this.posID));
570
            configElement.setAttribute("scanDelay", String.valueOf(this.scanDelay));
571
            doc.addContent(configElement);
572
            // screen size
573
            final Element screenElement = new Element("screen");
574
            screenElement.setAttribute("width", String.valueOf(this.screenWidth));
575
            screenElement.setAttribute("height", String.valueOf(this.screenHeight));
576
            configElement.addContent(screenElement);
577
            // credit card
578
            final Element creditCardElement = new Element("creditcard");
579
            creditCardElement.setAttribute("port", this.creditCardPort);
580
            configElement.addContent(creditCardElement);
581
            // LCD
582
            final Element lcdElement = new Element("lcd");
583
            lcdElement.setAttribute("port", this.LCDSerialPort);
584
            lcdElement.setAttribute("line1", this.LCDLine1);
585
            lcdElement.setAttribute("line2", this.LCDLine2);
586
            configElement.addContent(lcdElement);
587
 
588
            // header
589
            for (TicketLine line : this.headerLines) {
590
                Element e = new Element("header");
591
                final String style = line.getStyle();
592
                if (style != null && !style.isEmpty()) {
593
                    e.setAttribute("style", style);
594
                }
595
                e.setText(line.getText());
596
                configElement.addContent(e);
597
            }
598
            // footer
599
            for (TicketLine line : this.footerLines) {
600
                Element e = new Element("footer");
601
                final String style = line.getStyle();
602
                if (style != null && !style.isEmpty()) {
603
                    e.setAttribute("style", style);
604
                }
605
                e.setText(line.getText());
606
                configElement.addContent(e);
607
            }
608
            // ticket printer
609
            configElement.addContent(getElementFromConfiguration(this.ticketPrinterConf1));
610
            configElement.addContent(getElementFromConfiguration(this.ticketPrinterConf2));
611
            outputter.output(doc, fileOutputStream);
612
            fileOutputStream.close();
613
        } catch (Exception e) {
614
            e.printStackTrace();
615
            ExceptionHandler.handle("Erreur lors de la sauvegarde de la configuration de la caisse.\n" + file.getAbsolutePath());
616
        }
617
 
618
    }
619
 
620
    public void print(Ticket ticket) {
621
        print(ticket, this.ticketPrinterConf1);
622
        print(ticket, this.ticketPrinterConf2);
623
    }
624
 
625
    public void print(Ticket ticket, TicketPrinterConfiguration conf) {
626
        if (conf.isValid() && conf.getCopyCount() > 0) {
627
            final TicketPrinter prt = conf.createTicketPrinter();
628
            for (int i = 0; i < conf.getCopyCount(); i++) {
629
                ticket.print(prt, conf.getTicketWidth());
630
            }
631
        }
632
    }
633
 
634
    public boolean isUsingJPos() {
635
        // TODO Auto-generated method stub
636
        return false;
637
    }
638
 
639
    public List<String> getJPosDirectories() {// TODO Auto-generated method stub
640
        final ArrayList<String> result = new ArrayList<String>();
641
        return result;
642
    }
643
 
644
    public String getLCDSerialPort() {
645
        return LCDSerialPort;
646
    }
647
 
648
    public void setLCDSerialPort(String port) {
649
        this.LCDSerialPort = port;
650
    }
651
 
652
    public String getLCDLine1() {
653
        return this.LCDLine1;
654
    }
655
 
656
    public void setLCDLine1(String text) {
657
        this.LCDLine1 = text;
658
    }
659
 
660
    public String getLCDLine2() {
661
        return this.LCDLine2;
662
    }
663
 
664
    public void setLCDLine2(String text) {
665
        this.LCDLine2 = text;
666
    }
667
 
668
}