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
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
185 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
18 ilm 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;
185 ilm 485
            if (achat) {
486
                if (rowTVAPort.getFloat("TAUX") > 0) {
487
                    rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_SOUMIS_ACHAT"));
488
                    if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
489
                        try {
490
                            rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortAchatSoumisTVA");
491
                        } catch (Exception e) {
492
                            e.printStackTrace();
493
                        }
94 ilm 494
                    }
185 ilm 495
                } else {
496
                    rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_NON_SOUMIS_ACHAT"));
497
                    if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
498
                        try {
499
                            rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortAchatNonSoumisTVA");
500
                        } catch (Exception e) {
501
                            e.printStackTrace();
502
                        }
503
                    }
94 ilm 504
                }
505
            } else {
185 ilm 506
                if (rowTVAPort.getFloat("TAUX") > 0) {
507
                    rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_SOUMIS"));
508
                    if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
509
                        try {
510
                            rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteSoumisTVA");
511
                        } catch (Exception e) {
512
                            e.printStackTrace();
513
                        }
94 ilm 514
                    }
185 ilm 515
                } else {
516
                    rowDefaultCptPort = cacheCompte.getRowFromId(rowPrefsCompte.getForeignID("ID_COMPTE_PCE_PORT_NON_SOUMIS"));
517
                    if (rowDefaultCptPort == null || rowDefaultCptPort.isUndefined()) {
518
                        try {
519
                            rowDefaultCptPort = ComptePCESQLElement.getRowComptePceDefault("PortVenteNonSoumisTVA");
520
                        } catch (Exception e) {
521
                            e.printStackTrace();
522
                        }
523
                    }
94 ilm 524
                }
525
            }
142 ilm 526
            final SQLRowValues rowValsArt = rowValsPort.putRowValues("ID_ARTICLE");
149 ilm 527
            rowValsArt.put(achat ? "ID_COMPTE_PCE_ACHAT" : "ID_COMPTE_PCE", rowDefaultCptPort.getID());
142 ilm 528
            rowValsArt.put("ID_TAXE_COMPLEMENTAIRE", null);
156 ilm 529
            rowValsArt.put("ID_FAMILLE_ARTICLE", null);
94 ilm 530
            calc.addLine(rowValsPort, rowValsPort.getForeign("ID_ARTICLE"), 1, false);
67 ilm 531
        }
156 ilm 532
 
533
        if (rowTVAFraisDoc != null && !rowTVAFraisDoc.isUndefined()) {
534
            // Frais documents
535
            SQLRowValues rowValsFraisDoc = new SQLRowValues(foreign);
536
            rowValsFraisDoc.put(achat ? "T_PA_HT" : "T_PV_HT", fraisDocHT);
537
            rowValsFraisDoc.put("QTE", 1);
538
            rowValsFraisDoc.put("ID_TAXE", rowTVAFraisDoc.getIDNumber());
539
            rowValsFraisDoc.put("SERVICE", Boolean.TRUE);
540
            rowValsFraisDoc.put("ID_FAMILLE_ARTICLE", null);
541
            calc.addLine(rowValsFraisDoc, null, 1, false);
542
        }
543
 
174 ilm 544
        // Fix TVA si nécessaire pour facture fournisseur
545
        if (row.getTable().contains("TVA_ADJUSTMENT")) {
546
            BigDecimal tvaFix = row.getBigDecimal("TVA_ADJUSTMENT");
547
            calc.addTVAAdjust(tvaFix);
548
        }
549
 
67 ilm 550
        calc.checkResult();
551
        return calc;
552
    }
553
 
18 ilm 554
    /**
555
     * Crée un nouveau mouvement associé à la piece d'id idPiece
556
     *
557
     * @param source
558
     * @param idSource
559
     * @param idPere
560
     * @param idPiece
561
     * @return id d'un nouveau mouvement
73 ilm 562
     * @throws SQLException
18 ilm 563
     */
