OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
75 ilm 1
package org.openconcerto.modules.project;
2
 
3
import java.awt.Color;
4
import java.awt.event.ActionEvent;
5
import java.io.IOException;
6
import java.sql.SQLException;
97 ilm 7
import java.util.ArrayList;
75 ilm 8
import java.util.Arrays;
9
import java.util.Collection;
10
import java.util.Date;
11
import java.util.List;
12
import java.util.Map;
13
import java.util.Set;
14
 
15
import javax.swing.AbstractAction;
16
import javax.swing.JComponent;
17
import javax.swing.JFrame;
97 ilm 18
import javax.swing.JOptionPane;
75 ilm 19
import javax.swing.JScrollPane;
97 ilm 20
import javax.swing.SwingUtilities;
75 ilm 21
 
22
import org.openconcerto.erp.action.CreateFrameAbstractAction;
97 ilm 23
import org.openconcerto.erp.config.ComptaPropsConfiguration;
75 ilm 24
import org.openconcerto.erp.config.MainFrame;
25
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
26
import org.openconcerto.erp.core.sales.invoice.ui.SaisieVenteFactureItemTable;
27
import org.openconcerto.erp.core.sales.order.ui.CommandeClientItemTable;
28
import org.openconcerto.erp.core.sales.quote.component.DevisSQLComponent;
29
import org.openconcerto.erp.core.sales.quote.element.DevisSQLElement;
30
import org.openconcerto.erp.core.sales.quote.element.EtatDevisSQLElement;
31
import org.openconcerto.erp.core.sales.quote.report.DevisXmlSheet;
32
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
33
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProvider;
34
import org.openconcerto.erp.generationEcritures.provider.AccountingRecordsProviderManager;
35
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
36
import org.openconcerto.erp.modules.AbstractModule;
37
import org.openconcerto.erp.modules.AlterTableRestricted;
38
import org.openconcerto.erp.modules.ComponentsContext;
39
import org.openconcerto.erp.modules.DBContext;
40
import org.openconcerto.erp.modules.MenuContext;
41
import org.openconcerto.erp.modules.ModuleFactory;
42
import org.openconcerto.modules.project.element.ProjectSQLElement;
43
import org.openconcerto.modules.project.element.ProjectStateSQLElement;
44
import org.openconcerto.modules.project.element.ProjectTypeSQLElement;
45
import org.openconcerto.sql.Configuration;
46
import org.openconcerto.sql.element.SQLComponent;
47
import org.openconcerto.sql.element.SQLElement;
48
import org.openconcerto.sql.element.SQLElementDirectory;
49
import org.openconcerto.sql.model.DBRoot;
50
import org.openconcerto.sql.model.FieldPath;
51
import org.openconcerto.sql.model.SQLRow;
52
import org.openconcerto.sql.model.SQLRowAccessor;
53
import org.openconcerto.sql.model.SQLRowValues;
54
import org.openconcerto.sql.model.SQLSelect;
55
import org.openconcerto.sql.model.SQLTable;
97 ilm 56
import org.openconcerto.sql.model.SQLTableEvent;
57
import org.openconcerto.sql.model.SQLTableEvent.Mode;
58
import org.openconcerto.sql.model.SQLTableModifiedListener;
75 ilm 59
import org.openconcerto.sql.model.Where;
128 ilm 60
import org.openconcerto.sql.model.graph.Link.Direction;
75 ilm 61
import org.openconcerto.sql.model.graph.Path;
146 ilm 62
import org.openconcerto.sql.utils.AlterTable;
75 ilm 63
import org.openconcerto.sql.utils.SQLCreateTable;
64
import org.openconcerto.sql.view.EditFrame;
65
import org.openconcerto.sql.view.IListFrame;
66
import org.openconcerto.sql.view.ListeAddPanel;
67
import org.openconcerto.sql.view.column.ColumnFooterRenderer;
68
import org.openconcerto.sql.view.column.ColumnPanel;
69
import org.openconcerto.sql.view.column.ColumnPanelFetcher;
70
import org.openconcerto.sql.view.column.ColumnRowRenderer;
71
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
72
import org.openconcerto.sql.view.list.IListe;
73
import org.openconcerto.sql.view.list.RowAction;
74
import org.openconcerto.utils.CollectionUtils;
97 ilm 75
import org.openconcerto.utils.ExceptionHandler;
75 ilm 76
import org.openconcerto.utils.Tuple2;
77
import org.openconcerto.utils.cc.IClosure;
78
import org.openconcerto.utils.cc.ITransformer;
79
import org.openconcerto.utils.i18n.TranslationManager;
80
 
