OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.generationEcritures;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
83 ilm 17
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
151 ilm 18
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
67 ilm 19
import org.openconcerto.erp.core.common.ui.TotalCalculator;
83 ilm 20
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
21
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
156 ilm 22
import org.openconcerto.erp.generationDoc.OOXMLCache;
83 ilm 23
import org.openconcerto.erp.generationEcritures.provider.AnalytiqueProvider;
24
import org.openconcerto.erp.generationEcritures.provider.AnalytiqueProviderManager;
73 ilm 25
import org.openconcerto.erp.preferences.DefaultNXProps;
80 ilm 26
import org.openconcerto.erp.preferences.GestionPieceCommercialePanel;
18 ilm 27
import org.openconcerto.sql.Configuration;
151 ilm 28
import org.openconcerto.sql.element.SQLElement;
29
import org.openconcerto.sql.model.SQLBackgroundTableCache;
156 ilm 30
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
18 ilm 31
import org.openconcerto.sql.model.SQLBase;
32
import org.openconcerto.sql.model.SQLRow;
90 ilm 33
import org.openconcerto.sql.model.SQLRowAccessor;
151 ilm 34
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 35
import org.openconcerto.sql.model.SQLRowValues;
156 ilm 36
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
18 ilm 37
import org.openconcerto.sql.model.SQLSelect;
38
import org.openconcerto.sql.model.SQLTable;
151 ilm 39
import org.openconcerto.sql.model.Where;
18 ilm 40
import org.openconcerto.sql.users.UserManager;
41
import org.openconcerto.utils.ExceptionHandler;
42
 
61 ilm 43
import java.math.BigDecimal;
142 ilm 44
import java.math.RoundingMode;
18 ilm 45
import java.sql.SQLException;
156 ilm 46
import java.util.Arrays;
83 ilm 47
import java.util.Collection;
18 ilm 48
import java.util.Date;
49
import java.util.HashMap;
50
import java.util.List;
51
import java.util.Map;
52
 
80 ilm 53
import javax.swing.JOptionPane;
18 ilm 54
import javax.swing.SwingUtilities;
55
 
149 ilm 56
import com.ibm.icu.text.SimpleDateFormat;
57
 
18 ilm 58
/**
59
 * Generation des ecritures comptables, permet l'ajout d'ecriture, la creation des mouvements
60
 *
61
 * @author Administrateur
62
 *
63
 */