73 ilm 564
    synchronized public int getNewMouvement(String source, int idSource, int idPere, int idPiece) throws SQLException {
18 ilm 565
 
566
        SQLTable mouvementTable = base.getTable("MOUVEMENT");
567
 
568
        // on calcule le nouveau numero de mouvement
73 ilm 569
        SQLSelect selNumMvt = new SQLSelect();
570
        selNumMvt.addSelect(mouvementTable.getField("NUMERO"), "MAX");
18 ilm 571
 
572
        String reqNumMvt = selNumMvt.asString();
73 ilm 573
        Object obNumMvt = base.getDataSource().executeScalar(reqNumMvt);
18 ilm 574
 
575
        int numMvt = 1;
73 ilm 576
        if (obNumMvt != null) {
577
            numMvt = Integer.parseInt(obNumMvt.toString());
18 ilm 578
        }
579
        numMvt++;
580
 
581
        // Creation du mouvement
582
        Map<String, Object> m = new HashMap<String, Object>();
583
        m.put("SOURCE", source);
584
        m.put("IDSOURCE", Integer.valueOf(idSource));
585
        m.put("ID_MOUVEMENT_PERE", Integer.valueOf(idPere));
586
        this.idPiece = idPiece;
587
        m.put("ID_PIECE", Integer.valueOf(idPiece));
588
        m.put("NUMERO", Integer.valueOf(numMvt));
589
 
590
        SQLRowValues val = new SQLRowValues(mouvementTable, m);
591
 
73 ilm 592
        if (val.getInvalid() == null) {
593
            SQLRow row = val.insert();
594
            this.idMvt = row.getID();
595
            this.mEcritures.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
596
        } else {
597
            throw new IllegalStateException("Error in values for insert in table " + val.getTable().getName() + " : " + val.toString());
18 ilm 598
        }
599
 
600
        System.err.println("Numero de mouvement généré : " + numMvt);
601
 
602
        return this.idMvt;
603
    }
80 ilm 604
 
605
    protected void displayMvtNumber() {
606
        if (DefaultNXProps.getInstance().getBooleanValue(GestionPieceCommercialePanel.SHOW_MOUVEMENT_NUMBER, false)) {
607
            final int numero = mouvementTable.getRow(idMvt).getInt("NUMERO");
608
            SwingUtilities.invokeLater(new Runnable() {
609
                @Override
610
                public void run() {
611
                    JOptionPane.showMessageDialog(null, "N° de mouvement associé : " + numero);
612
                }
613
            });
614
        }
615
 
616
    }
617
 
83 ilm 618
    /**
619
     * Définit le journal en fonction de la banque sélectionnée
620
     *
621
     * @param sqlRow sqlRow contenant la foreignKey Banque
622
     */
623
    protected void fillJournalBanqueFromRow(SQLRow sqlRow) {
624
        this.mEcritures.put("ID_JOURNAL", JournalSQLElement.BANQUES);
625
        if (!sqlRow.isForeignEmpty("ID_" + BanqueSQLElement.TABLENAME)) {
626
            SQLRow rowBanque = sqlRow.getForeignRow("ID_" + BanqueSQLElement.TABLENAME);
627
            if (!rowBanque.isForeignEmpty("ID_JOURNAL")) {
628
                SQLRow rowJournal = rowBanque.getForeignRow("ID_JOURNAL");
629
                this.mEcritures.put("ID_JOURNAL", rowJournal.getID());
630
            }
185 ilm 631
        } else if (sqlRow.getTable().contains("ID_TYPE_REGLEMENT") && !sqlRow.isForeignEmpty("ID_TYPE_REGLEMENT")) {
632
            SQLRow rowType = sqlRow.getForeignRow("ID_TYPE_REGLEMENT");
633
            if (rowType.getTable().contains("ID_JOURNAL") && !rowType.isForeignEmpty("ID_JOURNAL")) {
634
                SQLRow rowJournal = rowType.getForeignRow("ID_JOURNAL");
635
                this.mEcritures.put("ID_JOURNAL", rowJournal.getID());
636
            }
83 ilm 637
        }
638
    }
639
 
640
    /**
641
     * Définit le compte en fonction de la banque sélectionnée
642
     *
643
     * @param sqlRow sqlRow contenant la foreignKey Banque
644
     * @throws Exception
645
     */