81
public final class Module extends AbstractModule {
82
 
83
    public static final String PROJECT_TABLENAME = "AFFAIRE";
146 ilm 84
    private List<String> listTableAffaire = Arrays.asList("DEMANDE_PRIX", "DEMANDE_ACHAT_ELEMENT", "SAISIE_VENTE_FACTURE", "AVOIR_CLIENT", "BON_DE_LIVRAISON", "COMMANDE_CLIENT", "DEVIS", "COMMANDE",
85
            "SAISIE_ACHAT", "AVOIR_FOURNISSEUR");
75 ilm 86
 
87
    public Module(ModuleFactory f) throws IOException {
88
        super(f);
89
 
90
    }
91
 
92
    @Override
93
    protected void install(DBContext ctxt) {
94
        super.install(ctxt);
95
 
96
        if (ctxt.getLastInstalledVersion() == null) {
97
 
98
            if (ctxt.getRoot().getTable(PROJECT_TABLENAME) == null) {
99
                final SQLCreateTable createTableEtatAff = ctxt.getCreateTable("ETAT_AFFAIRE");
100
                createTableEtatAff.addVarCharColumn("NOM", 128);
101
 
102
                final SQLCreateTable createTableType = ctxt.getCreateTable("TYPE_AFFAIRE");
103
                createTableType.addVarCharColumn("NOM", 256);
104
 
105
                // AFFAIRE
106
                final SQLCreateTable createTable = ctxt.getCreateTable(PROJECT_TABLENAME);
107
                createTable.addVarCharColumn("NUMERO", 256);
108
                createTable.addVarCharColumn("NOM", 1024);
109
                createTable.addVarCharColumn("INFOS", 1024);
110
                createTable.addForeignColumn("ID_CLIENT", ctxt.getRoot().getTable("CLIENT"));
111
                createTable.addForeignColumn("ID_DEVIS", ctxt.getRoot().getTable("DEVIS"));
112
                createTable.addColumn("DATE", "date");
113
                createTable.addForeignColumn("ID_COMMERCIAL", ctxt.getRoot().getTable("COMMERCIAL"));
114
                createTable.addForeignColumn("ID_ETAT_AFFAIRE", createTableEtatAff);
115
                createTable.addForeignColumn("ID_TYPE_AFFAIRE", createTableType);
116
 
117
                for (String table : this.listTableAffaire) {
118
                    SQLTable tableDevis = ctxt.getRoot().getTable(table);
119
                    if (!tableDevis.getFieldsName().contains("ID_AFFAIRE")) {
120
                        AlterTableRestricted alter = ctxt.getAlterTable(table);
121
                        alter.addForeignColumn("ID_AFFAIRE", createTable);
122
                    }
123
                }
124
                ctxt.manipulateData(new IClosure<DBRoot>() {
125
                    @Override
126
                    public void executeChecked(DBRoot input) {
127
                        // Undefined Affaire
128
                        SQLTable tableAff = input.getTable(PROJECT_TABLENAME);
129
                        SQLRowValues rowVals = new SQLRowValues(tableAff);
130
                        try {
131
                            rowVals.insert();
132
                        } catch (SQLException exn) {
133
                            // TODO Bloc catch auto-généré
134
                            exn.printStackTrace();
135
                        }
136
 
137
                        // Etat Affaire
138
                        SQLTable tableTypeAffaire = input.getTable("TYPE_AFFAIRE");
139
                        rowVals = new SQLRowValues(tableTypeAffaire);
140
                        try {
141
                            rowVals.put("NOM", "Indéfini");
142
                            rowVals.insert();
143
                        } catch (SQLException exn) {
144
                            // TODO Bloc catch auto-généré
145
                            exn.printStackTrace();
146
                        }
147
 
148
                        // Etat Affaire
149
                        SQLTable tableEtatAffaire = input.getTable("ETAT_AFFAIRE");
150
                        rowVals = new SQLRowValues(tableEtatAffaire);
151
                        try {
152
                            rowVals.put("NOM", "Indéfini");
153
                            rowVals.insert();
154
 
155
                            rowVals.clear();
156
                            rowVals.put("NOM", "A traiter");
157
                            rowVals.insert();
158
 
159
                            rowVals.clear();
160
                            rowVals.put("NOM", "En cours");
161
                            rowVals.insert();
162
 
163
                            rowVals.clear();
164
                            rowVals.put("NOM", "Traitement terminé");
165
                            rowVals.insert();
166
 
167
                            rowVals.clear();
168
                            rowVals.put("NOM", "A facturer");
169
                            rowVals.insert();
170
 
171
                            rowVals.clear();
172
                            rowVals.put("NOM", "Dossier clos");
173
                            rowVals.insert();
174
                        } catch (SQLException exn) {
175
                            exn.printStackTrace();
176
                        }
177
 
178
                    }
179
                });
180
            }
181
        }
182
 
183
    }
184
 
185
    @Override
186
    protected void setupElements(final SQLElementDirectory dir) {
187
        super.setupElements(dir);
188
        TranslationManager.getInstance().addTranslationStreamFromClass(this.getClass());
189
        dir.addSQLElement(ProjectSQLElement.class);
190
        dir.addSQLElement(ProjectStateSQLElement.class);
191
        dir.addSQLElement(ProjectTypeSQLElement.class);
192
 
193
        final SQLElement element = dir.getElement("DEVIS");
194
        DevisSQLElement eltDevis = dir.getElement(DevisSQLElement.class);
195
        eltDevis.getRowActions().clear();
196
 
197
        eltDevis.addListColumn(new BaseSQLTableModelColumn("Temps Total", Double.class) {
198
 
199
            SQLTable tableDevisElt = Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT").getTable();
200
 
201
            @Override
202
            protected Object show_(SQLRowAccessor r) {
203
 
204
                Collection<? extends SQLRowAccessor> rows = r.getReferentRows(tableDevisElt);
205
                double time = 0;
206
                for (SQLRowAccessor sqlRowAccessor : rows) {
207
                    time += OrderColumnRowRenderer.getHours(sqlRowAccessor);
208
                }
209
                return time;
210
            }
211
 
212
            @Override
213
            public Set<FieldPath> getPaths() {
214
                SQLTable table = Configuration.getInstance().getDirectory().getElement("DEVIS").getTable();
88 ilm 215
                Path p = new Path(table).add(tableDevisElt.getField("ID_DEVIS"));
75 ilm 216
 
88 ilm 217
                Path p2 = new Path(table).add(tableDevisElt.getField("ID_DEVIS")).addForeignField("ID_UNITE_VENTE");
75 ilm 218
                return CollectionUtils.createSet(new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"), new FieldPath(p2, "CODE"));
219
            }
220
        });
221
 
222
        // Transfert vers facture
223
        RowAction factureAction = eltDevis.getDevis2FactureAction();
224
        eltDevis.getRowActions().add(factureAction);
225
 
226
        // Transfert vers commande
227
        RowAction commandeAction = eltDevis.getDevis2CmdCliAction();
228
        eltDevis.getRowActions().add(commandeAction);
229
 
230
        // Marqué accepté
231
        RowAction accepteAction = getAcceptAction();
232
        eltDevis.getRowActions().add(accepteAction);
233
 
234
        // Marqué accepté
235
        RowAction refuseAction = eltDevis.getRefuseAction();
236
        eltDevis.getRowActions().add(refuseAction);
237
 
238
        // // Dupliquer
239
        RowAction cloneAction = eltDevis.getCloneAction();
240
        eltDevis.getRowActions().add(cloneAction);
241
 
242
        MouseSheetXmlListeListener mouseSheetXmlListeListener = new MouseSheetXmlListeListener(DevisXmlSheet.class);
243
        mouseSheetXmlListeListener.setGenerateHeader(true);
244
        mouseSheetXmlListeListener.setShowHeader(true);
245
        eltDevis.getRowActions().addAll(mouseSheetXmlListeListener.getRowActions());
246
 
247
        element.addComponentFactory(SQLElement.DEFAULT_COMP_ID, new ITransformer<Tuple2<SQLElement, String>, SQLComponent>() {
248
 
249
            @Override
250
            public SQLComponent transformChecked(Tuple2<SQLElement, String> input) {
251
                return new DevisSQLComponent(element) {
252
 
253
                    public int insert(SQLRow order) {
254
                        int id = super.insert(order);
255
                        checkAffaire(id);
256
                        return id;
257
                    }
258
 
259
                    public void update() {
260
                        super.update();
261
                        checkAffaire(getSelectedID());
262
                    }
263
 
264
                };
265
            }
266
        });
267
 
268
        final SQLElement elementCmd = dir.getElement("COMMANDE_CLIENT");
269
        elementCmd.addListColumn(new BaseSQLTableModelColumn("Temps Total", Double.class) {
270
 
271
            SQLTable tableCmdElt = dir.getElement("COMMANDE_CLIENT_ELEMENT").getTable();
272
 
273
            @Override
274
            protected Object show_(SQLRowAccessor r) {
275
 
276
                Collection<? extends SQLRowAccessor> rows = r.getReferentRows(tableCmdElt);
277
                double time = 0;
278
                for (SQLRowAccessor sqlRowAccessor : rows) {
279
                    time += OrderColumnRowRenderer.getHours(sqlRowAccessor);
280
                }
281
                return time;
282
            }
283
 
284
            @Override
285
            public Set<FieldPath> getPaths() {
286
                final SQLTable table = elementCmd.getTable();
88 ilm 287
                final Path p = new Path(table).add(tableCmdElt.getField("ID_COMMANDE_CLIENT"));
288
                final Path p2 = new Path(table).add(tableCmdElt.getField("ID_COMMANDE_CLIENT")).addForeignField("ID_UNITE_VENTE");
75 ilm 289
                return CollectionUtils.createSet(new FieldPath(p, "QTE"), new FieldPath(p, "QTE_UNITAIRE"), new FieldPath(p2, "CODE"));
290
            }
291
        });
292
 
293
        NumerotationAutoSQLElement.addClass(ProjectSQLElement.class, PROJECT_TABLENAME);
294
 
128 ilm 295
        for (String tableName : this.listTableAffaire) {
296
            if (!tableName.equalsIgnoreCase("DEVIS")) {
297
                final SQLElement elt = dir.getElement(tableName);
146 ilm 298
                if (elt == null) {
299
                    JOptionPane.showMessageDialog(null, "Table " + tableName + " manquante");
300
                    continue;
301
                }
128 ilm 302
                RowAction action = new RowAction(new AbstractAction("Historique affaire") {
303
                    @Override
304
                    public void actionPerformed(ActionEvent e) {
305
                        ProjectHistory histo = new ProjectHistory();
306
                        histo.getHistoriquePanel().selectIDinJList(IListe.get(e).getSelectedRow().getForeignID("ID_AFFAIRE"));
307
                        histo.getFrame().setVisible(true);
308
                    }
309
                }, false) {
310
                    @Override
311
                    public boolean enabledFor(IListeEvent evt) {
312
                        if (evt.getSelectedRows().size() == 1) {
313
                            SQLRowAccessor r = evt.getSelectedRow();
314
                            return !r.isForeignEmpty("ID_AFFAIRE");
315
                        }
316
                        return false;
317
                    }
318
                };
319
 
320
                elt.getRowActions().add(action);
321
                elt.addListColumn(new BaseSQLTableModelColumn("Affaire", String.class) {
322
 
323
                    @Override
324
                    protected Object show_(SQLRowAccessor r) {
325
                        if (!r.isForeignEmpty("ID_AFFAIRE") && r.getForeign("ID_AFFAIRE") != null) {
326
                            return r.getForeign("ID_AFFAIRE").getString("NUMERO");
327
                        } else {
328
                            return "";
329
                        }
330
                    }
331
 
332
                    @Override
333
                    public Set<FieldPath> getPaths() {
334
                        SQLTable table = elt.getTable();
335
                        Path p = new Path(table).add(table.getField("ID_AFFAIRE"));
336
                        return CollectionUtils.createSet(new FieldPath(p, "NUMERO"));
337
                    }
338
                });
339
            }
340
        }
341
 
342
        final SQLElement elt = dir.getElement("DEVIS");
343
        RowAction action = new RowAction(new AbstractAction("Historique affaire") {
344
            @Override
345
            public void actionPerformed(ActionEvent e) {
346
                ProjectHistory histo = new ProjectHistory();
347
                SQLRowAccessor selectedRow = IListe.get(e).getSelectedRow();
348
                Collection<? extends SQLRowAccessor> l = selectedRow.getReferentRows(selectedRow.getTable().getTable("AFFAIRE"));
349
                histo.getHistoriquePanel().selectIDinJList(l.iterator().next().getID());
350
                histo.getFrame().setVisible(true);
351
            }
352
        }, false) {
353
            @Override
354
            public boolean enabledFor(IListeEvent evt) {
355
                if (evt.getSelectedRows().size() == 1) {
356
                    SQLRowAccessor r = evt.getSelectedRow();
357
                    Collection<? extends SQLRowAccessor> l = r.getReferentRows(r.getTable().getTable("AFFAIRE"));
358
                    return l.size() > 0;
359
                }
360
                return false;
361
            }
362
        };
363
 
364
        elt.getRowActions().add(action);
365
 
366
        elt.addListColumn(new BaseSQLTableModelColumn("Affaire", String.class) {
367
 
368
            @Override
369
            protected Object show_(SQLRowAccessor r) {
370
                Collection<? extends SQLRowAccessor> rows = r.getReferentRows(elt.getTable().getTable("AFFAIRE"));
371
                if (rows.size() == 1) {
372
                    return rows.iterator().next().getString("NUMERO");
373
                } else {
374
                    return "";
375
                }
376
            }
377
 
378
            @Override
379
            public Set<FieldPath> getPaths() {
380
                SQLTable table = elt.getTable();
381
                Path p = new Path(table).add(table.getTable("AFFAIRE"), Direction.REFERENT);
382
                return CollectionUtils.createSet(new FieldPath(p, "NUMERO"));
383
            }
384
        });
385
 
75 ilm 386
        new QuoteToOrderSQLInjector();
387
        new QuoteToInvoiceSQLInjector();
388
        new OrderToInvoiceSQLInjector();
389
    }
390
 
391
    public void checkAffaire(int id) {
392
        final SQLTable tableDevis = Configuration.getInstance().getRoot().findTable("DEVIS");
393
        final SQLTable tableNum = Configuration.getInstance().getRoot().findTable("NUMEROTATION_AUTO");
394
        final SQLRow row = tableDevis.getRow(id);
395
        final SQLRow rowAffaire = row.getForeign("ID_AFFAIRE");
396
        if (rowAffaire == null || rowAffaire.isUndefined()) {
397
            if (row.getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.ACCEPTE) {
398
                // FIXME Vérifier si le devis n'est pas déjà rattaché à une affaire
399
                final SQLTable table = tableDevis.getTable(PROJECT_TABLENAME);
400
                final SQLRowValues rowVals = new SQLRowValues(table);
401
 
402
                final String nextNumero = NumerotationAutoSQLElement.getNextNumero(ProjectSQLElement.class);
403
                rowVals.put("NUMERO", nextNumero);
404
 
405
                // incrémentation du numéro auto
406
                final SQLRowValues rowValsNum = new SQLRowValues(tableNum);
407
                int val = tableNum.getRow(2).getInt(NumerotationAutoSQLElement.getLabelNumberFor(ProjectSQLElement.class));
408
                val++;
409
                rowValsNum.put(NumerotationAutoSQLElement.getLabelNumberFor(ProjectSQLElement.class), new Integer(val));
410
                try {
411
                    rowValsNum.update(2);
412
                } catch (final SQLException e) {
413
                    e.printStackTrace();
414
                }
415
 
416
                rowVals.put("ID_DEVIS", row.getID());
417
                rowVals.put("ID_CLIENT", row.getObject("ID_CLIENT"));
418
                rowVals.put("ID_COMMERCIAL", row.getObject("ID_COMMERCIAL"));
419
                rowVals.put("DATE", new Date());
420
                rowVals.put("ID_ETAT_AFFAIRE", ProjectStateSQLElement.EN_COURS);
421
 
422
                SQLRowValues rowValsDevis = row.asRowValues();
423
                rowValsDevis.put("ID_AFFAIRE", rowVals);
424
 
425
                try {
426
                    rowVals.commit();
427
                } catch (SQLException exn) {
428
                    // TODO Bloc catch auto-généré
429
                    exn.printStackTrace();
430
                }
431
            }
146 ilm 432
 
433
        } else if (row.getInt("ID_ETAT_DEVIS") != EtatDevisSQLElement.ACCEPTE) {
75 ilm 434
            SQLRowValues rowVals = rowAffaire.asRowValues();
435
            rowVals.putEmptyLink("ID_DEVIS");
436
            try {
437
                rowVals.update();
438
            } catch (SQLException exn) {
439
                exn.printStackTrace();
440
            }
441
        }
442
    }
443
 
97 ilm 444
    List<Integer> idsAsked = new ArrayList<Integer>();
445
 
446
    public void checkProjectState(final SQLRowAccessor rowFact) {
447
        if (!rowFact.isForeignEmpty("ID_AFFAIRE")) {
448
            final SQLRowAccessor rowAff = rowFact.getForeign("ID_AFFAIRE");
449
 
450
            if (rowAff.getInt("ID_ETAT_AFFAIRE") < ProjectStateSQLElement.DOSSIER_CLOS) {
451
 
452
                SQLSelect sel = new SQLSelect();
453
                final SQLTable tableVF = rowFact.getTable();
454
                sel.addSelect(tableVF.getField("T_TTC"), "SUM");
455
                Where w = new Where(tableVF.getField("ID_AFFAIRE"), "=", rowAff.getID());
456
                sel.setWhere(w);
457
 
458
                Number total = (Number) tableVF.getDBSystemRoot().getDataSource().executeScalar(sel.asString());
459
 
460
                long devis = rowAff.getForeign("ID_DEVIS").getLong("T_TTC");
461
                if (devis == total.longValue()) {
462
                    if (!idsAsked.contains(rowFact.getID())) {
463
                        idsAsked.add(rowFact.getID());
464
                        SwingUtilities.invokeLater(new Runnable() {
465
 
466
                            @Override
467
                            public void run() {
468
                                int a = JOptionPane.showConfirmDialog(null, "Voulez vous passer l'affaire " + rowAff.getString("NUMERO") + " dans l'état \"Dossier Clos\"?", "Affaire 100% facturée",
469
                                        JOptionPane.YES_NO_OPTION);
470
                                if (a == JOptionPane.YES_OPTION) {
471
                                    SQLRowValues rowVals = rowAff.createEmptyUpdateRow();
472
                                    rowVals.put("ID_ETAT_AFFAIRE", ProjectStateSQLElement.DOSSIER_CLOS);
473
                                    try {
474
                                        rowVals.commit();
475
                                    } catch (SQLException e) {
476
                                        ExceptionHandler.handle("Erreur lors de la mise à jour de l'état de l'affaire", e);
477
                                    }
478
                                }
479
                                idsAsked.remove(Integer.valueOf(rowFact.getID()));
480
                            }
481
                        });
482
                    }
483
                }
484
 
485
            }
486
        }
487
    }
488
 
75 ilm 489
    public RowAction getAcceptAction() {
490
        return new RowAction(new AbstractAction() {
491
            public void actionPerformed(ActionEvent e) {
88 ilm 492
                SQLRow selectedRow = IListe.get(e).getSelectedRow().asRow();
75 ilm 493
                SQLRowValues rowVals = selectedRow.createEmptyUpdateRow();
494
                rowVals.put("ID_ETAT_DEVIS", EtatDevisSQLElement.ACCEPTE);
495
                try {
496
                    rowVals.update();
497
                } catch (SQLException e1) {
498
                    e1.printStackTrace();
499
                }
500
                selectedRow.getTable().fireTableModified(selectedRow.getID());
501
                checkAffaire(selectedRow.getID());
502
            }
503
        }, false, "project.accept") {
97 ilm 504
            public boolean enabledFor(List<SQLRowValues> selection) {
75 ilm 505
                if (selection != null && selection.size() == 1) {
506
                    if (selection.get(0).getInt("ID_ETAT_DEVIS") == EtatDevisSQLElement.EN_ATTENTE) {
507
                        return true;
508
                    }
509
                }
510
                return false;
511
            };
512
        };
513
    }
514
 
515
    @Override
516
    protected void setupComponents(final ComponentsContext ctxt) {
146 ilm 517
        DBRoot root = ComptaPropsConfiguration.getInstanceCompta().getRootSociete();
518
        List<String> table2check = Arrays.asList("DEMANDE_PRIX", "DEMANDE_ACHAT_ELEMENT");
519
        for (String table : table2check) {
520
            if (root.contains(table)) {
521
                SQLTable tableCR = root.getTable(table);
522
                if (!tableCR.contains("ID_AFFAIRE")) {
523
                    try {
524
                        AlterTable alt = new AlterTable(tableCR);
525
                        alt.addForeignColumn("ID_AFFAIRE", root.getTable("AFFAIRE"));
526
                        root.getDBSystemRoot().getDataSource().execute(alt.asString());
527
                        String s = "INSERT INTO " + root.getTable("FWK_MODULE_METADATA").getSQLName().quote()
528
                                + "(\"MODULE_NAME\",\"TABLE\",\"FIELD\",\"KEY\",\"MODULE_VERSION\") VALUES('org.openconcerto.modules.project','" + table + "','ID_AFFAIRE',true,10000)";
529
                        root.getDBSystemRoot().getDataSource().execute(s);
530
                        root.getSchema().updateVersion();
531
                        root.refetchTable(tableCR.getName());
532
                    } catch (SQLException e) {
533
                        e.printStackTrace();
534
                    }
535
                }
536
            }
537
        }
75 ilm 538
        for (String table : this.listTableAffaire) {
539
            if (!table.equalsIgnoreCase("DEVIS"))
540
                ctxt.putAdditionalField(table, "ID_AFFAIRE");
541
        }
146 ilm 542
 
75 ilm 543
    }
544
 
545
    @Override
546
    protected void setupMenu(final MenuContext ctxt) {
547
        ctxt.addMenuItem(new CreateFrameAbstractAction("Liste des affaires") {
548
            @Override
549
            public JFrame createFrame() {
550
                IListFrame frame = new IListFrame(new ListeAddPanel(ctxt.getElement(PROJECT_TABLENAME)));
551
                return frame;
552
            }
553
        }, MainFrame.LIST_MENU);
554
        ctxt.addMenuItem(new CreateFrameAbstractAction("Historique des affaires") {
555
            @Override
556
            public JFrame createFrame() {
557
                ProjectHistory histo = new ProjectHistory();
558
 
559
                return histo.getFrame();
560
            }
561
        }, MainFrame.LIST_MENU);
562
 
563
        ctxt.addMenuItem(new CreateFrameAbstractAction("Saisie affaire") {
564
            @Override
565
            public JFrame createFrame() {
566
                return new EditFrame(ctxt.getElement(PROJECT_TABLENAME));
567
            }
568
        }, MainFrame.CREATE_MENU);
569
 
146 ilm 570
        // ctxt.addMenuItem(new AbstractAction("Export Affaire") {
571
        // @Override
572
        // public void actionPerformed(ActionEvent e) {
573
        // ProjectImportExport importExport = new
574
        // ProjectImportExport(ctxt.getElement("AFFAIRE").getTable().getDBRoot());
575
        // importExport.export();
576
        // }
577
        // }, MainFrame.HELP_MENU);
578
        //
579
        // ctxt.addMenuItem(new AbstractAction("Import Affaire") {
580
        // @Override
581
        // public void actionPerformed(ActionEvent e) {
582
        // ProjectImportExport importExport = new
583
        // ProjectImportExport(ctxt.getElement("AFFAIRE").getTable().getDBRoot());
584
        // importExport.importProjects();
585
        // }
586
        // }, MainFrame.HELP_MENU);
587
        //
588
        // ctxt.addMenuItem(new AbstractAction("Fix ID_AFFAIRE") {
589
        // @Override
590
        // public void actionPerformed(ActionEvent e) {
591
        // {
592
        // SQLTable tableCmd = ctxt.getElement("COMMANDE_CLIENT").getTable();
593
        // SQLSelect selBadCmd = new SQLSelect();
594
        // selBadCmd.addSelect(tableCmd.getKey());
595
        // selBadCmd.addSelect(tableCmd.getField("ID_AFFAIRE"));
596
        // SQLSelectJoin joinTR = selBadCmd.addBackwardJoin("RIGHT", "tr",
597
        // tableCmd.getTable().getTable("TR_DEVIS").getField("ID_COMMANDE_CLIENT"), null);
598
        // SQLSelectJoin joinDevis = selBadCmd.addJoin("LEFT",
599
        // joinTR.getJoinedTable().getField("ID_DEVIS"));
600
        // SQLSelectJoin joinAff = selBadCmd.addBackwardJoin("LEFT", "aff",
601
        // tableCmd.getTable().getTable("AFFAIRE").getField("ID_DEVIS"), null);
602
        // selBadCmd.addSelect(joinAff.getJoinedTable().getKey());
603
        //
604
        // selBadCmd.setWhere(Where.isNull(tableCmd.getField("ID_AFFAIRE")));
605
        // System.err.println(selBadCmd.asString());
606
        //
607
        // List<Object[]> result = (List<Object[]>)
608
        // tableCmd.getDBSystemRoot().getDataSource().executeA(selBadCmd.asString());
609
        // try {
610
        // for (Object[] objects : result) {
611
        // if (objects[2] != null && objects[2].toString().trim().length() > 0)
612
        // tableCmd.getRow(((Number)
613
        // objects[0]).intValue()).createEmptyUpdateRow().put("ID_AFFAIRE", ((Number)
614
        // objects[2]).intValue()).commit();
615
        // }
616
        // } catch (SQLException e1) {
617
        // // TODO Auto-generated catch block
618
        // e1.printStackTrace();
619
        // }
620
        //
621
        // // List<SQLRow> list = SQLRowListRSH.execute(selBadVF);
622
        // }
623
        // {
624
        // SQLTable tableVF = ctxt.getElement("SAISIE_VENTE_FACTURE").getTable();
625
        // SQLSelect selBadVF = new SQLSelect();
626
        // selBadVF.addSelect(tableVF.getKey());
627
        // selBadVF.addSelect(tableVF.getField("ID_AFFAIRE"));
628
        // SQLSelectJoin joinTR = selBadVF.addBackwardJoin("RIGHT", "tr",
629
        // tableVF.getTable().getTable("TR_COMMANDE_CLIENT").getField("ID_SAISIE_VENTE_FACTURE"),
630
        // null);
631
        // SQLSelectJoin joinCmd = selBadVF.addJoin("LEFT",
632
        // joinTR.getJoinedTable().getField("ID_COMMANDE_CLIENT"));
633
        // selBadVF.addSelect(joinCmd.getJoinedTable().getField("ID_AFFAIRE"));
634
        //
635
        // selBadVF.setWhere(Where.isNull(tableVF.getField("ID_AFFAIRE")));
636
        // System.err.println(selBadVF.asString());
637
        // List<Object[]> result = (List<Object[]>)
638
        // tableVF.getDBSystemRoot().getDataSource().executeA(selBadVF.asString());
639
        // try {
640
        // for (Object[] objects : result) {
641
        // if (objects[2] != null && objects[2].toString().trim().length() > 0)
642
        // tableVF.getRow(((Number) objects[0]).intValue()).createEmptyUpdateRow().put("ID_AFFAIRE",
643
        // ((Number) objects[2]).intValue()).commit();
644
        // }
645
        // } catch (SQLException e1) {
646
        // // TODO Auto-generated catch block
647
        // e1.printStackTrace();
648
        // }
649
        // }
650
        // }
651
        // }, MainFrame.CREATE_MENU);
652
        //
653
        // ctxt.addMenuItem(new AbstractAction("Recalcul Total achat facture prorata") {
654
        // @Override
655
        // public void actionPerformed(ActionEvent e) {
656
        //
657
        // {
658
        // final SQLTable table = ctxt.getElement("SAISIE_VENTE_FACTURE").getTable();
659
        // SQLRowValues rowValsFact = new SQLRowValues(table);
660
        // rowValsFact.putNulls("SOLDE", "PARTIAL", "T_HA", "T_HT");
661
        //
662
        // final SQLTable tableCmd = ctxt.getElement("COMMANDE_CLIENT").getTable();
663
        // SQLRowValues rowValsCmd = new SQLRowValues(tableCmd);
664
        // rowValsCmd.putNulls("T_HT");
665
        //
666
        // final SQLTable tableCmdElt = ctxt.getElement("COMMANDE_CLIENT_ELEMENT").getTable();
667
        // SQLRowValues rowValsCmdElt = new SQLRowValues(tableCmdElt);
668
        // rowValsCmdElt.put("ID_COMMANDE_CLIENT", rowValsCmd);
669
        // rowValsCmdElt.putNulls("T_PA_HT", "NIVEAU");
670
        //
671
        // final SQLTable tableTR = table.getTable("TR_COMMANDE_CLIENT");
672
        // SQLRowValues rowValsTR = new SQLRowValues(tableTR);
673
        // rowValsTR.put("ID_SAISIE_VENTE_FACTURE", rowValsFact);
674
        // rowValsTR.put("ID_COMMANDE_CLIENT", rowValsCmd);
675
        //
676
        // SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowValsFact);
677
        // fetcher.appendSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
678
        // @Override
679
        // public SQLSelect transformChecked(SQLSelect input) {
680
        // Where w = new Where(table.getField("SOLDE"), "=", Boolean.TRUE);
681
        // w = w.or(new Where(table.getField("PARTIAL"), "=", Boolean.TRUE));
682
        // input.setWhere(w);
683
        // return input;
684
        // }
685
        // });
686
        //
687
        // List<SQLRowValues> rowVals = fetcher.fetch();
688
        //
689
        // for (SQLRowValues sqlRowValues : rowVals) {
690
        // // Recuperation de la commande
691
        // final Collection<SQLRowValues> referentRows = sqlRowValues.getReferentRows(tableTR);
692
        // if (!referentRows.isEmpty()) {
693
        // SQLRowAccessor rowTR = referentRows.iterator().next();
694
        // SQLRowAccessor rowCmd = rowTR.getForeign("ID_COMMANDE_CLIENT");
695
        // final long htCmd = rowCmd.getLong("T_HT");
696
        // if (htCmd != 0) {
697
        //
698
        // BigDecimal totalHA = BigDecimal.ZERO;
699
        // Collection<? extends SQLRowAccessor> elt = rowCmd.getReferentRows(tableCmdElt);
700
        // for (SQLRowAccessor sqlRowAccessor : elt) {
701
        // if (sqlRowAccessor.getInt("NIVEAU") == 1) {
702
        // totalHA = totalHA.add(sqlRowAccessor.getBigDecimal("T_PA_HT"));
703
        // }
704
        // }
705
        // BigDecimal prorata = new BigDecimal((double) sqlRowValues.getLong("T_HT") / (double)
706
        // htCmd);
707
        // try {
708
        // sqlRowValues.createEmptyUpdateRow().put("T_HA",
709
        // totalHA.multiply(prorata).movePointRight(2).setScale(0,
710
        // RoundingMode.HALF_UP).longValue()).update();
711
        // } catch (SQLException e1) {
712
        // e1.printStackTrace();
713
        // }
714
        // }
715
        // }
716
        // }
717
        // }
718
        // }
719
        // }, MainFrame.CREATE_MENU);
720
 
75 ilm 721
    }
722
 
723
    @Override
724
    protected void start() {
146 ilm 725
 
726
 
727
 
75 ilm 728
        final JComponent quoteComponent = createQuotePanel();
729
        final JComponent orderComponent = createOrderPanel();
730
        MainFrame.getInstance().getTabbedPane().addTab("Commandes en cours", orderComponent);
731
        MainFrame.getInstance().getTabbedPane().addTab("Devis en attente", quoteComponent);
732
        MainFrame.getInstance().getTabbedPane().addTab("Affaires", new ListeAddPanel(Configuration.getInstance().getDirectory().getElement(PROJECT_TABLENAME)));
733
        // Fix for classic XP Theme
734
        quoteComponent.setOpaque(true);
735
        quoteComponent.setBackground(Color.WHITE);
736
        orderComponent.setOpaque(true);
737
        orderComponent.setBackground(Color.WHITE);
738
        // Select first tab
739
        MainFrame.getInstance().getTabbedPane().setSelectedIndex(1);
740
 
741
        CommandeClientItemTable.getVisibilityMap().put("POURCENT_ACOMPTE", Boolean.TRUE);
742
        SaisieVenteFactureItemTable.getVisibilityMap().put("POURCENT_ACOMPTE", Boolean.TRUE);
743
        AccountingRecordsProvider p = new AccountingRecordsProvider() {
744
 
745
            @Override
746
            public void putLabel(SQLRowAccessor rowSource, Map<String, Object> values) {
747
                values.put("NOM", "Fact. vente " + rowSource.getString("NUMERO"));
748
            }
749
 
750
            @Override
751
            public void putPieceLabel(SQLRowAccessor rowSource, SQLRowValues rowValsPiece) {
752
                rowValsPiece.put("NOM", rowSource.getString("NUMERO"));
753
            }
754
        };
755
        AccountingRecordsProviderManager.put(GenerationMvtSaisieVenteFacture.ID, p);
97 ilm 756
 
757
        final SQLTable tableFact = ComptaPropsConfiguration.getInstanceCompta().getRootSociete().getTable("SAISIE_VENTE_FACTURE");
758
 
759
        tableFact.addTableModifiedListener(new SQLTableModifiedListener() {
760
 
761
            @Override
762
            public void tableModified(SQLTableEvent evt) {
763
                if (evt.getMode() == Mode.ROW_ADDED || evt.getMode() == Mode.ROW_UPDATED) {
764
                    checkProjectState(evt.getRow());
765
                }
766
            }
767
        });
75 ilm 768
    }
769
 
770
    private JComponent createQuotePanel() {
771
        ColumnRowRenderer cRenderer = new QuoteColumnRowRenderer();
772
        ColumnFooterRenderer fRenderer = new QuoteColumnFooterRenderer();
773
        final ColumnPanel columnPanel = new ColumnPanel(220, cRenderer, fRenderer);
774
        columnPanel.setOpaque(false);
775
        final SQLElement element = Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT");
88 ilm 776
        Path p = Path.get(element.getTable()).addForeignField("ID_ARTICLE").addForeignField("ID_FAMILLE_ARTICLE");
75 ilm 777
 
778
        SQLRowValues values = new SQLRowValues(element.getTable());
779
        values.put("NOM", null);
780
        values.put("T_PV_HT", null);
781
        SQLRowValues rowValsClient = new SQLRowValues(element.getTable().getTable("CLIENT"));
782
        rowValsClient.put("NOM", null);
783
        final SQLTable tableDevis = element.getTable().getTable("DEVIS");
784
        SQLRowValues rowValsDevis = new SQLRowValues(tableDevis);
785
        rowValsDevis.put("NUMERO", null);
786
        rowValsDevis.put("DATE", null);
787
        rowValsDevis.put("T_HT", null);
788
 
789
        rowValsDevis.put("ID_CLIENT", rowValsClient);
790
        values.put("ID_DEVIS", rowValsDevis);
791
        SQLRowValues rowValsUnite = new SQLRowValues(element.getTable().getTable("UNITE_VENTE"));
792
        rowValsUnite.put("CODE", null);
793
        values.put("ID_UNITE_VENTE", rowValsUnite);
794
        values.put("QTE", null);
795
        values.put("QTE_UNITAIRE", null);
796
 
797
        ITransformer<SQLSelect, SQLSelect> t = new ITransformer<SQLSelect, SQLSelect>() {
798
            @Override
799
            public SQLSelect transformChecked(SQLSelect input) {
800
                input.andWhere(new Where(input.getAlias(tableDevis.getField("ID_ETAT_DEVIS")), "=", EtatDevisSQLElement.EN_ATTENTE));
801
                return input;
802
            }
803
        };
804
        final ColumnPanelFetcher projectFetcher = new ColumnPanelFetcher(values, new FieldPath(p, "NOM"), t);
805
        columnPanel.setHeaderRenderer(new TotalHeaderRenderer());
806
        columnPanel.setFetch(projectFetcher);
807
 
808
        final JScrollPane comp = new JScrollPane(columnPanel);
809
        comp.setBorder(null);
810
        comp.getViewport().setOpaque(false);
811
        return comp;
812
    }
813
 
814
    private JComponent createOrderPanel() {
815
        ColumnRowRenderer cRenderer = new OrderColumnRowRenderer();
816
        ColumnFooterRenderer fRenderer = new OrderColumnFooterRenderer();
817
        final ColumnPanel columnPanel = new ColumnPanel(220, cRenderer, fRenderer);
818
        columnPanel.setOpaque(false);
819
        final SQLElement element = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
820
        final SQLTable tableOrder = element.getTable();
88 ilm 821
        Path p = Path.get(tableOrder).addForeignField("ID_ARTICLE").addForeignField("ID_FAMILLE_ARTICLE");
75 ilm 822
 
823
        SQLRowValues values = new SQLRowValues(tableOrder);
824
        values.put("NOM", null);
825
        values.put("T_PV_HT", null);
826
        SQLRowValues rowValsClient = new SQLRowValues(tableOrder.getTable("CLIENT"));
827
        rowValsClient.put("NOM", null);
828
        SQLRowValues rowValsCmd = new SQLRowValues(tableOrder.getTable("COMMANDE_CLIENT"));
829
        rowValsCmd.put("NUMERO", null);
830
        rowValsCmd.put("DATE", null);
831
        rowValsCmd.put("T_HT", null);
832
 
833
        rowValsCmd.put("ID_CLIENT", rowValsClient);
834
        values.put("ID_COMMANDE_CLIENT", rowValsCmd);
835
        SQLRowValues rowValsUnite = new SQLRowValues(tableOrder.getTable("UNITE_VENTE"));
836
        rowValsUnite.put("CODE", null);
837
        values.put("ID_UNITE_VENTE", rowValsUnite);
838
        values.put("QTE", null);
839
        values.put("QTE_UNITAIRE", null);
840
 
841
        final SQLTable tableAffaire = tableOrder.getTable(PROJECT_TABLENAME);
842
        SQLRowValues rowValsAffaire = new SQLRowValues(tableAffaire);
843
        rowValsAffaire.put("NUMERO", null);
844
        rowValsAffaire.put("DATE", null);
845
        rowValsCmd.put("ID_AFFAIRE", rowValsAffaire);
846
 
847
        if (tableOrder.getDBRoot().contains("AFFAIRE_TEMPS")) {
848
            final SQLTable tableAffaireTemps = tableOrder.getTable("AFFAIRE_TEMPS");
849
            SQLRowValues rowValsAffaireTemps = new SQLRowValues(tableAffaireTemps);
850
            rowValsAffaireTemps.put("TEMPS", null);
851
            rowValsAffaireTemps.put("ID_COMMANDE_CLIENT_ELEMENT", values);
852
        }
853
        ITransformer<SQLSelect, SQLSelect> t = new ITransformer<SQLSelect, SQLSelect>() {
854
            @Override
855
            public SQLSelect transformChecked(SQLSelect input) {
856
                input.andWhere(new Where(input.getAlias(tableAffaire.getField("ID_ETAT_AFFAIRE")), "=", ProjectStateSQLElement.EN_COURS));
857
                return input;
858
            }
859
        };
860
        final ColumnPanelFetcher projectFetcher = new ColumnPanelFetcher(values, new FieldPath(p, "NOM"), t);
861
        columnPanel.setHeaderRenderer(new TotalHeaderRenderer());
862
        columnPanel.setFetch(projectFetcher);
863
        final JScrollPane comp = new JScrollPane(columnPanel);
864
        comp.setBorder(null);
865
        comp.getViewport().setOpaque(false);
866
        return comp;
867
    }
868
 
869
    @Override
870
    protected void stop() {
871
    }
872
}