OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 151 | Rev 182 | 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.core.sales.invoice.element;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.config.Gestion;
73 ilm 18
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
18 ilm 19
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
94 ilm 20
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable;
67 ilm 21
import org.openconcerto.erp.core.common.ui.DeviseField;
22
import org.openconcerto.erp.core.common.ui.PanelFrame;
151 ilm 23
import org.openconcerto.erp.core.edm.AttachmentAction;
67 ilm 24
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
156 ilm 25
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
83 ilm 26
import org.openconcerto.erp.core.sales.account.PartialInvoiceEditGroup;
80 ilm 27
import org.openconcerto.erp.core.sales.account.VenteFactureSituationSQLComponent;
83 ilm 28
import org.openconcerto.erp.core.sales.account.VenteFactureSoldeEditGroup;
80 ilm 29
import org.openconcerto.erp.core.sales.account.VenteFactureSoldeSQLComponent;
18 ilm 30
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
67 ilm 31
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
156 ilm 32
import org.openconcerto.erp.core.sales.invoice.ui.DateReglementRenderer;
19 ilm 33
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
34
import org.openconcerto.erp.core.sales.shipment.component.BonDeLivraisonSQLComponent;
35
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
67 ilm 36
import org.openconcerto.erp.generationEcritures.GenerationMvtRetourNatexis;
142 ilm 37
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
67 ilm 38
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
83 ilm 39
import org.openconcerto.erp.preferences.DefaultNXProps;
61 ilm 40
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
142 ilm 41
import org.openconcerto.erp.preferences.PrinterNXProps;
67 ilm 42
import org.openconcerto.erp.rights.NXRights;
18 ilm 43
import org.openconcerto.sql.Configuration;
83 ilm 44
import org.openconcerto.sql.element.GlobalMapper;
18 ilm 45
import org.openconcerto.sql.element.SQLComponent;
46
import org.openconcerto.sql.element.SQLElement;
132 ilm 47
import org.openconcerto.sql.element.SQLElementLink.LinkType;
48
import org.openconcerto.sql.element.SQLElementLinksSetup;
49
import org.openconcerto.sql.element.TreesOfSQLRows;
83 ilm 50
import org.openconcerto.sql.model.FieldPath;
19 ilm 51
import org.openconcerto.sql.model.SQLField;
18 ilm 52
import org.openconcerto.sql.model.SQLInjector;
53
import org.openconcerto.sql.model.SQLRow;
67 ilm 54
import org.openconcerto.sql.model.SQLRowAccessor;
55
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 56
import org.openconcerto.sql.model.SQLRowValues;
57
import org.openconcerto.sql.model.SQLSelect;
19 ilm 58
import org.openconcerto.sql.model.SQLTable;
18 ilm 59
import org.openconcerto.sql.model.Where;
83 ilm 60
import org.openconcerto.sql.model.graph.Path;
61 ilm 61
import org.openconcerto.sql.preferences.SQLPreferences;
18 ilm 62
import org.openconcerto.sql.request.ListSQLRequest;
67 ilm 63
import org.openconcerto.sql.sqlobject.ElementComboBox;
94 ilm 64
import org.openconcerto.sql.users.rights.UserRightsManager;
18 ilm 65
import org.openconcerto.sql.view.EditFrame;
67 ilm 66
import org.openconcerto.sql.view.EditPanel;
73 ilm 67
import org.openconcerto.sql.view.EditPanel.EditMode;
67 ilm 68
import org.openconcerto.sql.view.EditPanelListener;
83 ilm 69
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
67 ilm 70
import org.openconcerto.sql.view.list.IListe;
73 ilm 71
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
67 ilm 72
import org.openconcerto.sql.view.list.RowAction;
73
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
142 ilm 74
import org.openconcerto.sql.view.list.SQLTableModelSource;
67 ilm 75
import org.openconcerto.ui.DefaultGridBagConstraints;
142 ilm 76
import org.openconcerto.ui.FrameUtil;
83 ilm 77
import org.openconcerto.ui.table.PercentTableCellRenderer;
78
import org.openconcerto.utils.CollectionUtils;
90 ilm 79
import org.openconcerto.utils.DecimalUtils;
18 ilm 80
import org.openconcerto.utils.ExceptionHandler;
83 ilm 81
import org.openconcerto.utils.ListMap;
80 ilm 82
import org.openconcerto.utils.Tuple2;
132 ilm 83
import org.openconcerto.utils.cc.IClosure;
80 ilm 84
import org.openconcerto.utils.cc.ITransformer;
67 ilm 85
import org.openconcerto.utils.i18n.TranslationManager;
18 ilm 86
 
