OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
80 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.account;
15
 
16
import org.openconcerto.erp.core.common.component.TransfertGroupSQLComponent;
17
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
18
import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable;
132 ilm 19
import org.openconcerto.erp.core.common.ui.AbstractVenteArticleItemTable.TypeCalcul;
80 ilm 20
import org.openconcerto.erp.core.common.ui.Acompte;
21
import org.openconcerto.erp.core.common.ui.AcompteField;
22
import org.openconcerto.erp.core.common.ui.AcompteRowItemView;
23
import org.openconcerto.erp.core.common.ui.DeviseField;
24
import org.openconcerto.erp.core.common.ui.TotalPanel;
156 ilm 25
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
142 ilm 26
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
80 ilm 27
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
28
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
29
import org.openconcerto.erp.core.sales.invoice.ui.FactureSituationItemTable;
30
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
142 ilm 31
import org.openconcerto.erp.panel.PanelOOSQLComponent;
80 ilm 32
import org.openconcerto.sql.Configuration;
33
import org.openconcerto.sql.element.ElementSQLObject;
83 ilm 34
import org.openconcerto.sql.element.GlobalMapper;
80 ilm 35
import org.openconcerto.sql.element.SQLElement;
36
import org.openconcerto.sql.model.SQLRow;
142 ilm 37
import org.openconcerto.sql.model.SQLRowAccessor;
80 ilm 38
import org.openconcerto.sql.model.SQLRowValues;
39
import org.openconcerto.sql.model.SQLTable;
144 ilm 40
import org.openconcerto.sql.model.Where;
41
import org.openconcerto.sql.sqlobject.ElementComboBox;
80 ilm 42
import org.openconcerto.sql.sqlobject.JUniqueTextField;
43
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
44
import org.openconcerto.sql.view.EditFrame;
45
import org.openconcerto.sql.view.list.RowValuesTable;
46
import org.openconcerto.sql.view.list.SQLTableElement;
47
import org.openconcerto.ui.JDate;
48
import org.openconcerto.ui.component.ITextArea;
49
import org.openconcerto.ui.group.Group;
50
import org.openconcerto.utils.ExceptionHandler;
51
import org.openconcerto.utils.text.SimpleDocumentListener;
52
 
53
import java.awt.Component;
54
import java.beans.PropertyChangeEvent;
55
import java.beans.PropertyChangeListener;
56
import java.math.BigDecimal;
57
import java.sql.SQLException;
58
import java.util.Date;
59
import java.util.HashSet;
60
import java.util.Set;
61
 
62
import javax.swing.JCheckBox;
63
import javax.swing.JComponent;
64
import javax.swing.JLabel;
142 ilm 65
import javax.swing.JOptionPane;
80 ilm 66
import javax.swing.JTextField;
67
import javax.swing.SwingConstants;
68
import javax.swing.SwingUtilities;
69
import javax.swing.event.DocumentEvent;
177 ilm 70
import javax.swing.event.TableModelEvent;
71
import javax.swing.event.TableModelListener;
80 ilm 72
 
