OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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