64
public class GenerationEcritures {
65
 
66
    protected static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
67 ilm 67
    protected static final SQLTable compteTable = base.getTable("COMPTE_PCE");
68
    protected static final SQLTable journalTable = base.getTable("JOURNAL");
69
    protected static final SQLTable ecritureTable = base.getTable("ECRITURE");
70
    protected static final SQLTable pieceTable = base.getTable("PIECE");
80 ilm 71
    protected static final SQLTable mouvementTable = base.getTable("MOUVEMENT");
18 ilm 72
 
73
    protected int idMvt;
74
    protected int idPiece;
75
 
76
    // Date d'ecriture
77
    protected Date date;
78
 
79
    // Libelle de l'ecriture
80
    protected String nom;
81
 
93 ilm 82
    private SQLRow rowAnalytiqueSource;
83
 
18 ilm 84
    // Map contenant les valeurs pour la SQLRowValues de la table Ecritures à ajouter
149 ilm 85
    protected final Map<String, Object> mEcritures = new HashMap<String, Object>();
18 ilm 86
 
149 ilm 87
    public void putValue(String field, Object value) {
88
        mEcritures.put(field, value);
89
    }
93 ilm 90
 
91
    public void setRowAnalytiqueSource(SQLRow rowAnalytiqueSource) {
92
        this.rowAnalytiqueSource = rowAnalytiqueSource;
93
    }
94
 
95
    public SQLRow getRowAnalytiqueSource() {
96
        return this.rowAnalytiqueSource;
97
    }
98
 
156 ilm 99
    private Date dDebEx = null;
100
    private Date dCloture = null;
101
 
18 ilm 102
    /**
103
     * Ajout d'une écriture et maj des totaux du compte associé
104
     *
105
     * @return Id de l'ecriture crée
106
     * @throws IllegalArgumentException
107
     */
83 ilm 108
    synchronized public SQLRow ajoutEcriture() throws IllegalArgumentException {
18 ilm 109
 
110
        long debit = ((Long) this.mEcritures.get("DEBIT")).longValue();
111
        long credit = ((Long) this.mEcritures.get("CREDIT")).longValue();
112
 
113
        // Report des valeurs pour accelerer les IListes
114
        Number n = (Number) this.mEcritures.get("ID_JOURNAL");
115
        if (n != null) {
156 ilm 116
            final SQLBackgroundTableCacheItem cacheForTableJrnl = SQLBackgroundTableCache.getInstance().getCacheForTable(journalTable);
117
            SQLRow rowJrnl = cacheForTableJrnl.getRowFromId(n.intValue());
83 ilm 118
            if (rowJrnl == null) {
119
                throw new IllegalArgumentException("Le journal qui a pour ID " + n + " a été archivé.");
120
            }
18 ilm 121
            this.mEcritures.put("JOURNAL_NOM", rowJrnl.getString("NOM"));
122
            this.mEcritures.put("JOURNAL_CODE", rowJrnl.getString("CODE"));
123
        }
124
 
125
        Number n2 = (Number) this.mEcritures.get("ID_COMPTE_PCE");
126
        if (n2 != null) {
156 ilm 127
            final SQLBackgroundTableCacheItem cacheForTableCpt = SQLBackgroundTableCache.getInstance().getCacheForTable(compteTable);
128
            SQLRow rowCpt = cacheForTableCpt.getRowFromId(n2.intValue());
129
            if (rowCpt == null) {
130
                rowCpt = compteTable.getRow(n2.intValue());
131
            }
18 ilm 132
            this.mEcritures.put("COMPTE_NUMERO", rowCpt.getString("NUMERO"));
133
            this.mEcritures.put("COMPTE_NOM", rowCpt.getString("NOM"));
134
        }
135
 
136
        if (debit != 0 && credit != 0) {
137
            // ExceptionHandler.handle("Le débit et le crédit ne peuvent pas être tous les 2
138
            // différents de 0. Debit : " + debit + " Credit : " + credit);
139
            throw new IllegalArgumentException("Le débit et le crédit ne peuvent pas être tous les 2 différents de 0. Debit : " + debit + " Credit : " + credit);
140
            // return -1;
141
        }
142
 
143
        if (debit < 0) {
144
            credit = -debit;
145
            debit = 0;
146
        }
147
        if (credit < 0) {
148
            debit = -credit;
149
            credit = 0;
150
        }
151
 
152
        this.mEcritures.put("DEBIT", Long.valueOf(debit));
153
        this.mEcritures.put("CREDIT", Long.valueOf(credit));
154
 
155
        // TODO checker que les ecritures sont entrees à une date correcte
156
        Date d = (Date) this.mEcritures.get("DATE");
157
 
156 ilm 158
        if (this.dDebEx == null) {
159
            SQLTable tableExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON");
160
            SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
161
            SQLRow rowExercice = tableExercice.getRow(rowSociete.getInt("ID_EXERCICE_COMMON"));
162
            this.dDebEx = (Date) rowExercice.getObject("DATE_DEB");
163
            this.dCloture = (Date) rowExercice.getObject("DATE_CLOTURE");
164
        }
18 ilm 165
 
166
        if (dCloture != null) {
167
            if (dCloture.after(d)) {
149 ilm 168
                final String error = "Impossible de générer l'écriture pour la date " + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(d)
156 ilm 169
                        + ". Cette date est antérieure à la date de clôture (" + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(dCloture) + ")";
149 ilm 170
                throw new IllegalArgumentException(error);
18 ilm 171
            }
172
        } else {
173
            if (dDebEx.after(d)) {
149 ilm 174
                final String error = "Impossible de générer l'écriture pour la date " + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(d)
175
                        + ". Cette date est antérieure à la date de début d'exercice (" + SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL).format(dDebEx) + ")";
176
                throw new IllegalArgumentException(error);
18 ilm 177
            }
178
        }
179
 
180
        final SQLRowValues valEcriture = new SQLRowValues(GenerationEcritures.ecritureTable, this.mEcritures);
181
        valEcriture.put("IDUSER_CREATE", UserManager.getInstance().getCurrentUser().getId());
182
 
183
        try {
156 ilm 184
            // ajout de l'ecriture
185
            // SQLRow ecritureRow = valEcriture.insert();
186
            SQLRow ecritureRow = valEcriture.getGraph().store(StoreMode.INSERT, false).getStoredRow(valEcriture);
93 ilm 187
 
156 ilm 188
            // TODO Analytique
189
            addAssocAnalytiqueFromProvider(ecritureRow, this.rowAnalytiqueSource);
190
            return ecritureRow;
191
 
18 ilm 192
        } catch (SQLException e) {
193
            System.err.println("Error insert row in " + GenerationEcritures.ecritureTable.getName() + " : " + e);
194
            final SQLException eFinal = e;
195
            SwingUtilities.invokeLater(new Runnable() {
196
                public void run() {
197
                    ExceptionHandler.handle("Erreur lors de la génération des écritures.", eFinal);
198
                }
199
            });
200
            e.printStackTrace();
201
        }
202
 
83 ilm 203
        return null;
18 ilm 204
    }
