OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
93 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.customerrelationship.customer.element;
15
 
16
import org.openconcerto.erp.core.common.component.AdresseSQLComponent;
17
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
18
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseClientItemTable;
177 ilm 19
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
144 ilm 20
import org.openconcerto.erp.core.sales.product.element.ClientCodeArticleTable;
174 ilm 21
import org.openconcerto.erp.core.sales.product.ui.CustomerProductQtyPriceListTable;
177 ilm 22
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
132 ilm 23
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
94 ilm 24
import org.openconcerto.erp.utils.TM;
93 ilm 25
import org.openconcerto.sql.Configuration;
26
import org.openconcerto.sql.element.ElementSQLObject;
27
import org.openconcerto.sql.element.GroupSQLComponent;
28
import org.openconcerto.sql.element.SQLElement;
29
import org.openconcerto.sql.model.SQLRow;
30
import org.openconcerto.sql.model.SQLRowAccessor;
31
import org.openconcerto.sql.model.SQLRowValues;
177 ilm 32
import org.openconcerto.sql.model.SQLSelect;
93 ilm 33
import org.openconcerto.sql.model.SQLTable;
34
import org.openconcerto.sql.model.UndefinedRowValuesCache;
177 ilm 35
import org.openconcerto.sql.model.Where;
36
import org.openconcerto.sql.preferences.SQLPreferences;
93 ilm 37
import org.openconcerto.sql.sqlobject.JUniqueTextField;
38
import org.openconcerto.sql.sqlobject.SQLSearchableTextCombo;
39
import org.openconcerto.sql.ui.textmenu.TextFieldWithMenu;
40
import org.openconcerto.sql.ui.textmenu.TextFieldWithMenuItemsTableFetcher;
41
import org.openconcerto.sql.ui.textmenu.TextFieldWithWebBrowsing;
42
import org.openconcerto.sql.view.EditFrame;
43
import org.openconcerto.sql.view.EditPanel.EditMode;
44
import org.openconcerto.sql.view.IListFrame;
45
import org.openconcerto.sql.view.ListeAddPanel;
46
import org.openconcerto.ui.DefaultGridBagConstraints;
47
import org.openconcerto.ui.FrameUtil;
48
import org.openconcerto.ui.JDate;
49
import org.openconcerto.ui.JLabelBold;
50
import org.openconcerto.ui.component.ComboLockedMode;
51
import org.openconcerto.ui.component.ITextArea;
52
import org.openconcerto.ui.component.InteractionMode;
142 ilm 53
import org.openconcerto.utils.ExceptionHandler;
93 ilm 54
 
94 ilm 55
import java.awt.Component;
56
import java.awt.Dimension;
177 ilm 57
import java.awt.Font;
94 ilm 58
import java.awt.GridBagConstraints;
59
import java.awt.GridBagLayout;
60
import java.awt.event.ActionEvent;
61
import java.awt.event.ActionListener;
62
import java.sql.SQLException;
63
import java.util.HashSet;
64
import java.util.Set;
65
 
66
import javax.swing.AbstractAction;
67
import javax.swing.Icon;
68
import javax.swing.JCheckBox;
69
import javax.swing.JComponent;
70
import javax.swing.JLabel;
142 ilm 71
import javax.swing.JOptionPane;
94 ilm 72
import javax.swing.JPanel;
73
import javax.swing.JTabbedPane;
74
import javax.swing.JTextField;
142 ilm 75
import javax.swing.SwingUtilities;
94 ilm 76
import javax.swing.event.DocumentEvent;
77
import javax.swing.event.DocumentListener;
78
 
