OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Rev 182 | Go to most recent revision | 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) {
180 ilm 210
                if (!isFilling()) {
211
                    Acompte a = acompteField.getValue();
212
                    table.calculPourcentage(a, TypeCalcul.CALCUL_FACTURABLE);
213
                }
80 ilm 214
            }
177 ilm 215
 
216
        };
217
        acompteField.getDocument().addDocumentListener(listenerAcompteField);
218
 
219
        listenerTable = new TableModelListener() {
220
 
221
            @Override
222
            public void tableChanged(TableModelEvent e) {
223
                acompteField.getDocument().removeDocumentListener(listenerAcompteField);
224
                if (e.getColumn() == table.getModel().getColumnForField("POURCENT_FACTURABLE")) {
225
                    Acompte a = new Acompte(null, table.getTotalHT(TypeCalcul.CALCUL_MONTANT_TOTAL));
226
                    acompteField.setValue(a);
227
 
228
                }
229
                acompteField.getDocument().addDocumentListener(listenerAcompteField);
230
            }
231
 
232
        };
233
        table.getRowValuesTable().getModel().addTableModelListener(listenerTable);
80 ilm 234
        total.addValueListener(new PropertyChangeListener() {
235
 
236
            @Override
237
            public void propertyChange(PropertyChangeEvent evt) {
238
                acompteField.setTotal(new BigDecimal(total.getTotalHT()).movePointLeft(2));
239
 
240
            }
241
        });
242
 
243
    }
244
 
177 ilm 245
    private SimpleDocumentListener listenerAcompteField;
246
    private TableModelListener listenerTable;
83 ilm 247
 
80 ilm 248
    @Override
249
    public JComponent getLabel(String id) {
250
        if (id.equals("sales.invoice.partial.amount")) {
132 ilm 251
            final JLabel jLabel = new JLabel("Montant HT (ou %) à facturer");
80 ilm 252
            jLabel.setHorizontalAlignment(SwingConstants.RIGHT);
253
            return jLabel;
142 ilm 254
        } else if (id.equals("panel.oo")) {
255
            return new JLabel();
80 ilm 256
        } else if (id.equals("sales.invoice.partial.total.amount")) {
257
            return new JLabel();
258
        } else {
259
            return super.getLabel(id);
260
        }
261
    }
262
 
263
    JUniqueTextField numberField;
264
 
265
    @Override
266
    public JComponent createEditor(String id) {
267
 
268
        if (id.equals("sales.invoice.number")) {
142 ilm 269
            this.numberField = new JUniqueTextField(20) {
270
                @Override
271
                public String getAutoRefreshNumber() {
272
                    if (getMode() == Mode.INSERTION) {
273
                        return NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), ((JDate) getEditor("DATE")).getDate());
274
                    } else {
275
                        return null;
276
                    }
277
                }
278
            };
80 ilm 279
            return this.numberField;