205
 
83 ilm 206
    private static SQLTable tableAssoc = null;
207
    private static SQLTable tablePoste = Configuration.getInstance().getDirectory().getElement("POSTE_ANALYTIQUE").getTable();
18 ilm 208
 
83 ilm 209
    public void addAssocAnalytique(SQLRow rowEcr, int idPoste) throws SQLException {
210
        if (tablePoste.getUndefinedID() == idPoste) {
211
            return;
212
        }
213
        if (tableAssoc == null) {
214
            tableAssoc = Configuration.getInstance().getDirectory().getElement("ASSOCIATION_ANALYTIQUE").getTable();
215
        }
216
        SQLRowValues rowVals = new SQLRowValues(tableAssoc);
217
        rowVals.put("ID_POSTE_ANALYTIQUE", idPoste);
218
        rowVals.put("POURCENT", 100.0);
219
        rowVals.put("ID_ECRITURE", rowEcr.getID());
220
        rowVals.put("MONTANT", rowEcr.getLong("DEBIT") - rowEcr.getLong("CREDIT"));
221
        rowVals.commit();
222
 
223
    }
224
 
225
    public void addAssocAnalytiqueFromProvider(SQLRow rowEcr, SQLRow rowSource) throws SQLException {
226
 
93 ilm 227
        String numeroCpt = rowEcr.getString("COMPTE_NUMERO");
228
        if (rowSource != null && !rowSource.getTable().getName().equalsIgnoreCase("SAISIE_KM") && (numeroCpt.startsWith("6") || numeroCpt.startsWith("7"))) {
229
            for (SQLRow axe : AnalytiqueCache.getCache().getAxes()) {
230
                // TODO Check if total = 100%
231
                int assoc = 0;
232
                Collection<AnalytiqueProvider> l = AnalytiqueProviderManager.getAll();
233
                for (AnalytiqueProvider analytiqueProvider : l) {
234
                    List<SQLRow> result = analytiqueProvider.addAssociation(axe, rowEcr, rowSource);
235
                    if (result != null) {
236
                        assoc += result.size();
237
                    }
238
                }
239
 
240
                if (assoc == 0) {
241
                    SQLRow poste = AnalytiqueCache.getCache().getDefaultPoste(axe.getID());
242
                    if (poste != null) {
243
                        if (tableAssoc == null) {
244
                            tableAssoc = Configuration.getInstance().getDirectory().getElement("ASSOCIATION_ANALYTIQUE").getTable();
245
                        }
246
                        SQLRowValues rowVals = new SQLRowValues(tableAssoc);
247
                        rowVals.put("ID_POSTE_ANALYTIQUE", poste.getID());
248
                        rowVals.put("POURCENT", 100.0);
249
                        rowVals.put("ID_ECRITURE", rowEcr.getID());
250
                        rowVals.put("MONTANT", rowEcr.getLong("DEBIT") - rowEcr.getLong("CREDIT"));
251
                        rowVals.put("GESTION_AUTO", Boolean.TRUE);
252
                        rowVals.commit();
253
                    }
254
                }
255
            }
83 ilm 256
        }
257
    }
258
 
18 ilm 259
    /**
260
     * Génération d'un groupe d'écritures respectant la partie double.
261
     *
262
     * @param l liste de SQLRowValues d'ecritures
263
     */
264
    public void genereEcritures(List<SQLRowValues> l) {
265
 
266
        if (l == null) {
267
            return;
268
        }
269
        try {
270
 
271
            // Test de validité des écritures
272
            for (SQLRowValues rowVals : l) {
273
                checkDateValide(rowVals);
274
                checkDebitCreditValide(rowVals);
275
            }
276
            if (isSoldeNul(l)) {
277
 
278
                for (SQLRowValues rowVals : l) {
279
 
280
                    rowVals.put("IDUSER_CREATE", UserManager.getInstance().getCurrentUser().getId());
281
 
282
                    // ajout de l'ecriture
283
                    rowVals.insert();
284
                }
285
            } else {
286
                throw new IllegalArgumentException("La partie double n'est pas respectée. Impossible de générer les écritures comptables.");
287
            }
288
        } catch (final Exception e) {
289
            e.printStackTrace();
290
            SwingUtilities.invokeLater(new Runnable() {
291
                public void run() {
292
                    // TODO Auto-generated method stub
293
                    ExceptionHandler.handle("", e);
294
                }
295
            });
296
        }
297
    }