93 ilm 79
public class CustomerSQLComponent extends GroupSQLComponent {
80
    private ContactItemTable table;
144 ilm 81
    private ClientCodeArticleTable tableCustomProduct;
93 ilm 82
    private AdresseClientItemTable adresseTable = new AdresseClientItemTable();
174 ilm 83
 
93 ilm 84
    private SQLTable contactTable = Configuration.getInstance().getDirectory().getElement("CONTACT").getTable();
85
    private final SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
142 ilm 86
    private final JUniqueTextField code = new JUniqueTextField(20) {
87
        @Override
88
        public String getAutoRefreshNumber() {
89
            if (getMode() == Mode.INSERTION) {
90
                return NumerotationAutoSQLElement.getNextNumero(getElement().getClass());
91
            } else {
92
                return null;
93
            }
94
        }
95
    };
93 ilm 96
 
174 ilm 97
    private CustomerProductQtyPriceListTable clienTarifTable = new CustomerProductQtyPriceListTable();
93 ilm 98
    private SQLRowValues defaultContactRowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(this.contactTable));
99
    private JCheckBox checkAdrLivraison, checkAdrFacturation;
100
 
101
    public CustomerSQLComponent(SQLElement element) {
102
        super(element);
103
        this.table = new ContactItemTable(this.defaultContactRowVals);
144 ilm 104
        this.tableCustomProduct = new ClientCodeArticleTable();
93 ilm 105
        this.table.setPreferredSize(new Dimension(this.table.getSize().width, 150));
106
    }
107
 
108
    @Override
109
    protected Set<String> createRequiredNames() {
110
        final Set<String> s = new HashSet<String>();
111
        s.add("NOM");
112
        s.add("ID_ADRESSE");
113
        s.add("ID_MODE_REGLEMENT");
114
        return s;
115
    }
116
 
117
    @Override