73
public class VenteFactureSituationSQLComponent extends TransfertGroupSQLComponent {
74
    public static final String ID = "sales.invoice.partial";
75
 
142 ilm 76
    private PanelOOSQLComponent panelOO;
77
 
80 ilm 78
    public VenteFactureSituationSQLComponent(SQLElement element) {
83 ilm 79
        super(element, (Group) GlobalMapper.getInstance().get(ID));
80 ilm 80
    }
81
 
82
    public VenteFactureSituationSQLComponent(SQLElement element, Group p) {
83
        super(element, p);
84
    }
85
 
86
    @Override
87
    protected Set<String> createRequiredNames() {
88
        final Set<String> s = new HashSet<String>(1);
89
        s.add("ID_CLIENT");
142 ilm 90
        s.add("ID_COMMERCIAL");
80 ilm 91
        s.add("NUMERO");
92
        s.add("DATE");
93
        s.add("MONTANT_FACTURABLE");
94
        s.add("ID_MODE_REGLEMENT");
95
        return s;
96
    }
97
 
98
    @Override
99
    protected RowValuesTable getRowValuesTable() {
100
 
101
        return ((AbstractArticleItemTable) getEditor("sales.invoice.partial.items.list")).getRowValuesTable();
102
    }
103
 
104
    JCheckBox box = new JCheckBox("partial");
105
 
106
    @Override
142 ilm 107
    public void select(SQLRowAccessor r) {
108
        super.select(r);
109
        final DeviseField totalRemise = (DeviseField) getEditor("REMISE_HT");
110
        totalRemise.setEditable(false);
111
        totalRemise.setEnabled(false);
112
    }
113
 
114
    @Override
80 ilm 115
    protected void addViews() {
116
 
117
        super.addViews();
118
 
119
        box.setSelected(true);
120
        this.addView(box, "PARTIAL", REQ);
121
 
122
        final DeviseField totalHT = (DeviseField) getEditor("T_HT");
123
        final DeviseField totalService = (DeviseField) getEditor("T_SERVICE");
124
        final DeviseField totalSupply = (DeviseField) getEditor("T_HA");
125
        final DeviseField totalDevise = (DeviseField) getEditor("T_DEVISE");
126
        final JTextField totalWeight = (JTextField) getEditor("T_POIDS");
127
        final DeviseField totalTTC = (DeviseField) getEditor("T_TTC");
128
        final DeviseField totalTVA = (DeviseField) getEditor("T_TVA");
142 ilm 129
        final DeviseField totalEco = (DeviseField) getEditor("T_ECO_CONTRIBUTION");
80 ilm 130
        final DeviseField totalRemise = (DeviseField) getEditor("REMISE_HT");
142 ilm 131
        totalRemise.setEditable(false);
132
        totalRemise.setEnabled(false);
80 ilm 133
        final DeviseField totalPORT = (DeviseField) getEditor("PORT_HT");
134
        this.addView(totalPORT, "PORT_HT");
135
        this.addView(totalTVA, "T_TVA");
136
        this.addView(totalTTC, "T_TTC");
142 ilm 137
        this.addView(totalEco, "T_ECO_CONTRIBUTION");
80 ilm 138
        this.addView(totalWeight, "T_POIDS");
139
        this.addView(totalDevise, "T_DEVISE");
140
        this.addView(totalSupply, "T_HA");
141
        this.addView(totalService, "T_SERVICE");
142
        this.addView(totalHT, "T_HT");
143
 
132 ilm 144
        final DeviseField fieldNet = new DeviseField();
145
        this.addView(fieldNet, "NET_A_PAYER");
146
        totalTTC.getDocument().addDocumentListener(new SimpleDocumentListener() {
147
 
148
            @Override
149
            public void update(DocumentEvent e) {
150
                fieldNet.setText(totalTTC.getText());
151
            }
152
        });
153
 
144 ilm 154
        final SQLRequestComboBox sqlRequestComboBoxAdr = (SQLRequestComboBox) getEditor("ID_ADRESSE");
155
        final SQLRequestComboBox sqlRequestComboBoxAdrL = (SQLRequestComboBox) getEditor("ID_ADRESSE_LIVRAISON");
156
 
80 ilm 157
        final SQLRequestComboBox sqlRequestComboBox = (SQLRequestComboBox) getEditor("sales.invoice.customer");
156 ilm 158
        final FactureSituationItemTable table = ((FactureSituationItemTable) getEditor("sales.invoice.partial.items.list"));
159
        final TotalPanel total = ((TotalPanel) getEditor("sales.invoice.partial.total.amount"));
160
 
80 ilm 161
        sqlRequestComboBox.addModelListener("wantedID", new PropertyChangeListener() {
162
 
163
            @Override
164
            public void propertyChange(PropertyChangeEvent evt) {
165
 
144 ilm 166
                int wantedID = sqlRequestComboBox.getWantedID();
167
 
168
                if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
169
 
170
                    sqlRequestComboBoxAdr.getRequest().setWhere(new Where(getTable().getTable("ADRESSE").getField("ID_CLIENT"), "=", wantedID)
171
                            .and(new Where(getTable().getTable("ADRESSE").getField("TYPE"), "=", AdresseType.Invoice.getId())));
172
                    sqlRequestComboBoxAdrL.getRequest().setWhere(new Where(getTable().getTable("ADRESSE").getField("ID_CLIENT"), "=", wantedID)
173
                            .and(new Where(getTable().getTable("ADRESSE").getField("TYPE"), "=", AdresseType.Delivery.getId())));
156 ilm 174
                    SQLRow rowCli = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
175
                    if (rowCli.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowCli.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
176
                        total.setCategorieComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
177
                        table.setRowCatComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
178
                    } else {
179
                        total.setCategorieComptable(null);
180
                        table.setRowCatComptable(null);
181
                    }
144 ilm 182
                } else {
183
                    sqlRequestComboBoxAdr.getRequest().setWhere(Where.FALSE);
184
                    sqlRequestComboBoxAdrL.getRequest().setWhere(Where.FALSE);
156 ilm 185
                    total.setCategorieComptable(null);
186
                    table.setRowCatComptable(null);
144 ilm 187
                }
188
 
80 ilm 189
                SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
190
                final SQLRow client = sqlRequestComboBox.getSelectedRow();
191
                if (client != null && !client.isUndefined()) {
192
                    int idModeRegl = client.getInt("ID_MODE_REGLEMENT");
193
                    if (idModeRegl > 1) {
194
                        SQLRow rowModeRegl = sqleltModeRegl.getTable().getRow(idModeRegl);
195
                        SQLRowValues rowValsModeRegl = rowModeRegl.createUpdateRow();
196
                        rowValsModeRegl.clearPrimaryKeys();
197
                        ((ElementSQLObject) getEditor("ID_MODE_REGLEMENT")).setValue(rowValsModeRegl);
198
                    }
199
                }
200
 
201
            }
202
        });
203
        sqlRequestComboBox.setEnabled(false);
204
 
205
        final AcompteField acompteField = ((AcompteField) getEditor("sales.invoice.partial.amount"));
177 ilm 206
        listenerAcompteField = new SimpleDocumentListener() {
80 ilm 207
 
208
            @Override
209
            public void update(DocumentEvent e) {
210
                Acompte a = acompteField.getValue();
94 ilm 211
                table.calculPourcentage(a, TypeCalcul.CALCUL_FACTURABLE);
80 ilm 212
            }
177 ilm 213
 
214
        };
215
        acompteField.getDocument().addDocumentListener(listenerAcompteField);
216
 
217
        listenerTable = new TableModelListener() {
218
 
219
            @Override
220
            public void tableChanged(TableModelEvent e) {
221
                acompteField.getDocument().removeDocumentListener(listenerAcompteField);
222
                if (e.getColumn() == table.getModel().getColumnForField("POURCENT_FACTURABLE")) {
223
                    Acompte a = new Acompte(null, table.getTotalHT(TypeCalcul.CALCUL_MONTANT_TOTAL));
224
                    acompteField.setValue(a);
225
 
226
                }
227
                acompteField.getDocument().addDocumentListener(listenerAcompteField);
228
            }
229
 
230
        };
231
        table.getRowValuesTable().getModel().addTableModelListener(listenerTable);
80 ilm 232
        total.addValueListener(new PropertyChangeListener() {
233
 
234
            @Override
235
            public void propertyChange(PropertyChangeEvent evt) {
236
                acompteField.setTotal(new BigDecimal(total.getTotalHT()).movePointLeft(2));
237
 
238
            }
239
        });
240
 
241
    }
