OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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