67 ilm 87
import java.awt.GridBagConstraints;
88
import java.awt.GridBagLayout;
89
import java.awt.event.ActionEvent;
90
import java.awt.event.ActionListener;
19 ilm 91
import java.math.BigDecimal;
83 ilm 92
import java.math.RoundingMode;
156 ilm 93
import java.sql.Date;
18 ilm 94
import java.sql.SQLException;
95
import java.util.ArrayList;
83 ilm 96
import java.util.Arrays;
97
import java.util.Collection;
98
import java.util.Collections;
90 ilm 99
import java.util.HashMap;
18 ilm 100
import java.util.HashSet;
101
import java.util.List;
90 ilm 102
import java.util.Map;
18 ilm 103
import java.util.Set;
104
 
67 ilm 105
import javax.swing.AbstractAction;
18 ilm 106
import javax.swing.ImageIcon;
67 ilm 107
import javax.swing.JButton;
18 ilm 108
import javax.swing.JFrame;
67 ilm 109
import javax.swing.JLabel;
110
import javax.swing.JPanel;
142 ilm 111
import javax.swing.SwingUtilities;
18 ilm 112
 
113
import org.apache.commons.dbutils.handlers.ArrayListHandler;
114
 
67 ilm 115
// Depuis le 1er juillet 2003, la règlementation fiscale impose la délivrance d'une facture pour
116
// tous les versements d'acomptes, même lorsqu'ils ne donnent pas lieu à exigibilité de la TVA
117
// (article 289 I -1-c du CGI).
118
// Avant la loi de finances rectificative pour 2002, il n'y avait obligation de délivrer une facture
119
// pour les acomptes que lorsque la TVA était exigible sur ces versements. Depuis l'entrée en
120
// vigueur de cette loi, initialement fixée au 1er juillet 2003, et reportée par tolérance
121
// administrative au 1er janvier 2004, il faut désormais délivrer une facture pour tous les acomptes
122
// perçus.
123
// L'obligation nouvelle de facturer tous les versements d'acomptes ne modifie pas les règles
124
// d'exigibilité de la TVA.
125
// La date du versement de l'acompte doit être indiquée sur la facture d'acompte si elle est
126
// différente de la date de délivrance de cette facture, et si elle est connue à cette date.
127
 