118
    protected SQLRowValues createDefaults() {
119
 
120
        SQLRowValues rowVals = new SQLRowValues(getTable());
121
        rowVals.put("CODE", NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
132 ilm 122
        // Mode de règlement par defaut
123
        try {
124
            SQLRow r = ModeReglementDefautPrefPanel.getDefaultRow(true);
125
            SQLElement eltModeReglement = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
126
            if (r.getID() > 1) {
127
                SQLRowValues rowValsMR = eltModeReglement.createCopy(r, null);
128
                rowVals.put("ID_MODE_REGLEMENT", rowValsMR);
129
            }
130
        } catch (SQLException e) {
131
            System.err.println("Impossible de sélectionner le mode de règlement par défaut du client.");
132
            e.printStackTrace();
133
        }
93 ilm 134
        return rowVals;
135
    }
136
 
137
    @Override
138
    public JComponent createEditor(String id) {
139
        if (id.equals("CATEGORIES")) {
140
            TextFieldWithMenuItemsTableFetcher itemsFetcher = new TextFieldWithMenuItemsTableFetcher(getTable().getTable("CATEGORIE_CLIENT").getField("NOM"));
141
            TextFieldWithMenu t = new TextFieldWithMenu(itemsFetcher, false);
142
            t.addAction(new AbstractAction(TM.tr("add")) {
143
 
144
                @Override
145
                public void actionPerformed(ActionEvent e) {
146
                    EditFrame frame = new EditFrame(getElement().getDirectory().getElement("CATEGORIE_CLIENT"), EditMode.CREATION);
147
                    FrameUtil.showPacked(frame);
148
 
149
                }
150
            });
151 ilm 151
            t.addAction(new AbstractAction(TM.tr("modify.or.delete")) {
93 ilm 152
 
153
                @Override
154
                public void actionPerformed(ActionEvent e) {
155
                    final SQLElement element = getElement().getDirectory().getElement("CATEGORIE_CLIENT");
156
 
157
                    ListeAddPanel p = new ListeAddPanel(element);
158
                    // EditFrame frame = new EditFrame(element, EditMode.CREATION);
159
                    IListFrame frame = new IListFrame(p);
160
                    FrameUtil.showPacked(frame);
161
 
162
                }
163
            });
164
            return t;
94 ilm 165
        } else if (id.equals("GROUPE") || id.equals("FORME_JURIDIQUE") || id.equals("CENTRE_GESTION") || id.equals("METHODE_RELANCE")) {
93 ilm 166
            return new SQLSearchableTextCombo(ComboLockedMode.UNLOCKED, 1, 20, false);
167
        } else if (id.equals("SITE_INTERNET")) {
168
            return new TextFieldWithWebBrowsing();
156 ilm 169
        } else if (id.equals("SIRET")) {
170
            return new JTextField(20);
93 ilm 171
        } else if (id.equals("DATE")) {
172
            return new JDate(true);
173
        } else if (id.equals("customerrelationship.customer.contacts")) {
174
            return this.table;
144 ilm 175
        } else if (id.equals("customerrelationship.customer.customproduct")) {
176
            return this.tableCustomProduct;
174 ilm 177
        } else if (id.equals("customerrelationship.customer.customtarif")) {
178
            return this.clienTarifTable;
93 ilm 179
        } else if (id.equals("customerrelationship.customer.addresses")) {
180
            return createAdressesComponent();
181
        } else if (id.equals("NOM")) {
132 ilm 182
            return super.createEditor(id);
93 ilm 183
        }
184
        if (id.equals("CODE")) {
185
 
186
            return this.code;
187
        } else if (id.equals("INFOS")) {
188
            return new ITextArea(4, 40);
189
        } else if (id.equals("COMMENTAIRES")) {
190
            return new ITextArea(10, 40);
191
        } else if (id.equals("TEL")) {
192
            final JTextField textTel = new JTextField(25);
193
            textTel.getDocument().addDocumentListener(new DocumentListener() {
194
 
195
                public void changedUpdate(DocumentEvent e) {
196
                    defaultContactRowVals.put("TEL_DIRECT", textTel.getText());
197
                }
198
 
199
                public void insertUpdate(DocumentEvent e) {
200
                    defaultContactRowVals.put("TEL_DIRECT", textTel.getText());
201
                }
202
 
203
                public void removeUpdate(DocumentEvent e) {
204
                    defaultContactRowVals.put("TEL_DIRECT", textTel.getText());
205
                }
206
 
207
            });
208
            return textTel;
209
        } else if (id.equals("FAX")) {
210
            final JTextField textFax = new JTextField(25);
211
            textFax.getDocument().addDocumentListener(new DocumentListener() {
212
 
213
                public void changedUpdate(DocumentEvent e) {
214
                    defaultContactRowVals.put("FAX", textFax.getText());
215
                }
216
 
217
                public void insertUpdate(DocumentEvent e) {
218
                    defaultContactRowVals.put("FAX", textFax.getText());
219
                }
220
 
221
                public void removeUpdate(DocumentEvent e) {
222
                    defaultContactRowVals.put("FAX", textFax.getText());
223
                }
224
 
225
            });
226
            return textFax;
227
        }
94 ilm 228
        JComponent c = super.createEditor(id);
229
        return c;
93 ilm 230
    }
231
 
232
    @Override
233
    public JComponent getLabel(String id) {
234
        if (id.equals("ID_MODE_REGLEMENT") || id.equals("INFOS") || id.startsWith("ID_ADRESSE")) {
235
            JLabel l = (JLabel) super.getLabel(id);
236
            l.setFont(l.getFont().deriveFont(Font.BOLD));
237
            return l;
238
        }
239
        if (id.equals("customerrelationship.customer.contact")) {
240
            return new JLabelBold("Contacts");
241
        } else if (id.equals("customerrelationship.customer.payment")) {
242
            return new JLabelBold("Mode de règlement");
243
        } else if (id.equals("customerrelationship.customer.address")) {
244
            return new JLabelBold("Adresses du client");
245
        }
94 ilm 246
        JComponent c = super.getLabel(id);
247
        return c;
93 ilm 248
    }
249
 
250
    @Override
251
    public void update() {
252
        super.update();
253
        final int selectedID = getSelectedID();
254
        this.table.updateField("ID_CLIENT", selectedID);
174 ilm 255
        this.clienTarifTable.updateField("ID_CLIENT", selectedID);
144 ilm 256
        this.tableCustomProduct.updateField("ID_CLIENT", selectedID);
93 ilm 257
        this.adresseTable.updateField("ID_CLIENT", selectedID);
258
    }
259
 
260
    @Override
261
    public void select(SQLRowAccessor r) {
262
        super.select(r);
263
        this.checkAdrLivraison.setSelected(r == null || !r.getFields().contains("ID_ADRESSE_L") || r.isForeignEmpty("ID_ADRESSE_L"));
264
        this.checkAdrFacturation.setSelected(r == null || !r.getFields().contains("ID_ADRESSE_F") || r.isForeignEmpty("ID_ADRESSE_F"));
265
        if (r != null) {
266
            this.table.insertFrom("ID_CLIENT", r.asRowValues());
174 ilm 267
            this.clienTarifTable.insertFrom("ID_CLIENT", r.asRowValues());
144 ilm 268
            this.tableCustomProduct.insertFrom("ID_CLIENT", r.asRowValues());
93 ilm 269
            this.adresseTable.insertFrom("ID_CLIENT", r.asRowValues());
270
        }
271
    }
272
 
273
    @Override
274
    public int insert(SQLRow order) {
142 ilm 275
        int id;
93 ilm 276
 
142 ilm 277
        int attempt = 0;
278
        // on verifie qu'un client du meme numero n'a pas été inséré entre temps
156 ilm 279
        if (this.code.getText().trim().length() > 0 && !this.code.checkValidation(false)) {
142 ilm 280
            while (attempt < JUniqueTextField.RETRY_COUNT) {
281
                String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass());
282
                this.code.setText(num);
283
                attempt++;
284
                if (this.code.checkValidation(false)) {
285
                    System.err.println("ATEMPT " + attempt + " SUCCESS WITH NUMERO " + num);
286
                    break;
287
                }
93 ilm 288
                try {
142 ilm 289
                    Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
290
                } catch (InterruptedException e) {
93 ilm 291
                    e.printStackTrace();
292
                }
293
            }
294
        }
142 ilm 295
        final String num = this.code.getText();
296
        if (attempt == JUniqueTextField.RETRY_COUNT) {
297
            id = getSelectedID();
298
            ExceptionHandler.handle("Impossible d'ajouter, numéro de client existant.");
299
            final Object root = SwingUtilities.getRoot(this);
300
            if (root instanceof EditFrame) {
301
                final EditFrame frame = (EditFrame) root;
302
                frame.getPanel().setAlwaysVisible(true);
303
            }
304
        } else {
305
            id = super.insert(order);
306
            this.table.updateField("ID_CLIENT", id);
144 ilm 307
            this.tableCustomProduct.updateField("ID_CLIENT", id);
174 ilm 308
            this.clienTarifTable.updateField("ID_CLIENT", id);
142 ilm 309
            this.adresseTable.updateField("ID_CLIENT", id);
310
            if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass()).equalsIgnoreCase(this.code.getText().trim())) {
311
                SQLRowValues rowVals = new SQLRowValues(this.tableNum);
312
                final SQLRow rowNumAuto = this.tableNum.getRow(2);
313
                if (rowNumAuto.getObject("CLIENT_START") != null) {
314
                    int val = rowNumAuto.getInt("CLIENT_START");
315
                    val++;
316
                    rowVals.put("CLIENT_START", new Integer(val));
93 ilm 317
 
142 ilm 318
                    try {
319
                        rowVals.update(2);
320
                    } catch (SQLException e) {
321
                        e.printStackTrace();
322
                    }
323
                }
324
            }