298
 
299
    private void checkDateValide(SQLRowValues rowVals) throws Exception {
300
        Date d = (Date) rowVals.getObject("DATE");
301
 
302
        SQLTable tableExercice = Configuration.getInstance().getBase().getTable("EXERCICE_COMMON");
303
        SQLRow rowSociete = ((ComptaPropsConfiguration) Configuration.getInstance()).getRowSociete();
304
        SQLRow rowExercice = tableExercice.getRow(rowSociete.getInt("ID_EXERCICE_COMMON"));
305
        Date dDebEx = (Date) rowExercice.getObject("DATE_DEB");
306
 
307
        Date dCloture = (Date) rowExercice.getObject("DATE_CLOTURE");
308
 
309
        if (dCloture != null) {
310
            if (dCloture.after(d)) {
311
                System.err.println("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
312
                throw new Exception("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
313
                // return -1;
314
            }
315
        } else {
316
            if (dDebEx.after(d)) {
317
                System.err.println("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
318
                throw new Exception("Impossible de générer l'écriture pour la date " + d + ". Cette période est cloturée.");
319
            }
320
        }
321
    }
322
 
323
    private void checkDebitCreditValide(SQLRowValues rowVals) throws Exception {
324
        long debit = rowVals.getLong("DEBIT");
325
        long credit = rowVals.getLong("CREDIT");
326
 
327
        if (debit != 0 && credit != 0) {
328
            // ExceptionHandler.handle("Le débit et le crédit ne peuvent pas être tous les 2
329
            // différents de 0. Debit : " + debit + " Credit : " + credit);
330
            throw new Exception("Le débit et le crédit ne peuvent pas être tous les 2 différents de 0. Debit : " + debit + " Credit : " + credit);
331
            // return -1;
332
        }
333
 
334
        if (debit < 0) {
335
            credit = -debit;
336
            debit = 0;
337
        }
338
        if (credit < 0) {
339
            debit = -credit;
340
            credit = 0;
341
        }
342
 
343
        rowVals.put("DEBIT", Long.valueOf(debit));
344
        rowVals.put("CREDIT", Long.valueOf(credit));
345
    }
346
 
347
    private boolean isSoldeNul(List<SQLRowValues> l) {
348
 
349
        long debit = 0;
350
        long credit = 0;
351
        for (SQLRowValues rowVals : l) {
352
            debit += rowVals.getLong("DEBIT");
353
            credit += rowVals.getLong("CREDIT");
354
        }
355
        return (debit - credit == 0);
356
    }
357
 
358
    /**
359
     * Crée un mouvement et une nouvelle piecé associée
360
     *
361
     * @param source
362
     * @param idSource
363
     * @param idPere
364
     * @param nomPiece
365
     * @return id d'un nouveau mouvement
73 ilm 366
     * @throws SQLException
18 ilm 367
     */
73 ilm 368
    synchronized public int getNewMouvement(String source, int idSource, int idPere, SQLRowValues rowValsPiece) throws SQLException {
369
        SQLRow rowPiece = rowValsPiece.insert();
370
        return getNewMouvement(source, idSource, idPere, rowPiece.getID());
18 ilm 371
 
372
    }
373
 
73 ilm 374
    synchronized public int getNewMouvement(String source, int idSource, int idPere, String nomPiece) throws SQLException {
67 ilm 375
 
376
        SQLRowValues rowValsPiece = new SQLRowValues(pieceTable);
377
        rowValsPiece.put("NOM", nomPiece);
378
        return getNewMouvement(source, idSource, idPere, rowValsPiece);
379
    }
380
 
156 ilm 381
    protected TotalCalculator getValuesFromElement(SQLRow row, SQLTable foreign, BigDecimal portHT, SQLRow rowTVAPort, BigDecimal fraisDocHT, SQLRow rowTVAFraisDoc, SQLTable tableEchantillon) {
382
        return getValuesFromElement(false, false, "T_PV_HT", row, foreign, portHT, rowTVAPort, fraisDocHT, rowTVAFraisDoc, tableEchantillon, null);
80 ilm 383
    }
67 ilm 384
 
156 ilm 385
    protected TotalCalculator getValuesFromElement(boolean intra, boolean achat, String fieldTotalHT, SQLRow row, SQLTable foreign, BigDecimal portHT, SQLRow rowTVAPort, BigDecimal fraisDocHT,
386
            SQLRow rowTVAFraisDoc, SQLTable tableEchantillon, SQLRow defaultCompte) {
80 ilm 387
 
156 ilm 388
        final SQLRow tiers;
389
        if (achat) {
390
            tiers = row.getForeign("ID_FOURNISSEUR");
391
        } else {
392
            tiers = row.getForeign("ID_CLIENT");
393
        }
394
 
395
        SQLRowAccessor rowCatCompta = null;
396
        if (tiers.getObject("ID_CATEGORIE_COMPTABLE") != null && !tiers.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
397
            rowCatCompta = tiers.getForeign("ID_CATEGORIE_COMPTABLE");
398
        }
174 ilm 399
 
400
        if (row.getTable().contains("ID_CATEGORIE_COMPTABLE") && row.getObject("ID_CATEGORIE_COMPTABLE") != null && !row.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
401
            rowCatCompta = row.getForeign("ID_CATEGORIE_COMPTABLE");
402
        }
156 ilm 403
        TotalCalculator calc = new TotalCalculator("T_PA_HT", fieldTotalHT, null, achat, defaultCompte, rowCatCompta);
142 ilm 404
        calc.setIntraComm(intra);
156 ilm 405
 
73 ilm 406
        String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
93 ilm 407
        Boolean bServiceActive = Boolean.valueOf(val);
408
 
73 ilm 409
        calc.setServiceActive(bServiceActive != null && bServiceActive);
156 ilm 410
 
411
        SQLBackgroundTableCacheItem cacheCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(compteTable);
90 ilm 412
        if (row.getTable().contains("ID_COMPTE_PCE_SERVICE") && !row.isForeignEmpty("ID_COMPTE_PCE_SERVICE")) {
156 ilm 413
            SQLRowAccessor serviceCompte = cacheCompte.getRowFromId(row.getForeignID("ID_COMPTE_PCE_SERVICE"));
414
            if (serviceCompte != null && !serviceCompte.isUndefined()) {
90 ilm 415
                calc.setRowDefaultCptService(serviceCompte);
416
            }
417
        }
132 ilm 418
        if (row.getTable().contains("ID_COMPTE_PCE_VENTE") && !row.isForeignEmpty("ID_COMPTE_PCE_VENTE")) {
156 ilm 419
            SQLRowAccessor produitCompte = cacheCompte.getRowFromId(row.getForeignID("ID_COMPTE_PCE_VENTE"));
132 ilm 420
            if (!produitCompte.isUndefined()) {
421
                calc.setRowDefaultCptProduit(produitCompte);
422
            }
423
        }
67 ilm 424
        long remise = 0;
425
        BigDecimal totalAvtRemise = BigDecimal.ZERO;
156 ilm 426
        OOXMLCache cacheRefRows = new OOXMLCache();
427
        final List<? extends SQLRowAccessor> referentRows = cacheRefRows.getReferentRows(Arrays.asList(row), foreign);
67 ilm 428
        if (row.getTable().contains("REMISE_HT")) {
429
            remise = row.getLong("REMISE_HT");
430
            if (remise != 0) {
156 ilm 431
 
432
                // List<SQLRow> rows = row.getReferentRows(foreign);
433
                for (SQLRowAccessor sqlRow : referentRows) {
67 ilm 434
                    calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), 1, false);
435
                }
436
 
437
                if (tableEchantillon != null) {
438
                    List<SQLRow> rowsEch = row.getReferentRows(tableEchantillon);
439
                    for (SQLRow sqlRow : rowsEch) {
440
                        calc.addEchantillon((BigDecimal) sqlRow.getObject("T_PV_HT"), sqlRow.getForeign("ID_TAXE"));
441
                    }
442
                }
174 ilm 443
 
67 ilm 444
                calc.checkResult();
445
                totalAvtRemise = calc.getTotalHT();
446
            }
447
        }
448
 
449
        calc.initValues();
142 ilm 450
        long valRemiseHTReel = remise;
451
        if (row.getFields().contains("POURCENT_FACTURABLE") && row.getFields().contains("MONTANT_FACTURABLE")) {
452
            BigDecimal montantFact = row.getBigDecimal("MONTANT_FACTURABLE");
453
            BigDecimal percentFact = row.getBigDecimal("POURCENT_FACTURABLE");
67 ilm 454
 
142 ilm 455
            if (montantFact != null && montantFact.signum() > 0) {
456
                valRemiseHTReel = 0;
457
            } else if (percentFact != null && percentFact.signum() > 0) {
458
                valRemiseHTReel = percentFact.movePointLeft(2).multiply(new BigDecimal(remise)).setScale(0, RoundingMode.HALF_UP).longValue();
459
            }
460
 
461
        }
462
        calc.setRemise(valRemiseHTReel, totalAvtRemise);
463
 
156 ilm 464
        // List<SQLRow> rows = row.getReferentRows(foreign);
465
        for (int i = 0; i < referentRows.size(); i++) {
466
            SQLRowAccessor sqlRow = referentRows.get(i);
467
            calc.addLine(sqlRow, sqlRow.getForeign("ID_ARTICLE"), i, i == referentRows.size() - 1);
67 ilm 468
        }
469
 
470
        if (tableEchantillon != null) {
471
            List<SQLRow> rowsEch = row.getReferentRows(tableEchantillon);
472
            for (SQLRow sqlRow : rowsEch) {
473
                calc.addEchantillon((BigDecimal) sqlRow.getObject("T_PV_HT"), sqlRow.getForeign("ID_TAXE"));
474
            }
475
        }
476
        if (rowTVAPort != null && !rowTVAPort.isUndefined()) {
477
            SQLRowValues rowValsPort = new SQLRowValues(foreign);
149 ilm 478
            rowValsPort.put(achat ? "T_PA_HT" : "T_PV_HT", portHT);
67 ilm 479
            rowValsPort.put("QTE", 1);
73 ilm 480
            rowValsPort.put("ID_TAXE", rowTVAPort.getIDNumber());
94 ilm 481
 
482
            final SQLTable tablePrefCompte = Configuration.getInstance().getRoot().findTable("PREFS_COMPTE");
156 ilm 483
            final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
94 ilm 484
            SQLRow rowDefaultCptPort;
485
            if (rowTVAPort.getFloat("TAUX") > 0) {
156 ilm 486
                rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_SOUMIS"));
94 ilm 487
                if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
488
                    try {
489
                        rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteSoumisTVA");
490
                    } catch (Exception e) {
491
                        e.printStackTrace();
492
                    }
493
                }
494
            } else {
156 ilm 495
                rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_NON_SOUMIS"));
94 ilm 496
                if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
497
                    try {
498
                        rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteNonSoumisTVA");
499
                    } catch (Exception e) {
500
                        e.printStackTrace();
501
                    }
502
                }
503
            }
142 ilm 504
            final SQLRowValues rowValsArt = rowValsPort.putRowValues("ID_ARTICLE");
149 ilm 505
            rowValsArt.put(achat ? "ID_COMPTE_PCE_ACHAT" : "ID_COMPTE_PCE", rowDefaultCptPort.getID());
142 ilm 506
            rowValsArt.put("ID_TAXE_COMPLEMENTAIRE", null);
156 ilm 507
            rowValsArt.put("ID_FAMILLE_ARTICLE", null);
94 ilm 508
            calc.addLine(rowValsPort, rowValsPort.getForeign("ID_ARTICLE"), 1, false);
67 ilm 509
        }