242
 
177 ilm 243
    private SimpleDocumentListener listenerAcompteField;
244
    private TableModelListener listenerTable;
83 ilm 245
 
80 ilm 246
    @Override
247
    public JComponent getLabel(String id) {
248
        if (id.equals("sales.invoice.partial.amount")) {
132 ilm 249
            final JLabel jLabel = new JLabel("Montant HT (ou %) à facturer");
80 ilm 250
            jLabel.setHorizontalAlignment(SwingConstants.RIGHT);
251
            return jLabel;
142 ilm 252
        } else if (id.equals("panel.oo")) {
253
            return new JLabel();
80 ilm 254
        } else if (id.equals("sales.invoice.partial.total.amount")) {
255
            return new JLabel();
256
        } else {
257
            return super.getLabel(id);
258
        }
259
    }
260
 
261
    JUniqueTextField numberField;
262
 
263
    @Override
264
    public JComponent createEditor(String id) {
265
 
266
        if (id.equals("sales.invoice.number")) {
142 ilm 267
            this.numberField = new JUniqueTextField(20) {
268
                @Override
269
                public String getAutoRefreshNumber() {
270
                    if (getMode() == Mode.INSERTION) {
271
                        return NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), ((JDate) getEditor("DATE")).getDate());
272
                    } else {
273
                        return null;
274
                    }
275
                }
276
            };
80 ilm 277
            return this.numberField;