325
            if (attempt > 0) {
326
                SwingUtilities.invokeLater(new Runnable() {
327
                    public void run() {
328
                        JOptionPane.showMessageDialog(null, "Le numéro a été actualisé en " + num);
329
                    }
330
                });
331
            }
332
        }
177 ilm 333
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
334
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.COMPTE_CLIENT_AUTO, Boolean.FALSE)) {
335
            createCompteClientFromCodeAuto(id);
336
        }
93 ilm 337
        return id;
338
    }
339
 
177 ilm 340
    private void createCompteClientFromCodeAuto(int idClient) {
341
        final SQLRow rowClient = getTable().getRow(idClient);
342
        if (rowClient.isForeignEmpty("ID_COMPTE_PCE")) {
343
 
344
            SQLRowValues rowVals = rowClient.createEmptyUpdateRow();
345
            final String text = rowClient.getString("CODE");
346
 
347
            String compte = "411" + text;
348
 
349
            SQLTable table = getTable().getForeignTable("ID_COMPTE_PCE");
350
            SQLSelect selCompte = new SQLSelect();
351
            selCompte.addSelectFunctionStar("COUNT");
352
            selCompte.setArchivedPolicy(SQLSelect.BOTH);
353
            selCompte.setWhere(new Where(table.getField("NUMERO"), "LIKE", compte + "%"));
354
            System.err.println(selCompte.asString());
355
            Object o = getTable().getDBRoot().getDBSystemRoot().getDataSource().executeScalar(selCompte.asString());
356
 
357
            int nb = 0;
358
            if (o != null) {
359
                Long i = (Long) o;
360
                nb = i.intValue();
361
            }
362
            if (nb > 0) {
363
                compte = compte + nb;
364
            }
365
            int idCpt = ComptePCESQLElement.getId(compte, rowClient.getString("NOM"));
366
            rowVals.put("ID_COMPTE_PCE", idCpt);
367
            try {
368
                rowVals.update();
369
            } catch (SQLException e) {
370
                e.printStackTrace();
371
            }
372
        }
373
    }