156 ilm 510
 
511
        if (rowTVAFraisDoc != null && !rowTVAFraisDoc.isUndefined()) {
512
            // Frais documents
513
            SQLRowValues rowValsFraisDoc = new SQLRowValues(foreign);
514
            rowValsFraisDoc.put(achat ? "T_PA_HT" : "T_PV_HT", fraisDocHT);
515
            rowValsFraisDoc.put("QTE", 1);
516
            rowValsFraisDoc.put("ID_TAXE", rowTVAFraisDoc.getIDNumber());
517
            rowValsFraisDoc.put("SERVICE", Boolean.TRUE);
518
            rowValsFraisDoc.put("ID_FAMILLE_ARTICLE", null);
519
            calc.addLine(rowValsFraisDoc, null, 1, false);
520
        }
521
 
174 ilm 522
        // Fix TVA si nécessaire pour facture fournisseur
523
        if (row.getTable().contains("TVA_ADJUSTMENT")) {
524
            BigDecimal tvaFix = row.getBigDecimal("TVA_ADJUSTMENT");
525
            calc.addTVAAdjust(tvaFix);
526
        }
527
 
67 ilm 528
        calc.checkResult();
529
        return calc;
530
    }
531
 
18 ilm 532
    /**
533
     * Crée un nouveau mouvement associé à la piece d'id idPiece
534
     *
535
     * @param source
536
     * @param idSource
537
     * @param idPere
538
     * @param idPiece
539
     * @return id d'un nouveau mouvement
73 ilm 540
     * @throws SQLException
18 ilm 541
     */