142 ilm 280
        } else if (id.equals("panel.oo")) {
281
            this.panelOO = new PanelOOSQLComponent(this);
282
            return this.panelOO;
80 ilm 283
        } else if (id.equals("INFOS")) {
284
            final ITextArea jTextArea = new ITextArea();
285
            jTextArea.setFont(new JLabel().getFont());
286
            return jTextArea;
287
        } else if (id.equals("sales.invoice.partial.items.list")) {
288
            return new FactureSituationItemTable();
289
        } else if (id.equals("DATE")) {
290
            return new JDate(true);
291
        } else if (id.equals("T_POIDS")) {
292
            return new JTextField();
293
        } else if (id.equals("sales.invoice.partial.total.amount")) {
294
            final AbstractArticleItemTable items = (AbstractArticleItemTable) getEditor("sales.invoice.partial.items.list");
295
            // Set only VAT Editable
296
            for (int i = 0; i < items.getRowValuesTable().getColumnModel().getColumnCount(false); i++) {
297
                final SQLTableElement sqlTableElementAt = items.getRowValuesTable().getRowValuesTableModel().getSQLTableElementAt(i);
177 ilm 298
                if (sqlTableElementAt.getField() != null && (sqlTableElementAt.getField().getName().equalsIgnoreCase("ID_STYLE")
299
                        || sqlTableElementAt.getField().getName().equalsIgnoreCase("POURCENT_FACTURABLE") || sqlTableElementAt.getField().getName().equalsIgnoreCase("ID_TAXE"))) {
300
                    sqlTableElementAt.setEditable(true);
301
                } else {
80 ilm 302
                    sqlTableElementAt.setEditable(false);
303
                }
304
            }
305
 
306
            final DeviseField totalHT = (DeviseField) getEditor("T_HT");
142 ilm 307
            final DeviseField totalEco = (DeviseField) getEditor("T_ECO_CONTRIBUTION");
80 ilm 308
            final DeviseField totalService = (DeviseField) getEditor("T_SERVICE");
309
            final DeviseField totalSupply = (DeviseField) getEditor("T_HA");
310
            final DeviseField totalDevise = (DeviseField) getEditor("T_DEVISE");
311
            final JTextField totalWeight = (JTextField) getEditor("T_POIDS");
312
            final DeviseField totalTTC = (DeviseField) getEditor("T_TTC");
313
            final DeviseField totalTVA = (DeviseField) getEditor("T_TVA");
314
            final DeviseField totalRemise = (DeviseField) getEditor("REMISE_HT");
142 ilm 315
            totalRemise.setEditable(false);
316
            totalRemise.setEnabled(false);
317
            final AcompteField acompte = (AcompteField) getEditor("sales.invoice.partial.amount");
80 ilm 318
            final DeviseField totalPORT = (DeviseField) getEditor("PORT_HT");
142 ilm 319
            final SQLRequestComboBox taxePort = (SQLRequestComboBox) getEditor("ID_TAXE_PORT");
320
            return new TotalPanel(items, totalEco, totalHT, totalTVA, totalTTC, totalPORT, totalRemise, totalService, totalSupply, totalDevise, totalWeight, null, taxePort, acompte);
80 ilm 321
        } else if (id.startsWith("T_")) {
322
            return new DeviseField();
323
        } else if (id.equals("REMISE_HT") || id.equals("PORT_HT")) {
142 ilm 324
            DeviseField fieldD = new DeviseField();
325
            fieldD.setEditable(false);
326
            fieldD.setEnabled(false);
327
            return fieldD;
144 ilm 328
        } else if (id.startsWith("ID_ADRESSE")) {
329
            ElementComboBox comboAdrF = new ElementComboBox();
330
            comboAdrF.setButtonsVisible(false);
331
            final SQLElement adrElement = getElement().getForeignElement("ID_ADRESSE");
332
            comboAdrF.init(adrElement, adrElement.getComboRequest(true));
333
            comboAdrF.getRequest().setWhere(Where.FALSE);
334
            return comboAdrF;
80 ilm 335
        } else if (id.equals("sales.invoice.partial.amount")) {
336
            return new AcompteField();
337
        }
338
        return super.createEditor(id);
339
    }
340
 
341
    private final SQLTable tableNum = getElement().getTable().getTable("NUMEROTATION_AUTO");
342
 
343
    @Override
344
    public int insert(SQLRow order) {
345
 
346
        int idSaisieVF = SQLRow.NONEXISTANT_ID;
347
 
142 ilm 348
        int attempt = 0;
349
        // on verifie qu'un devis du meme numero n'a pas été inséré entre temps
350
        if (!this.numberField.checkValidation(false)) {
351
            while (attempt < JUniqueTextField.RETRY_COUNT) {
352
                String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), ((JDate) getEditor("DATE")).getDate());
353
                this.numberField.setText(num);
354
                attempt++;
355
                if (this.numberField.checkValidation(false)) {
356
                    System.err.println("ATEMPT " + attempt + " SUCCESS WITH NUMERO " + num);
357
                    break;
358
                }
359
                try {
360
                    Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
361
                } catch (InterruptedException e) {
362
                    e.printStackTrace();
363
                }
364
            }
365
        }
366
        final String num = this.numberField.getText();