374
 
93 ilm 375
    private JComponent createAdressesComponent() {
376
        final JTabbedPane tabbedAdresse = new JTabbedPane() {
377
            public void insertTab(String title, Icon icon, Component component, String tip, int index) {
378
                if (component instanceof JComponent) {
379
                    ((JComponent) component).setOpaque(false);
380
                }
381
                super.insertTab(title, icon, component, tip, index);
382
            }
383
 
384
        };
385
 
386
        // Adr principale
387
 
388
        final JPanel panelAdressePrincipale = new JPanel(new GridBagLayout());
389
        GridBagConstraints cPanel = new DefaultGridBagConstraints();
390
        cPanel.weightx = 1;
391
        cPanel.weighty = 1;
392
        cPanel.anchor = GridBagConstraints.NORTH;
393
        this.addView("ID_ADRESSE", REQ + ";" + DEC + ";" + SEP);
394
 
395
        final ElementSQLObject componentPrincipale = (ElementSQLObject) this.getView("ID_ADRESSE");
396
        ((AdresseSQLComponent) componentPrincipale.getSQLChild()).setDestinataireVisible(true);
397
        componentPrincipale.setOpaque(false);
398
        panelAdressePrincipale.add(componentPrincipale, cPanel);
399
        tabbedAdresse.add(getLabelFor("ID_ADRESSE"), panelAdressePrincipale);
400
        tabbedAdresse.setOpaque(false);
401
 
402
        // Adresse de facturation
403
 
404
        tabbedAdresse.add(getLabelFor("ID_ADRESSE_F"), createFacturationPanel());
405
 
406
        // Adresse de livraison
407
 
408
        tabbedAdresse.add(getLabelFor("ID_ADRESSE_L"), createLivraisonPanel());
409
 
410
        // Adresses supplémentaires
411
        String labelAdrSuppl = TM.tr("additional.address");
412
        tabbedAdresse.add(labelAdrSuppl, this.adresseTable);
413
 
414
        return tabbedAdresse;
415
    }
