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