128
// La facture d'acompte peut ne pas mentionner l'ensemble des mentions obligatoires lorsque les
129
// informations nécessaires à son établissement ne sont pas connues au moment de son émission (par
130
// exemple, quantité ou prix exact du produit).
18 ilm 131
public class SaisieVenteFactureSQLElement extends ComptaSQLConfElement {
132
 
25 ilm 133
    public static final String TABLENAME = "SAISIE_VENTE_FACTURE";
151 ilm 134
    static public final String MESSAGE_FIELD_NAME = "ID_SDD_MESSAGE";
135
    static public final String END2END_FIELD_NAME = "SDD_EndToEndId";
25 ilm 136
 
18 ilm 137
    public SaisieVenteFactureSQLElement() {
25 ilm 138
        super(TABLENAME, "une facture", "factures");
80 ilm 139
 
83 ilm 140
        GlobalMapper.getInstance().map(VenteFactureSituationSQLComponent.ID, new PartialInvoiceEditGroup());
80 ilm 141
        addComponentFactory(VenteFactureSituationSQLComponent.ID, new ITransformer<Tuple2<SQLElement, String>, SQLComponent>() {
142
 
143
            @Override
144
            public SQLComponent transformChecked(Tuple2<SQLElement, String> input) {
145
 
146
                return new VenteFactureSituationSQLComponent(SaisieVenteFactureSQLElement.this);
147
            }
148
        });
83 ilm 149
        GlobalMapper.getInstance().map(VenteFactureSoldeSQLComponent.ID, new VenteFactureSoldeEditGroup());
80 ilm 150
        addComponentFactory(VenteFactureSoldeSQLComponent.ID, new ITransformer<Tuple2<SQLElement, String>, SQLComponent>() {
151
 
152
            @Override
153
            public SQLComponent transformChecked(Tuple2<SQLElement, String> input) {
154
 
155
                return new VenteFactureSoldeSQLComponent(SaisieVenteFactureSQLElement.this);
156
            }
157
        });
158
 
142 ilm 159
        final boolean affact = UserRightsManager.getCurrentUserRights().haveRight(NXRights.ACCES_RETOUR_AFFACTURAGE.getCode());
67 ilm 160
        List<RowAction> l = new ArrayList<RowAction>(5);
161
            PredicateRowAction actionBL = new PredicateRowAction(new AbstractAction() {
162
                public void actionPerformed(ActionEvent e) {
93 ilm 163
                    TransfertBaseSQLComponent.openTransfertFrame(IListe.get(e).getSelectedRows(), "BON_DE_LIVRAISON");
67 ilm 164
                }
165
            }, false, "sales.invoice.create.delivery");
166
            actionBL.setPredicate(IListeEvent.getSingleSelectionPredicate());
167
            l.add(actionBL);
151 ilm 168
        if (getTable().contains("ATTACHMENTS")) {
169
            PredicateRowAction actionAttachment = new PredicateRowAction(new AttachmentAction().getAction(), true);
170
            actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate());
171
            getRowActions().add(actionAttachment);
172
        }
173
 
67 ilm 174
        PredicateRowAction actionAvoir = new PredicateRowAction(new AbstractAction() {
175
            public void actionPerformed(ActionEvent e) {
93 ilm 176
                TransfertBaseSQLComponent.openTransfertFrame(IListe.get(e).getSelectedRows(), "AVOIR_CLIENT");
67 ilm 177
            }
178
        }, false, "sales.invoice.create.credit");
179
        actionAvoir.setPredicate(IListeEvent.getSingleSelectionPredicate());
180
        l.add(actionAvoir);
142 ilm 181
 
182
        final String property = PrinterNXProps.getInstance().getProperty("QLPrinter");
183
        if (property != null && property.trim().length() > 0) {
184
            PredicateRowAction actionPrintLabel = new PredicateRowAction(new AbstractAction() {
185
                public void actionPerformed(ActionEvent e) {
186
                    // ((ClientNormalSQLElement)
187
                    // getForeignElement("ID_CLIENT")).printLabel(IListe.get(e).getSelectedRow().getForeign("ID_CLIENT"),
188
                    // property);
189
                }
190
            }, false, "customerrelationship.customer.label.print");
191
            actionPrintLabel.setPredicate(IListeEvent.getSingleSelectionPredicate());
156 ilm 192
            // l.add(actionPrintLabel);
142 ilm 193
        }
80 ilm 194
        RowAction actionClone = new RowAction(new AbstractAction() {
67 ilm 195
            public void actionPerformed(ActionEvent e) {
196
 
197
                SQLElement eltFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
198
                EditFrame editFrame = new EditFrame(eltFact, EditPanel.CREATION);
199
 
200
                ((SaisieVenteFactureSQLComponent) editFrame.getSQLComponent()).loadFactureExistante(IListe.get(e).getSelectedId());
201
                editFrame.setVisible(true);
202
            }
151 ilm 203
        }, true, "sales.invoice.clone") {
80 ilm 204
            public boolean enabledFor(IListeEvent evt) {
93 ilm 205
                List<? extends SQLRowAccessor> l = evt.getSelectedRows();
80 ilm 206
                if (l != null && l.size() == 1) {
207
                    SQLRowAccessor r = l.get(0);
208
                    return !r.getBoolean("PARTIAL") && !r.getBoolean("SOLDE");
209
                }
210
                return false;
211
            }
212
        };
213
 
67 ilm 214
        l.add(actionClone);
215
        getRowActions().addAll(l);
216
 
217
 
218
        PredicateRowAction actionClient = new PredicateRowAction(new AbstractAction("Détails client") {
219
            EditFrame edit;
220
            private SQLElement eltClient = Configuration.getInstance().getDirectory().getElement(((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT"));
221
 
222
            public void actionPerformed(ActionEvent e) {
223
                if (edit == null) {
224
                    edit = new EditFrame(eltClient, EditMode.READONLY);
225
                }
80 ilm 226
                edit.selectionId(IListe.get(e).fetchSelectedRow().getInt("ID_CLIENT"));
67 ilm 227
                edit.setVisible(true);
228
            }
229
        }, false, "sales.invoice.info.show");
230
        actionClient.setPredicate(IListeEvent.getSingleSelectionPredicate());
231
        getRowActions().add(actionClient);
232
 
233
        PredicateRowAction actionCommande = new PredicateRowAction(new AbstractAction() {
234
            public void actionPerformed(ActionEvent e) {
235
                SaisieVenteFactureSQLElement elt = (SaisieVenteFactureSQLElement) Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
236
                elt.transfertCommande(IListe.get(e).getSelectedId());
237
            }
238
        }, false, "sales.invoice.create.supplier.order");
239
        actionCommande.setPredicate(IListeEvent.getSingleSelectionPredicate());
240
        getRowActions().add(actionCommande);
241
 
142 ilm 242
        RowAction actionCancelAvoir = new PredicateRowAction(new AbstractAction() {
243
            public void actionPerformed(ActionEvent e) {
244
                cancelAvoir(IListe.get(e).getSelectedRow());
245
            }
246
        }, false, "sales.invoice.cancel.credit") {
247
            @Override
248
            public boolean enabledFor(IListeEvent evt) {
249
                final SQLRowAccessor selectedRow = evt.getSelectedRow().asRow();
250
                final List<SQLRowValues> rows = evt.getSelectedRows();
251
                return rows != null && rows.size() == 1 && selectedRow != null && !selectedRow.isForeignEmpty("ID_AVOIR_CLIENT");
252
            }
253
        };
254
        getRowActions().add(actionCancelAvoir);
255
 
67 ilm 256
        MouseSheetXmlListeListener mouseSheetXmlListeListener = new MouseSheetXmlListeListener(VenteFactureXmlSheet.class);
257
        getRowActions().addAll(mouseSheetXmlListeListener.getRowActions());
258
        // this.frame.getPanel().getListe().addRowActions(mouseListener.getRowActions());
259
 
18 ilm 260
    }
261
 
73 ilm 262
    @Override
132 ilm 263
    protected void setupLinks(SQLElementLinksSetup links) {
264
        super.setupLinks(links);
265
        if (getTable().contains("ID_ADRESSE")) {
266
            links.get("ID_ADRESSE").setType(LinkType.ASSOCIATION);
267
        }
268
        if (getTable().contains("ID_ADRESSE_LIVRAISON")) {
269
            links.get("ID_ADRESSE_LIVRAISON").setType(LinkType.ASSOCIATION);
270
        }
151 ilm 271
        links.get(MESSAGE_FIELD_NAME).setType(LinkType.ASSOCIATION, ReferenceAction.RESTRICT);
132 ilm 272
    }
273
 
274
    @Override
275
    public ListMap<String, String> getShowAs() {
276
        ListMap<String, String> map = new ListMap<String, String>();
142 ilm 277
        map.putCollection(null, "NUMERO", "DATE", "ID_COMMERCIAL");
73 ilm 278
        return map;
279
    }
280
 
18 ilm 281
    protected List<String> getListFields() {
282
        final List<String> l = new ArrayList<String>();
19 ilm 283
 
83 ilm 284
            l.add("NUMERO");
285
            l.add("DATE");
286
            l.add("NOM");
287
            l.add("ID_CLIENT");
288
                l.add("ID_MODE_REGLEMENT");
289
            l.add("ID_COMMERCIAL");
132 ilm 290
            if (UserRightsManager.getCurrentUserRights().haveRight(AbstractVenteArticleItemTable.SHOW_PRIX_ACHAT_CODE)) {
94 ilm 291
                l.add("T_HA");
292
            }
83 ilm 293
            l.add("T_HT");
294
            l.add("T_TTC");
295
            l.add("INFOS");
296
 
297
                    l.add("DATE_ENVOI");
298
                l.add("DATE_REGLEMENT");
18 ilm 299
        return l;
300
    }
301
 
302
    @Override
132 ilm 303
    protected void _initListRequest(ListSQLRequest req) {
304
        super._initListRequest(req);
305
        req.changeGraphToFetch(new IClosure<SQLRowValues>() {
18 ilm 306
            @Override
132 ilm 307
            public void executeChecked(SQLRowValues graphToFetch) {
18 ilm 308
                graphToFetch.put("ACOMPTE", null);
80 ilm 309
                graphToFetch.put("PARTIAL", null);
310
                graphToFetch.put("SOLDE", null);
18 ilm 311
                graphToFetch.put("COMPLEMENT", null);
19 ilm 312
 
18 ilm 313
                graphToFetch.put("PREVISIONNELLE", null);
314
                    graphToFetch.grow("ID_MODE_REGLEMENT").put("AJOURS", null).put("LENJOUR", null);
67 ilm 315
                SQLRowValues value = new SQLRowValues(graphToFetch.getTable().getTable("MOUVEMENT"));
316
                value.put("ID_PIECE", null);
317
                graphToFetch.put("ID_MOUVEMENT", value);
318
                graphToFetch.put("T_AVOIR_TTC", null);
18 ilm 319
            }
132 ilm 320
        });
18 ilm 321
    }
322
 
83 ilm 323
    private BigDecimal getAvancement(SQLRowAccessor r) {
324
        Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("ECHEANCE_CLIENT"));
325
        long totalEch = 0;
326
 
327
        for (SQLRowAccessor row : rows) {
328
            if (!row.getBoolean("REGLE") && !row.getBoolean("REG_COMPTA")) {
329
                totalEch += row.getLong("MONTANT");
330
            }
331
        }
332
 
333
        SQLRowAccessor avoir = r.getForeign("ID_AVOIR_CLIENT");
334
        BigDecimal avoirTTC = BigDecimal.ZERO;
335
        if (avoir != null && !avoir.isUndefined()) {
336
            avoirTTC = new BigDecimal(avoir.getLong("MONTANT_TTC"));
337
        }
338
 
339
        final BigDecimal totalAregler = new BigDecimal(r.getLong("T_TTC")).subtract(avoirTTC);
340
        if (totalAregler.signum() > 0 && totalEch > 0) {
90 ilm 341
            return totalAregler.subtract(new BigDecimal(totalEch)).divide(totalAregler, DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
83 ilm 342
        } else {
343
            return BigDecimal.ONE.movePointRight(2);
344
        }
345
    }
346
 
347
    @Override
142 ilm 348
    protected synchronized void _initTableSource(final SQLTableModelSource table) {
349
        super._initTableSource(table);
83 ilm 350
 
351
        final BaseSQLTableModelColumn colAvancement = new BaseSQLTableModelColumn("Avancement réglement", BigDecimal.class) {
352
 
353
            @Override
354
            protected Object show_(SQLRowAccessor r) {
355
 
356
                return getAvancement(r);
357
            }
358
 
359
            @Override
360
            public Set<FieldPath> getPaths() {
361
                Path p = new Path(SaisieVenteFactureSQLElement.this.getTable());
362
                p = p.add(getTable().getTable("ECHEANCE_CLIENT"));
363
 
364
                Path p2 = new Path(SaisieVenteFactureSQLElement.this.getTable());
365
                p2 = p2.add(getTable().getField("ID_AVOIR_CLIENT"));
366
 
367
                return CollectionUtils.createSet(new FieldPath(p, "MONTANT"), new FieldPath(p, "REG_COMPTA"), new FieldPath(p, "REGLE"), new FieldPath(p2, "MONTANT_TTC"));
368
            }
369
        };
370
        table.getColumns().add(colAvancement);
371
        colAvancement.setRenderer(new PercentTableCellRenderer());
372
 
373
    }
374
 
18 ilm 375
    protected List<String> getComboFields() {
376
        final List<String> l = new ArrayList<String>();
377
        l.add("NUMERO");
378
        return l;
379
    }
380
 
381
    @Override
382
    public Set<String> getReadOnlyFields() {
383
        Set<String> s = new HashSet<String>(1);
384
        s.add("CONTROLE_TECHNIQUE");
385
        return s;
386
    }
387
 
67 ilm 388
    @Override
389
    public Set<String> getInsertOnlyFields() {
390
        Set<String> s = new HashSet<String>(1);
391
        s.add("ACOMPTE");
392
        return s;
393
    }
394
 
18 ilm 395
    /*
396
     * (non-Javadoc)
397
     *
398
     * @see org.openconcerto.devis.SQLElement#getComponent()
399
     */
400
    public SQLComponent createComponent() {
401
        return new SaisieVenteFactureSQLComponent();
402
    }
403
 
404
    @Override
132 ilm 405
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
406
        for (SQLRow row : trees.getRows()) {
18 ilm 407
 
132 ilm 408
            // On retire l'avoir
409
            if (row.getInt("ID_AVOIR_CLIENT") > 1) {
410
                SQLElement eltAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT");
411
                SQLRow rowAvoir = eltAvoir.getTable().getRow(row.getInt("ID_AVOIR_CLIENT"));
18 ilm 412
 
132 ilm 413
                Long montantSolde = (Long) rowAvoir.getObject("MONTANT_SOLDE");
18 ilm 414
 
132 ilm 415
                Long avoirTTC = (Long) row.getObject("T_AVOIR_TTC");
18 ilm 416
 
132 ilm 417
                long montant = montantSolde - avoirTTC;
418
                if (montant < 0) {
419
                    montant = 0;
420
                }
18 ilm 421
 
132 ilm 422
                SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
18 ilm 423
 
132 ilm 424
                // Soldé
425
                rowVals.put("SOLDE", Boolean.FALSE);
426
                rowVals.put("MONTANT_SOLDE", montant);
427
                Long restant = (Long) rowAvoir.getObject("MONTANT_TTC") - montantSolde;
428
                rowVals.put("MONTANT_RESTANT", restant);
429
                try {
430
                    rowVals.update();
431
                } catch (SQLException e) {
432
                    e.printStackTrace();
433
                }
18 ilm 434
            }
435
 
132 ilm 436
            super.archive(new TreesOfSQLRows(this, row), cutLinks);
437
            SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
438
            if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
18 ilm 439
 
132 ilm 440
                // Mise à jour des stocks
441
                SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
442
                SQLSelect sel = new SQLSelect();
443
                sel.addSelect(eltMvtStock.getTable().getField("ID"));
444
                Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", row.getID());
445
                Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
446
                sel.setWhere(w.and(w2));
18 ilm 447
 
132 ilm 448
                @SuppressWarnings("rawtypes")
449
                List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
450
                if (l != null) {
451
                    for (int i = 0; i < l.size(); i++) {
452
                        Object[] tmp = (Object[]) l.get(i);
453
                        eltMvtStock.archive(((Number) tmp[0]).intValue());
454
                    }
61 ilm 455
                }
18 ilm 456
            }
457
        }
458
    }
459
 
19 ilm 460
    public void transfertBL(int idFacture) {
461
        final SQLElement elt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
462
        final EditFrame editAvoirFrame = new EditFrame(elt);
463
        editAvoirFrame.setIconImage(new ImageIcon(Gestion.class.getResource("frameicon.png")).getImage());
464
 
465
        final BonDeLivraisonSQLComponent comp = (BonDeLivraisonSQLComponent) editAvoirFrame.getSQLComponent();
466
        final SQLInjector inject = SQLInjector.getInjector(this.getTable(), elt.getTable());
467
        SQLRowValues createRowValuesFrom = inject.createRowValuesFrom(idFacture);
468
        SQLRow rowFacture = getTable().getRow(idFacture);
469
        String string = rowFacture.getString("NOM");
470
        createRowValuesFrom.put("NOM", string + (string.trim().length() == 0 ? "" : ", ") + rowFacture.getString("NUMERO"));
471
        comp.select(createRowValuesFrom);
472
        // comp.loadFactureItem(idFacture);
473
 
474
        editAvoirFrame.pack();
475
        editAvoirFrame.setState(JFrame.NORMAL);
476
        editAvoirFrame.setVisible(true);
477
 
478
    }
479
 
73 ilm 480
    /**
481
     * Transfert en commande fournisseur
132 ilm 482
     */
83 ilm 483
    public void transfertCommande(final int idFacture) {
484
        ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
19 ilm 485
 
83 ilm 486
            @Override
487
            public void run() {
488
                SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
489
                SQLTable tableCmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_ELEMENT").getTable();
490
                SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement("ARTICLE");
491
                List<SQLRow> rows = getTable().getRow(idFacture).getReferentRows(elt.getTable());
492
                final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
493
                SQLRow rowDeviseF = null;
494
                for (SQLRow sqlRow : rows) {
495
                    // on récupére l'article qui lui correspond
496
                    SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
497
                    for (SQLField field : eltArticle.getTable().getFields()) {
498
                        if (sqlRow.getTable().getFieldsName().contains(field.getName())) {
499
                            rowArticle.put(field.getName(), sqlRow.getObject(field.getName()));
500
                        }
501
                    }
73 ilm 502
 
83 ilm 503
                    int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
504
                    SQLRow rowArticleFind = eltArticle.getTable().getRow(idArticle);
132 ilm 505
                    if (rowArticleFind != null) {
506
                        SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCmdElt);
507
                        SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticleFind));
508
                        rowValsElt.put("ID_STYLE", sqlRow.getObject("ID_STYLE"));
509
                        rowValsElt.put("QTE", sqlRow.getObject("QTE"));
510
                        rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
19 ilm 511
 
132 ilm 512
                        // gestion de la devise
513
                        rowDeviseF = sqlRow.getForeignRow("ID_DEVISE");
514
                        SQLRow rowDeviseHA = rowArticleFind.getForeignRow("ID_DEVISE_HA");
515
                        BigDecimal qte = new BigDecimal(rowValsElt.getInt("QTE"));
516
                        if (rowDeviseF != null && !rowDeviseF.isUndefined()) {
517
                            if (rowDeviseF.getID() == rowDeviseHA.getID()) {
518
                                rowValsElt.put("PA_DEVISE", rowArticleFind.getObject("PA_DEVISE"));
519
                                rowValsElt.put("PA_DEVISE_T", ((BigDecimal) rowArticleFind.getObject("PA_DEVISE")).multiply(qte, DecimalUtils.HIGH_PRECISION));
520
                                rowValsElt.put("ID_DEVISE", rowDeviseF.getID());
521
                            } else {
522
                                BigDecimal taux = (BigDecimal) rowDeviseF.getObject("TAUX");
523
                                rowValsElt.put("PA_DEVISE", taux.multiply((BigDecimal) rowValsElt.getObject("PA_HT")));
524
                                rowValsElt.put("PA_DEVISE_T", ((BigDecimal) rowValsElt.getObject("PA_DEVISE")).multiply(qte, DecimalUtils.HIGH_PRECISION));
525
                                rowValsElt.put("ID_DEVISE", rowDeviseF.getID());
526
                            }
83 ilm 527
                        }
19 ilm 528
 
132 ilm 529
                        BigDecimal prixHA = (BigDecimal) rowValsElt.getObject("PA_HT");
530
                        rowValsElt.put("T_PA_HT", prixHA.multiply(qte, DecimalUtils.HIGH_PRECISION));
19 ilm 531
 
132 ilm 532
                        rowValsElt.put("T_PA_HT", prixHA.multiply(qte, DecimalUtils.HIGH_PRECISION));
533
                        rowValsElt.put("T_PA_TTC",
534
                                ((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal(rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0), DecimalUtils.HIGH_PRECISION));
19 ilm 535
 
132 ilm 536
                        map.add(rowArticleFind.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
537
                    }
83 ilm 538
                }
539
                MouvementStockSQLElement.createCommandeF(map, rowDeviseF);
19 ilm 540
 
83 ilm 541
            }
542
 
543
        });