142 ilm 278
        } else if (id.equals("panel.oo")) {
279
            this.panelOO = new PanelOOSQLComponent(this);
280
            return this.panelOO;
80 ilm 281
        } else if (id.equals("INFOS")) {
282
            final ITextArea jTextArea = new ITextArea();
283
            jTextArea.setFont(new JLabel().getFont());
284
            return jTextArea;
285
        } else if (id.equals("sales.invoice.partial.items.list")) {
286
            return new FactureSituationItemTable();
287
        } else if (id.equals("DATE")) {
288
            return new JDate(true);
289
        } else if (id.equals("T_POIDS")) {
290
            return new JTextField();
291
        } else if (id.equals("sales.invoice.partial.total.amount")) {
292
            final AbstractArticleItemTable items = (AbstractArticleItemTable) getEditor("sales.invoice.partial.items.list");
293
            // Set only VAT Editable
294
            for (int i = 0; i < items.getRowValuesTable().getColumnModel().getColumnCount(false); i++) {
295
                final SQLTableElement sqlTableElementAt = items.getRowValuesTable().getRowValuesTableModel().getSQLTableElementAt(i);
177 ilm 296
                if (sqlTableElementAt.getField() != null && (sqlTableElementAt.getField().getName().equalsIgnoreCase("ID_STYLE")
297
                        || sqlTableElementAt.getField().getName().equalsIgnoreCase("POURCENT_FACTURABLE") || sqlTableElementAt.getField().getName().equalsIgnoreCase("ID_TAXE"))) {
298
                    sqlTableElementAt.setEditable(true);
299
                } else {
80 ilm 300
                    sqlTableElementAt.setEditable(false);
301
                }
302
            }
303
 
304
            final DeviseField totalHT = (DeviseField) getEditor("T_HT");
142 ilm 305
            final DeviseField totalEco = (DeviseField) getEditor("T_ECO_CONTRIBUTION");
80 ilm 306
            final DeviseField totalService = (DeviseField) getEditor("T_SERVICE");
307
            final DeviseField totalSupply = (DeviseField) getEditor("T_HA");
308
            final DeviseField totalDevise = (DeviseField) getEditor("T_DEVISE");
309
            final JTextField totalWeight = (JTextField) getEditor("T_POIDS");
310
            final DeviseField totalTTC = (DeviseField) getEditor("T_TTC");
311
            final DeviseField totalTVA = (DeviseField) getEditor("T_TVA");
312
            final DeviseField totalRemise = (DeviseField) getEditor("REMISE_HT");
142 ilm 313
            totalRemise.setEditable(false);
314
            totalRemise.setEnabled(false);
315
            final AcompteField acompte = (AcompteField) getEditor("sales.invoice.partial.amount");
80 ilm 316
            final DeviseField totalPORT = (DeviseField) getEditor("PORT_HT");
142 ilm 317
            final SQLRequestComboBox taxePort = (SQLRequestComboBox) getEditor("ID_TAXE_PORT");
318
            return new TotalPanel(items, totalEco, totalHT, totalTVA, totalTTC, totalPORT, totalRemise, totalService, totalSupply, totalDevise, totalWeight, null, taxePort, acompte);
80 ilm 319
        } else if (id.startsWith("T_")) {
320
            return new DeviseField();
321
        } else if (id.equals("REMISE_HT") || id.equals("PORT_HT")) {
142 ilm 322
            DeviseField fieldD = new DeviseField();
323
            fieldD.setEditable(false);
324
            fieldD.setEnabled(false);
325
            return fieldD;
144 ilm 326
        } else if (id.startsWith("ID_ADRESSE")) {
327
            ElementComboBox comboAdrF = new ElementComboBox();
328
            comboAdrF.setButtonsVisible(false);
329
            final SQLElement adrElement = getElement().getForeignElement("ID_ADRESSE");
330
            comboAdrF.init(adrElement, adrElement.getComboRequest(true));
331
            comboAdrF.getRequest().setWhere(Where.FALSE);
332
            return comboAdrF;
80 ilm 333
        } else if (id.equals("sales.invoice.partial.amount")) {
334
            return new AcompteField();
335
        }
336
        return super.createEditor(id);
337
    }
338
 
339
    private final SQLTable tableNum = getElement().getTable().getTable("NUMEROTATION_AUTO");
340
 
341
    @Override
342
    public int insert(SQLRow order) {
343
 
344
        int idSaisieVF = SQLRow.NONEXISTANT_ID;
345
 
142 ilm 346
        int attempt = 0;
347
        // on verifie qu'un devis du meme numero n'a pas été inséré entre temps
348
        if (!this.numberField.checkValidation(false)) {
349
            while (attempt < JUniqueTextField.RETRY_COUNT) {
350
                String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), ((JDate) getEditor("DATE")).getDate());
351
                this.numberField.setText(num);
352
                attempt++;
353
                if (this.numberField.checkValidation(false)) {
354
                    System.err.println("ATEMPT " + attempt + " SUCCESS WITH NUMERO " + num);
355
                    break;
356
                }
357
                try {
358
                    Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
359
                } catch (InterruptedException e) {
360
                    e.printStackTrace();
361
                }
362
            }