73 ilm 542
    synchronized public int getNewMouvement(String source, int idSource, int idPere, int idPiece) throws SQLException {
18 ilm 543
 
544
        SQLTable mouvementTable = base.getTable("MOUVEMENT");
545
 
546
        // on calcule le nouveau numero de mouvement
73 ilm 547
        SQLSelect selNumMvt = new SQLSelect();
548
        selNumMvt.addSelect(mouvementTable.getField("NUMERO"), "MAX");
18 ilm 549
 
550
        String reqNumMvt = selNumMvt.asString();
73 ilm 551
        Object obNumMvt = base.getDataSource().executeScalar(reqNumMvt);
18 ilm 552
 
553
        int numMvt = 1;
73 ilm 554
        if (obNumMvt != null) {
555
            numMvt = Integer.parseInt(obNumMvt.toString());
18 ilm 556
        }
557
        numMvt++;
558
 
559
        // Creation du mouvement
560
        Map<String, Object> m = new HashMap<String, Object>();
561
        m.put("SOURCE", source);
562
        m.put("IDSOURCE", Integer.valueOf(idSource));
563
        m.put("ID_MOUVEMENT_PERE", Integer.valueOf(idPere));
564
        this.idPiece = idPiece;
565
        m.put("ID_PIECE", Integer.valueOf(idPiece));
566
        m.put("NUMERO", Integer.valueOf(numMvt));
567
 
568
        SQLRowValues val = new SQLRowValues(mouvementTable, m);
569
 
73 ilm 570
        if (val.getInvalid() == null) {
571
            SQLRow row = val.insert();
572
            this.idMvt = row.getID();
573
            this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
574
        } else {
575
            throw new IllegalStateException("Error in values for insert in table " + val.getTable().getName() + " : " + val.toString());
18 ilm 576
        }
577
 
578
        System.err.println("Numero de mouvement généré : " + numMvt);
579
 
580
        return this.idMvt;
581
    }