544
 
19 ilm 545
    }
90 ilm 546
 
547
    public interface DoWithRow {
548
        public void process(SQLRow row);
549
    }
550
 
551
    Map<String, DoWithRow> specialAction = new HashMap<String, DoWithRow>();
552
 
553
    public DoWithRow getSpecialAction(String key) {
554
        return specialAction.get(key);
555
    }
556
 
557
    public void putSpecialAction(String key, DoWithRow action) {
558
        specialAction.put(key, action);
559
    }
560
 
142 ilm 561
    public void cancelAvoir(final SQLRowAccessor rowFactureOrigin) {
562
        JPanel p = new JPanel(new GridBagLayout());
563
        GridBagConstraints c = new DefaultGridBagConstraints();
564
        c.gridwidth = GridBagConstraints.REMAINDER;
565
        p.add(new JLabel("Voulez annuler l'avoir affecté sur cette facture?"), c);
566
        c.gridwidth = 1;
567
        c.gridy++;
568
        c.gridx = 0;
569
        final JButton buttonApply = new JButton("Appliquer");
570
        JButton buttonAnnuler = new JButton("Fermer");
571
        p.add(buttonApply, c);
572
 
573
        c.gridx++;
574
        p.add(buttonAnnuler, c);
575
        final PanelFrame f = new PanelFrame(p, "Suppression d'un avoir client sur facture");
576
 
577
        buttonAnnuler.addActionListener(new ActionListener() {
578
 
579
            @Override
580
            public void actionPerformed(ActionEvent e) {
581
                f.dispose();
582
            }
583
        });
584
 
585
        buttonApply.addActionListener(new ActionListener() {
586
 
587
            @Override
588
            public void actionPerformed(ActionEvent e) {
589
                long ttc = rowFactureOrigin.getLong("T_TTC");
590
                // long netAPayer = rowFactureOrigin.getLong("NET_A_PAYER");
591
                long avoirTTC = rowFactureOrigin.getLong("T_AVOIR_TTC");
592
                SQLRowAccessor rowAvoir = rowFactureOrigin.getForeign("ID_AVOIR_CLIENT");
593
 
594
                final SQLRowValues createEmptyUpdateRow = rowFactureOrigin.createEmptyUpdateRow();
595
                createEmptyUpdateRow.put("ID_AVOIR_CLIENT", rowFactureOrigin.getTable().getTable("AVOIR_CLIENT").getUndefinedID());
596
                createEmptyUpdateRow.put("NET_A_PAYER", ttc);
597
                createEmptyUpdateRow.put("T_AVOIR_TTC", 0L);
598
                try {
599
                    SQLRow rowFacture = createEmptyUpdateRow.commit();
600
 
601
                    // long restant = totalAvoirTTC - totalAvoirApplique;
602
 
603
                    SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
604
                    rowVals.put("SOLDE", Boolean.FALSE);
605
                    rowVals.put("MONTANT_SOLDE", 0L);
606
                    rowVals.put("MONTANT_RESTANT", avoirTTC);
607
                    rowVals.update();
608
 
609
                    EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
610
                    final int foreignIDmvt = rowFacture.getForeignID("ID_MOUVEMENT");
611
                    eltEcr.archiveMouvementProfondeur(foreignIDmvt, false);
612
 
613
                    System.err.println("Regeneration des ecritures");
614
                    new GenerationMvtSaisieVenteFacture(rowFacture.getID(), foreignIDmvt);
615
                    System.err.println("Fin regeneration");
616
                } catch (SQLException e1) {
617
                    ExceptionHandler.handle("Erreur lors de l'affection de l'avoir sur la facture!", e1);
618
                } finally {
619
                    f.dispose();
620
                }
621
 
622
            }
623
        });
624
        SwingUtilities.invokeLater(new Runnable() {
625
 
626
            @Override
627
            public void run() {
628
 
629
                FrameUtil.showPacked(f);
630
            }
631
 
632
        });
633
    }
156 ilm 634
 
635
    @Override
636
    protected String createCode() {
637
        return "sales.invoice";
638
    }
18 ilm 639
}