363
        }
364
        final String num = this.numberField.getText();
365
        if (attempt == JUniqueTextField.RETRY_COUNT) {
366
            idSaisieVF = getSelectedID();
367
            ExceptionHandler.handle("Impossible d'ajouter, numéro de facture existant.");
368
            final Object root = SwingUtilities.getRoot(this);
369
            if (root instanceof EditFrame) {
370
                final EditFrame frame = (EditFrame) root;
371
                frame.getPanel().setAlwaysVisible(true);
372
            }
373
        } else {
80 ilm 374
            idSaisieVF = super.insert(order);
375
            SQLRow rowFacture = getTable().getRow(idSaisieVF);
376
            // incrémentation du numéro auto
377
            if (NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, rowFacture.getDate("DATE").getTime()).equalsIgnoreCase(this.numberField.getText().trim())) {
378
                SQLRowValues rowVals = new SQLRowValues(this.tableNum);
379
 
380
                String labelNumberFor = NumerotationAutoSQLElement.getLabelNumberFor(SaisieVenteFactureSQLElement.class);
381
                int val = this.tableNum.getRow(2).getInt(labelNumberFor);
382
                val++;
383
                rowVals.put(labelNumberFor, Integer.valueOf(val));
384
                try {
385
                    rowVals.update(2);
386
                } catch (SQLException e1) {
387
                    e1.printStackTrace();
388
                }
132 ilm 389
            }
390
            ((AbstractArticleItemTable) getEditor("sales.invoice.partial.items.list")).updateField("ID_SAISIE_VENTE_FACTURE", idSaisieVF);
80 ilm 391
 
132 ilm 392
            new GenerationMvtSaisieVenteFacture(idSaisieVF);
80 ilm 393
 
132 ilm 394
            try {
395
                VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowFacture);
396
                sheet.createDocument();
142 ilm 397
                sheet.showPrintAndExport(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
132 ilm 398
            } catch (Exception e) {
399
                ExceptionHandler.handle("Une erreur est survenue lors de la création du document.", e);
400
            }
142 ilm 401
            if (attempt > 0) {
402
                SwingUtilities.invokeLater(new Runnable() {
403
                    public void run() {
404
                        JOptionPane.showMessageDialog(null, "Le numéro a été actualisé en " + num);
405
                    }
406
                });
80 ilm 407
            }
408
        }
409
        return idSaisieVF;
410
    }
411
 
412
    @Override
413
    public void update() {
414
 
142 ilm 415
        int id = getSelectedID();
80 ilm 416
        super.update();
142 ilm 417
        final SQLRow rowFacture = getTable().getRow(id);
80 ilm 418
        ((AbstractArticleItemTable) getEditor("sales.invoice.partial.items.list")).updateField("ID_SAISIE_VENTE_FACTURE", id);
419
 
142 ilm 420
        int idMvt = rowFacture.getInt("ID_MOUVEMENT");
421
        // on supprime tout ce qui est lié à la facture
422
        System.err.println("Archivage des fils");
423
        EcritureSQLElement eltEcr = (EcritureSQLElement) getDirectory().getElement("ECRITURE");
424
        eltEcr.archiveMouvementProfondeur(idMvt, false);
425
        new GenerationMvtSaisieVenteFacture(id);
426
        try {
427
            VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowFacture);
428
            sheet.createDocument();
429
            sheet.showPrintAndExport(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
430
        } catch (Exception e) {
431
            ExceptionHandler.handle("Une erreur est survenue lors de la création du document.", e);
432
        }
80 ilm 433
    }
434
 
435
    @Override
436
    protected SQLRowValues createDefaults() {
437
        SQLRowValues rowVals = new SQLRowValues(getTable());
438
        rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date()));
439
        rowVals.put("PARTIAL", Boolean.TRUE);
440
        return rowVals;
441
    }
442
 
443
    @Override
444
    public Component addView(JComponent comp, String id) {
445
        if (id.equals("sales.invoice.partial.amount")) {
446
            return super.addView(new AcompteRowItemView((AcompteField) comp), "MONTANT_FACTURABLE,POURCENT_FACTURABLE", REQ);
447
        } else {
448
            return super.addView(comp, id);
449
        }
450
    }
451
}