80 ilm 582
 
583
    protected void displayMvtNumber() {
584
        if (DefaultNXProps.getInstance().getBooleanValue(GestionPieceCommercialePanel.SHOW_MOUVEMENT_NUMBER, false)) {
585
            final int numero = mouvementTable.getRow(idMvt).getInt("NUMERO");
586
            SwingUtilities.invokeLater(new Runnable() {
587
                @Override
588
                public void run() {
589
                    JOptionPane.showMessageDialog(null, "N° de mouvement associé : " + numero);
590
                }
591
            });
592
        }
593
 
594
    }
595
 
83 ilm 596
    /**
597
     * Définit le journal en fonction de la banque sélectionnée
598
     *
599
     * @param sqlRow sqlRow contenant la foreignKey Banque
600
     */
601
    protected void fillJournalBanqueFromRow(SQLRow sqlRow) {
602
        this.mEcritures.put("ID_JOURNAL", JournalSQLElement.BANQUES);
603
        if (!sqlRow.isForeignEmpty("ID_" + BanqueSQLElement.TABLENAME)) {
604
            SQLRow rowBanque = sqlRow.getForeignRow("ID_" + BanqueSQLElement.TABLENAME);
605
            if (!rowBanque.isForeignEmpty("ID_JOURNAL")) {
606
                SQLRow rowJournal = rowBanque.getForeignRow("ID_JOURNAL");
607
                this.mEcritures.put("ID_JOURNAL", rowJournal.getID());
608
            }
609
        }
610
    }
611
 
612
    /**
613
     * Définit le compte en fonction de la banque sélectionnée
614
     *
615
     * @param sqlRow sqlRow contenant la foreignKey Banque
616
     * @throws Exception
617
     */