367
        if (attempt == JUniqueTextField.RETRY_COUNT) {
368
            idSaisieVF = getSelectedID();
369
            ExceptionHandler.handle("Impossible d'ajouter, numéro de facture existant.");
370
            final Object root = SwingUtilities.getRoot(this);
371
            if (root instanceof EditFrame) {
372
                final EditFrame frame = (EditFrame) root;
373
                frame.getPanel().setAlwaysVisible(true);
374
            }
375
        } else {
80 ilm 376
            idSaisieVF = super.insert(order);
377
            SQLRow rowFacture = getTable().getRow(idSaisieVF);
378
            // incrémentation du numéro auto
379
            if (NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, rowFacture.getDate("DATE").getTime()).equalsIgnoreCase(this.numberField.getText().trim())) {
380
                SQLRowValues rowVals = new SQLRowValues(this.tableNum);
381
 
382
                String labelNumberFor = NumerotationAutoSQLElement.getLabelNumberFor(SaisieVenteFactureSQLElement.class);
383
                int val = this.tableNum.getRow(2).getInt(labelNumberFor);
384
                val++;
385
                rowVals.put(labelNumberFor, Integer.valueOf(val));
386
                try {
387
                    rowVals.update(2);
388
                } catch (SQLException e1) {
389
                    e1.printStackTrace();
390
                }
132 ilm 391
            }
392
            ((AbstractArticleItemTable) getEditor("sales.invoice.partial.items.list")).updateField("ID_SAISIE_VENTE_FACTURE", idSaisieVF);
80 ilm 393
 
132 ilm 394
            new GenerationMvtSaisieVenteFacture(idSaisieVF);
80 ilm 395
 
132 ilm 396
            try {
397
                VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowFacture);
398
                sheet.createDocument();
142 ilm 399
                sheet.showPrintAndExport(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
132 ilm 400
            } catch (Exception e) {
401
                ExceptionHandler.handle("Une erreur est survenue lors de la création du document.", e);
402
            }
142 ilm 403
            if (attempt > 0) {
404
                SwingUtilities.invokeLater(new Runnable() {
405
                    public void run() {
406
                        JOptionPane.showMessageDialog(null, "Le numéro a été actualisé en " + num);
407
                    }
408
                });
80 ilm 409
            }
410
        }
411
        return idSaisieVF;
412
    }
413
 
414
    @Override
415
    public void update() {
416
 
142 ilm 417
        int id = getSelectedID();
80 ilm 418
        super.update();
142 ilm 419
        final SQLRow rowFacture = getTable().getRow(id);
80 ilm 420
        ((AbstractArticleItemTable) getEditor("sales.invoice.partial.items.list")).updateField("ID_SAISIE_VENTE_FACTURE", id);
421
 
142 ilm 422
        int idMvt = rowFacture.getInt("ID_MOUVEMENT");
423
        // on supprime tout ce qui est lié à la facture
424
        System.err.println("Archivage des fils");
425
        EcritureSQLElement eltEcr = (EcritureSQLElement) getDirectory().getElement("ECRITURE");
426
        eltEcr.archiveMouvementProfondeur(idMvt, false);
427
        new GenerationMvtSaisieVenteFacture(id);
428
        try {
429
            VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowFacture);
430
            sheet.createDocument();
431
            sheet.showPrintAndExport(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
432
        } catch (Exception e) {
433
            ExceptionHandler.handle("Une erreur est survenue lors de la création du document.", e);
434
        }
80 ilm 435
    }
436
 
437
    @Override
438
    protected SQLRowValues createDefaults() {
439
        SQLRowValues rowVals = new SQLRowValues(getTable());
440
        rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date()));
441
        rowVals.put("PARTIAL", Boolean.TRUE);
442
        return rowVals;
443
    }
444
 
445
    @Override
446
    public Component addView(JComponent comp, String id) {
447
        if (id.equals("sales.invoice.partial.amount")) {
448
            return super.addView(new AcompteRowItemView((AcompteField) comp), "MONTANT_FACTURABLE,POURCENT_FACTURABLE", REQ);
449
        } else {
450
            return super.addView(comp, id);
451
        }
452
    }
453
}