OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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