618
    protected void fillCompteBanqueFromRow(SQLRow sqlRow, String defaultProps, boolean achat) throws Exception {
142 ilm 619
        int idPce = -1;
620
        if (sqlRow.getTable().contains("ID_TYPE_REGLEMENT")) {
621
            idPce = sqlRow.getForeign("ID_TYPE_REGLEMENT").getInt("ID_COMPTE_PCE_" + (achat ? "FOURN" : "CLIENT"));
622
        } else {
623
            idPce = base.getTable("TYPE_REGLEMENT").getRow(2).getInt("ID_COMPTE_PCE_" + (achat ? "FOURN" : "CLIENT"));
624
        }
83 ilm 625
        if (idPce <= 1) {
626
            idPce = ComptePCESQLElement.getIdComptePceDefault(defaultProps);
627
        }
628
        if (!sqlRow.isForeignEmpty("ID_" + BanqueSQLElement.TABLENAME)) {
629
            SQLRow rowBanque = sqlRow.getForeignRow("ID_" + BanqueSQLElement.TABLENAME);
630
            if (!rowBanque.isForeignEmpty("ID_COMPTE_PCE")) {
631
                SQLRow rowCompteBanque = rowBanque.getForeignRow("ID_COMPTE_PCE");
632
                idPce = rowCompteBanque.getID();
633
            }
634
        }
635
 
636
        this.mEcritures.put("ID_COMPTE_PCE", idPce);
637
    }
151 ilm 638
 
639
    protected void lettrageAuto(List<Integer> pieceIDs, Date d) {
640
        final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
641
        final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
642
 
643
        if (rowPrefsCompte.getBoolean("AUTO_LETTRAGE")) {
644
            SQLSelect selEcr = new SQLSelect();
645
            SQLTable tableEcr = base.getTable("ECRITURE");
646
            selEcr.addSelect(tableEcr.getKey());
647
            selEcr.addSelect(tableEcr.getField("DEBIT"));
648
            selEcr.addSelect(tableEcr.getField("CREDIT"));
649
            selEcr.addSelect(tableEcr.getField("LETTRAGE"));
650
            SQLTable tableCpte = base.getTable("COMPTE_PCE");
651
            Where w2 = new Where(base.getTable("MOUVEMENT").getField("ID_PIECE"), pieceIDs);
652
            w2 = w2.and(new Where(tableEcr.getField("ID_MOUVEMENT"), "=", base.getTable("MOUVEMENT").getKey()));
653
            w2 = w2.and(new Where(tableEcr.getField("ID_COMPTE_PCE"), "=", tableCpte.getKey()));
654
            w2 = w2.and(new Where(tableCpte.getField("NUMERO"), "LIKE", "40%").or(new Where(tableCpte.getField("NUMERO"), "LIKE", "41%")));
655
            w2 = w2.and(new Where(tableEcr.getField("DATE_LETTRAGE"), "=", (Object) null));
656
            selEcr.setWhere(w2);
657
            long solde = -1;
658
            List<SQLRow> ecr = SQLRowListRSH.execute(selEcr);
659
            if (!ecr.isEmpty()) {
660
                solde = 0;
661
                for (SQLRow sqlRow2 : ecr) {
662
                    solde += sqlRow2.getLong("DEBIT");
663
                    solde -= sqlRow2.getLong("CREDIT");
664
                }
665
            }
666
            if (solde == 0) {
667
 
668
                String codeLettre = NumerotationAutoSQLElement.getNextCodeLettrage();
669
 
670
                for (SQLRow sqlRow2 : ecr) {
671
                    SQLRowValues rowValsEcr = sqlRow2.asRowValues();
672
                    // Lettrage
673
                    // On lettre ou relettre la ligne avec le code saisi
674
                    if (codeLettre.length() > 0) {
675
 
676
                        rowValsEcr.put("LETTRAGE", codeLettre);
677
                        rowValsEcr.put("DATE_LETTRAGE", d);
678
                        try {
679
                            rowValsEcr.update();
680
                        } catch (SQLException e1) {
681
 
682
                            e1.printStackTrace();
683
                        }
684
                    }
685
                    // Mise à jour du code de lettrage
686
                    SQLElement elt = Configuration.getInstance().getDirectory().getElement("NUMEROTATION_AUTO");
687
                    SQLRowValues rowVals = elt.getTable().getRow(2).createEmptyUpdateRow();
688
                    rowVals.put("CODE_LETTRAGE", codeLettre);
689
                    try {
690
                        rowVals.update();
691
                    } catch (SQLException ex) {
692
                        ex.printStackTrace();
693
                    }
694
 
695
                }
696
 
697
            }
698
        }
699
    }
156 ilm 700
 
18 ilm 701
}