185 ilm 646
    protected void fillCompteBanqueFromRow(SQLRow sqlRow, String defaultProps, boolean achat) throws SQLException {
142 ilm 647
        int idPce = -1;
648
        if (sqlRow.getTable().contains("ID_TYPE_REGLEMENT")) {
649
            idPce = sqlRow.getForeign("ID_TYPE_REGLEMENT").getInt("ID_COMPTE_PCE_" + (achat ? "FOURN" : "CLIENT"));
650
        } else {
651
            idPce = base.getTable("TYPE_REGLEMENT").getRow(2).getInt("ID_COMPTE_PCE_" + (achat ? "FOURN" : "CLIENT"));
652
        }
83 ilm 653
        if (idPce <= 1) {
654
            idPce = ComptePCESQLElement.getIdComptePceDefault(defaultProps);
655
        }
656
        if (!sqlRow.isForeignEmpty("ID_" + BanqueSQLElement.TABLENAME)) {
657
            SQLRow rowBanque = sqlRow.getForeignRow("ID_" + BanqueSQLElement.TABLENAME);
658
            if (!rowBanque.isForeignEmpty("ID_COMPTE_PCE")) {
659
                SQLRow rowCompteBanque = rowBanque.getForeignRow("ID_COMPTE_PCE");
660
                idPce = rowCompteBanque.getID();
661
            }
662
        }
663
 
664
        this.mEcritures.put("ID_COMPTE_PCE", idPce);
665
    }
151 ilm 666
 
667
    protected void lettrageAuto(List<Integer> pieceIDs, Date d) {
668
        final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
669
        final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
670
 
671
        if (rowPrefsCompte.getBoolean("AUTO_LETTRAGE")) {
672
            SQLSelect selEcr = new SQLSelect();
673
            SQLTable tableEcr = base.getTable("ECRITURE");
674
            selEcr.addSelect(tableEcr.getKey());
675
            selEcr.addSelect(tableEcr.getField("DEBIT"));
676
            selEcr.addSelect(tableEcr.getField("CREDIT"));
677
            selEcr.addSelect(tableEcr.getField("LETTRAGE"));
678
            SQLTable tableCpte = base.getTable("COMPTE_PCE");
679
            Where w2 = new Where(base.getTable("MOUVEMENT").getField("ID_PIECE"), pieceIDs);
680
            w2 = w2.and(new Where(tableEcr.getField("ID_MOUVEMENT"), "=", base.getTable("MOUVEMENT").getKey()));
681
            w2 = w2.and(new Where(tableEcr.getField("ID_COMPTE_PCE"), "=", tableCpte.getKey()));
682
            w2 = w2.and(new Where(tableCpte.getField("NUMERO"), "LIKE", "40%").or(new Where(tableCpte.getField("NUMERO"), "LIKE", "41%")));
683
            w2 = w2.and(new Where(tableEcr.getField("DATE_LETTRAGE"), "=", (Object) null));
684
            selEcr.setWhere(w2);
685
            long solde = -1;
686
            List<SQLRow> ecr = SQLRowListRSH.execute(selEcr);
687
            if (!ecr.isEmpty()) {
688
                solde = 0;
689
                for (SQLRow sqlRow2 : ecr) {
690
                    solde += sqlRow2.getLong("DEBIT");
691
                    solde -= sqlRow2.getLong("CREDIT");
692
                }
693
            }
694
            if (solde == 0) {
695
 
696
                String codeLettre = NumerotationAutoSQLElement.getNextCodeLettrage();
697
 
698
                for (SQLRow sqlRow2 : ecr) {
699
                    SQLRowValues rowValsEcr = sqlRow2.asRowValues();
700
                    // Lettrage
701
                    // On lettre ou relettre la ligne avec le code saisi
702
                    if (codeLettre.length() > 0) {
703
 
704
                        rowValsEcr.put("LETTRAGE", codeLettre);
705
                        rowValsEcr.put("DATE_LETTRAGE", d);
706
                        try {
707
                            rowValsEcr.update();
708
                        } catch (SQLException e1) {
709
 
710
                            e1.printStackTrace();
711
                        }
712
                    }
713
                    // Mise à jour du code de lettrage
714
                    SQLElement elt = Configuration.getInstance().getDirectory().getElement("NUMEROTATION_AUTO");
715
                    SQLRowValues rowVals = elt.getTable().getRow(2).createEmptyUpdateRow();
716
                    rowVals.put("CODE_LETTRAGE", codeLettre);
717
                    try {
718
                        rowVals.update();
719
                    } catch (SQLException ex) {
720
                        ex.printStackTrace();
721
                    }
722
 
723
                }
724
 
725
            }
726
        }
727
    }
156 ilm 728
 
18 ilm 729
}