416
 
417
    private Component createLivraisonPanel() {
418
        final JPanel panel = new JPanel(new GridBagLayout());
419
        final GridBagConstraints c = new DefaultGridBagConstraints();
420
        final String field = "ID_ADRESSE_L";
421
 
422
        this.addView(field, DEC + ";" + SEP);
423
        final ElementSQLObject component = (ElementSQLObject) this.getView(field);
424
        final AdresseSQLComponent adresseSQLComponent = (AdresseSQLComponent) component.getSQLChild();
425
        adresseSQLComponent.setDestinataireVisible(true);
426
        System.err.println("CustomerSQLComponent.createLivraisonPanel()" + component + " " + System.identityHashCode(component));
427
        System.err.println("CustomerSQLComponent.createLivraisonPanel()" + adresseSQLComponent + " " + System.identityHashCode(adresseSQLComponent));
428
        component.setOpaque(false);
429
        c.weightx = 1;
430
        this.checkAdrLivraison = new JCheckBox(TM.tr("delivery.address.same.main.address"));
431
        this.checkAdrLivraison.setOpaque(false);
432
        panel.add(component, c);
433
 
434
        c.gridy++;
435
        c.weighty = 1;
436
        c.anchor = GridBagConstraints.NORTH;
437
        panel.add(this.checkAdrLivraison, c);
438
        // Listener
439
        this.checkAdrLivraison.addActionListener(new ActionListener() {
440
 
441
            public void actionPerformed(java.awt.event.ActionEvent e) {
442
                boolean b = checkAdrLivraison.isSelected();
443
                System.err.println("CustomerSQLComponent.createAdressesComponent().new ActionListener() {...}.actionPerformed() checkAdrLivraison " + b);
444
                component.setEditable((!b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED);
445
                component.setCreated(!b);
446
            };
447
        });
448
        panel.setOpaque(false);
449
        return panel;
450
    }
451
 
452
    private Component createFacturationPanel() {
453
        final JPanel panel = new JPanel(new GridBagLayout());
454
        final GridBagConstraints c = new DefaultGridBagConstraints();
455
        final String field = "ID_ADRESSE_F";
456
 
457
        this.addView(field, DEC + ";" + SEP);
458
        final ElementSQLObject component = (ElementSQLObject) this.getView(field);
459
        final AdresseSQLComponent adresseSQLComponent = (AdresseSQLComponent) component.getSQLChild();
460
        System.err.println("CustomerSQLComponent.createFacturationPanel()" + component + " " + System.identityHashCode(component));
461
        System.err.println("CustomerSQLComponent.createFacturationPanel()" + adresseSQLComponent + " " + System.identityHashCode(adresseSQLComponent));
462
        adresseSQLComponent.setDestinataireVisible(true);
463
        component.setOpaque(false);
464
        c.weightx = 1;
465
        this.checkAdrFacturation = new JCheckBox(TM.tr("invoice.address.same.main.address"));
466
        this.checkAdrFacturation.setOpaque(false);
467
        c.anchor = GridBagConstraints.NORTH;
468
        panel.add(component, c);
469
 
470
        c.gridy++;
471
        c.weighty = 1;
472
        c.anchor = GridBagConstraints.NORTH;
473
        panel.add(this.checkAdrFacturation, c);
474
        // Listener
475
        this.checkAdrFacturation.addActionListener(new ActionListener() {
476
 
477
            public void actionPerformed(java.awt.event.ActionEvent e) {
478
                boolean b = checkAdrFacturation.isSelected();
479
                System.err.println("CustomerSQLComponent.createAdressesComponent().new ActionListener() {...}.actionPerformed() checkAdrFacturation " + b);
480
                component.setEditable((!b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED);
481
                component.setCreated(!b);
482
            };
483
        });
484
        panel.setOpaque(false);
485
        return panel;
486
    }
487
 
488
}