OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
43 ilm 1
package org.openconcerto.modules.badge;
2
 
3
import java.awt.Component;
4
import java.io.File;
5
import java.io.IOException;
153 ilm 6
import java.sql.SQLException;
43 ilm 7
import java.text.DateFormat;
153 ilm 8
import java.text.Normalizer;
9
import java.text.Normalizer.Form;
43 ilm 10
import java.text.SimpleDateFormat;
11
import java.util.ArrayList;
79 ilm 12
import java.util.Arrays;
43 ilm 13
import java.util.Calendar;
14
import java.util.Date;
153 ilm 15
import java.util.HashMap;
43 ilm 16
import java.util.HashSet;
17
import java.util.List;
153 ilm 18
import java.util.Map;
43 ilm 19
import java.util.Set;
153 ilm 20
import java.util.regex.Matcher;
21
import java.util.regex.Pattern;
43 ilm 22
 
23
import javax.swing.Action;
98 ilm 24
import javax.swing.Icon;
43 ilm 25
import javax.swing.JFrame;
26
import javax.swing.JTable;
27
import javax.swing.table.DefaultTableCellRenderer;
28
 
29
import org.openconcerto.erp.action.CreateFrameAbstractAction;
30
import org.openconcerto.erp.config.MainFrame;
153 ilm 31
import org.openconcerto.erp.core.common.element.AdresseSQLElement;
43 ilm 32
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
33
import org.openconcerto.erp.core.common.ui.ListeViewPanel;
153 ilm 34
import org.openconcerto.erp.core.customerrelationship.customer.element.ContactSQLElement;
35
import org.openconcerto.erp.core.customerrelationship.customer.element.CustomerSQLElement;
43 ilm 36
import org.openconcerto.erp.modules.AbstractModule;
37
import org.openconcerto.erp.modules.ComponentsContext;
38
import org.openconcerto.erp.modules.DBContext;
79 ilm 39
import org.openconcerto.erp.modules.MenuContext;
43 ilm 40
import org.openconcerto.erp.modules.ModuleFactory;
79 ilm 41
import org.openconcerto.erp.modules.ModulePreferencePanel;
42
import org.openconcerto.erp.modules.ModulePreferencePanelDesc;
153 ilm 43
import org.openconcerto.erp.modules.ModuleVersion;
43 ilm 44
import org.openconcerto.sql.Configuration;
45
import org.openconcerto.sql.element.SQLComponent;
46
import org.openconcerto.sql.element.SQLElement;
47
import org.openconcerto.sql.element.SQLElementDirectory;
48
import org.openconcerto.sql.element.UISQLComponent;
167 ilm 49
import org.openconcerto.sql.model.DBRoot;
43 ilm 50
import org.openconcerto.sql.model.SQLName;
153 ilm 51
import org.openconcerto.sql.model.SQLRow;
43 ilm 52
import org.openconcerto.sql.model.SQLRowAccessor;
153 ilm 53
import org.openconcerto.sql.model.SQLRowValues;
54
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
43 ilm 55
import org.openconcerto.sql.model.SQLSyntax;
153 ilm 56
import org.openconcerto.sql.model.SQLTable;
43 ilm 57
import org.openconcerto.sql.model.Where;
58
import org.openconcerto.sql.utils.SQLCreateTable;
59
import org.openconcerto.sql.view.FileDropHandler;
60
import org.openconcerto.sql.view.IListFrame;
61
import org.openconcerto.sql.view.IListPanel;
62
import org.openconcerto.sql.view.list.IListe;
63
import org.openconcerto.sql.view.list.RowAction;
64
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
65
import org.openconcerto.ui.PanelFrame;
153 ilm 66
import org.openconcerto.ui.group.Group;
67
import org.openconcerto.ui.group.LayoutHints;
118 ilm 68
import org.openconcerto.utils.ListMap;
79 ilm 69
import org.openconcerto.utils.PrefType;
153 ilm 70
import org.openconcerto.utils.StringUtils;
43 ilm 71
import org.openconcerto.utils.cc.IClosure;
72
 
73
public final class Module extends AbstractModule {
74
 
153 ilm 75
    private static final String CLIENT_ADH_FIELDNAME = "ID_ADHERENT";
76
    private static final Pattern FIRST_NAME_PATTERN = Pattern.compile("([^0-9]*)([0-9]*).*");
77
    public static final boolean HAS_CODE_IN_FIRST_NAME = Boolean.getBoolean("adherent.hasCodeInFirstName");
78
 
43 ilm 79
    public Module(ModuleFactory f) throws IOException {
80
        super(f);
81
 
82
    }
83
 
84
    @Override
153 ilm 85
    protected void install(final DBContext ctxt) throws SQLException, IOException {
43 ilm 86
        super.install(ctxt);
153 ilm 87
        final AdresseSQLElement addrElem = ctxt.getElementDirectory().getElement(AdresseSQLElement.class);
43 ilm 88
 
153 ilm 89
        final ModuleVersion dbVersion = ctxt.getLastInstalledVersion() == null ? ModuleVersion.MIN : ctxt.getLastInstalledVersion();
90
        if (dbVersion.getMerged() > this.getFactory().getVersion().getMerged())
91
            throw new IllegalStateException("Cannot downgrade from " + dbVersion + " to " + this.getFactory());
92
        if (dbVersion.getMerged() < ModuleVersion.getMerged(1, 0)) {
43 ilm 93
            // ENTREE
94
            final SQLCreateTable createTableEntree = ctxt.getCreateTable("ENTREE");
95
            createTableEntree.addDateAndTimeColumn("DATE");
96
            createTableEntree.addVarCharColumn("NUMERO_CARTE", 256);
97
            createTableEntree.addVarCharColumn("ADHERENT", 512);
98
            createTableEntree.addVarCharColumn("MOTIF", 2048);
99
            createTableEntree.addColumn("ACCEPTE", "boolean");
153 ilm 100
 
43 ilm 101
            // PLAGE
102
            final SQLCreateTable createTablePlage = ctxt.getCreateTable("PLAGE_HORAIRE");
103
            createTablePlage.addVarCharColumn("NOM", 256);
104
            createTablePlage.addColumn("DEBUT_1_LUNDI", "time");
105
            createTablePlage.addColumn("DEBUT_1_MARDI", "time");
106
            createTablePlage.addColumn("DEBUT_1_MERCREDI", "time");
107
            createTablePlage.addColumn("DEBUT_1_JEUDI", "time");
108
            createTablePlage.addColumn("DEBUT_1_VENDREDI", "time");
109
            createTablePlage.addColumn("DEBUT_1_SAMEDI", "time");
110
            createTablePlage.addColumn("DEBUT_1_DIMANCHE", "time");
111
 
112
            createTablePlage.addColumn("DEBUT_2_LUNDI", "time");
113
            createTablePlage.addColumn("DEBUT_2_MARDI", "time");
114
            createTablePlage.addColumn("DEBUT_2_MERCREDI", "time");
115
            createTablePlage.addColumn("DEBUT_2_JEUDI", "time");
116
            createTablePlage.addColumn("DEBUT_2_VENDREDI", "time");
117
            createTablePlage.addColumn("DEBUT_2_SAMEDI", "time");
118
            createTablePlage.addColumn("DEBUT_2_DIMANCHE", "time");
119
 
120
            createTablePlage.addColumn("DEBUT_3_LUNDI", "time");
121
            createTablePlage.addColumn("DEBUT_3_MARDI", "time");
122
            createTablePlage.addColumn("DEBUT_3_MERCREDI", "time");
123
            createTablePlage.addColumn("DEBUT_3_JEUDI", "time");
124
            createTablePlage.addColumn("DEBUT_3_VENDREDI", "time");
125
            createTablePlage.addColumn("DEBUT_3_SAMEDI", "time");
126
            createTablePlage.addColumn("DEBUT_3_DIMANCHE", "time");
127
 
128
            createTablePlage.addColumn("FIN_1_LUNDI", "time");
129
            createTablePlage.addColumn("FIN_1_MARDI", "time");
130
            createTablePlage.addColumn("FIN_1_MERCREDI", "time");
131
            createTablePlage.addColumn("FIN_1_JEUDI", "time");
132
            createTablePlage.addColumn("FIN_1_VENDREDI", "time");
133
            createTablePlage.addColumn("FIN_1_SAMEDI", "time");
134
            createTablePlage.addColumn("FIN_1_DIMANCHE", "time");
135
 
136
            createTablePlage.addColumn("FIN_2_LUNDI", "time");
137
            createTablePlage.addColumn("FIN_2_MARDI", "time");
138
            createTablePlage.addColumn("FIN_2_MERCREDI", "time");
139
            createTablePlage.addColumn("FIN_2_JEUDI", "time");
140
            createTablePlage.addColumn("FIN_2_VENDREDI", "time");
141
            createTablePlage.addColumn("FIN_2_SAMEDI", "time");
142
            createTablePlage.addColumn("FIN_2_DIMANCHE", "time");
143
 
144
            createTablePlage.addColumn("FIN_3_LUNDI", "time");
145
            createTablePlage.addColumn("FIN_3_MARDI", "time");
146
            createTablePlage.addColumn("FIN_3_MERCREDI", "time");
147
            createTablePlage.addColumn("FIN_3_JEUDI", "time");
148
            createTablePlage.addColumn("FIN_3_VENDREDI", "time");
149
            createTablePlage.addColumn("FIN_3_SAMEDI", "time");
150
            createTablePlage.addColumn("FIN_3_DIMANCHE", "time");
151
 
152
            // ADHERENT
153
            final SQLCreateTable createTable = ctxt.getCreateTable("ADHERENT");
154
 
155
            createTable.addVarCharColumn("NUMERO_CARTE", 256);
156
            createTable.addVarCharColumn("NOM", 256);
157
 
158
            createTable.addVarCharColumn("TEL", 256);
159
            createTable.addColumn("ACTIF", "boolean default false");
160
            createTable.addColumn("ADMIN", "boolean default false");
161
            createTable.addVarCharColumn("MAIL", 256);
162
            createTable.addVarCharColumn("PRENOM", 256);
163
            createTable.addVarCharColumn("INFOS", 2048);
164
            createTable.addColumn("DATE_VALIDITE_INSCRIPTION", "date");
165
            createTable.addColumn("DATE_NAISSANCE", "date");
166
 
153 ilm 167
            createTable.addForeignColumn("ID_ADRESSE", addrElem.getTable());
43 ilm 168
            createTable.addForeignColumn("ID_PLAGE_HORAIRE", new SQLName("PLAGE_HORAIRE"), SQLSyntax.ID_NAME, null);
169
        }
153 ilm 170
        // at least v1.0
171
 
172
        if (dbVersion.getMerged() < ModuleVersion.getMerged(1, 1)) {
173
            // migrate from non-private
174
            final SQLTable adhT = ctxt.getRoot().getTable("ADHERENT");
175
            final CustomerSQLElement clientElem = ctxt.getElementDirectory().getElement(CustomerSQLElement.class);
176
            final SQLTable clientT = clientElem.getTable();
177
            ctxt.getAlterTable(clientT.getName()).addForeignColumn(CLIENT_ADH_FIELDNAME, adhT);
178
            // fill new field (no need to do anything in uninstall() since the field will be
179
            // dropped and new clients shouldn't be dropped)
180
            if (adhT.getRowCount(false) > 0) {
181
                ctxt.executeSQL();
182
                this.setupElements(ctxt.getElementDirectory());
183
                // 1. fetch all clients
184
                final ListMap<String, SQLRow> clientByName = new ListMap<>();
185
                final ListMap<String, SQLRow> clientByCode = new ListMap<>();
186
                for (final SQLRowValues clientR : SQLRowValuesListFetcher.create(new SQLRowValues(clientT).putNulls("NOM", "CODE")).fetch()) {
187
                    final String normalized = normalize(clientR.getString("NOM"));
188
                    clientByName.add(normalized, clientR.asRow());
189
                    clientByCode.add(clientR.getString("CODE"), clientR.asRow());
190
                }
191
                // 2. for each ADHERENT, link it to a single matching CLIENT, or create a
192
                // new one. Also fill CLIENT fields with duplicates from ADHERENT.
193
                // créer plutôt plus de clients : si besoin, fusion après coup.
194
                final SQLRowValues adhToFetch = new SQLRowValues(adhT).putNulls("NOM", "PRENOM", "MAIL", "TEL", "DATE_NAISSANCE");
195
                adhToFetch.putRowValues("ID_ADRESSE").setAllToNull();
196
                final Map<SQLRow, SQLRow> updatedClientsAndAdh = new HashMap<>();
197
 
198
                for (final SQLRowValues adhR : SQLRowValuesListFetcher.create(adhToFetch).fetch(null, true)) {
199
                    final String firstName;
200
                    final String code;
201
                    SQLRow existingClient = null;
202
                    if (HAS_CODE_IN_FIRST_NAME) {
203
                        final Matcher matcher = FIRST_NAME_PATTERN.matcher(adhR.getString("PRENOM"));
204
                        if (!matcher.matches())
205
                            throw new IllegalStateException("Couldn't match " + adhR);
206
                        firstName = matcher.group(1).trim();
207
                        code = matcher.group(2);
208
                    } else {
209
                        firstName = adhR.getString("PRENOM");
210
                        code = null;
211
                    }
212
                    if (!StringUtils.isEmpty(code)) {
213
                        existingClient = getUnique(clientByCode.get(code));
214
                    }
215
                    final String firstLastName = firstName + " " + adhR.getString("NOM");
216
                    if (existingClient == null) {
217
                        existingClient = getUnique(clientByName.get(normalize(firstLastName)));
218
                    }
219
                    final SQLRow newClient;
220
                    if (existingClient != null && !updatedClientsAndAdh.containsKey(existingClient)) {
221
                        updatedClientsAndAdh.put(existingClient, adhR.asRow());
222
                        // TODO use SQLElement.createFetcher()
223
                        final SQLRowValues clientToUpdateVals = SQLRowValuesListFetcher.create(clientElem.createGraph()).fetchOne(existingClient.getIDNumber(), true);
224
                        // TODO use new UpdateAction(SQLElement.createContext())
225
                        final SQLRowValues newVals = fillFields(clientToUpdateVals.deepCopy(), adhR, false, addrElem);
226
                        newClient = clientElem.update(clientToUpdateVals, newVals).exec();
227
                    } else {
228
                        // TODO use Logger
229
                        if (existingClient != null) {
230
                            System.err.println("While matching " + adhT + ", existing client " + existingClient + " already updated with " + updatedClientsAndAdh.get(existingClient)
231
                                    + " so creating new client for " + adhR);
232
                        } else {
233
                            System.err.println("While matching " + adhT + ", no client found for " + adhR);
234
                        }
235
                        // create new client row
236
                        // TODO use new InsertAction(SQLElement.createContext()) or at least
237
                        // SQLElement.insert()
238
                        final SQLRowValues vals = fillFields(new SQLRowValues(clientT).put("NOM", firstLastName), adhR, true, addrElem);
239
                        if (!StringUtils.isEmpty(code))
240
                            vals.put("CODE", code);
241
                        newClient = vals.insert();
242
                    }
243
                    final SQLRowValues contactVals = new SQLRowValues(ctxt.getElementDirectory().getElement(ContactSQLElement.class).getTable());
244
                    contactVals.putForeignID("ID_CLIENT", newClient);
245
                    contactVals.load(adhR.asRow(), Arrays.asList("NOM", "DATE_NAISSANCE"));
246
                    contactVals.put("PRENOM", firstName);
247
                    contactVals.put("EMAIL", adhR.getString("MAIL"));
248
                    contactVals.insert();
249
                }
250
 
251
                ctxt.getAlterTable(adhT.getName()).dropColumn("ID_ADRESSE");
252
            }
253
        }
43 ilm 254
    }
255
 
153 ilm 256
    protected SQLRow getUnique(final List<SQLRow> clientRows) {
257
        return clientRows != null && clientRows.size() == 1 ? clientRows.get(0) : null;
258
    }
259
 
260
    private final SQLRowValues fillFields(final SQLRowValues clientVals, final SQLRowValues adhVals, final boolean useAdhID, final SQLElement addrElem) {
261
        clientVals.put(CLIENT_ADH_FIELDNAME, useAdhID ? adhVals.getIDNumber() : adhVals.deepCopy());
262
        concatField(clientVals, adhVals, "MAIL");
263
        concatField(clientVals, adhVals, "TEL");
264
        final SQLRowValues adhAddr = (SQLRowValues) adhVals.getNonEmptyForeign("ID_ADRESSE");
265
        if (adhAddr != null && !StringUtils.isEmpty(adhAddr.getString("VILLE"), true)) {
266
            clientVals.put("ID_ADRESSE", addrElem.createCopy(adhAddr, true, null));
267
        }
268
        return clientVals;
269
    }
270
 
271
    private final void concatField(final SQLRowValues clientVals, final SQLRowValues adhVals, final String fieldName) {
272
        final String adhStr = adhVals.getString(fieldName);
273
        if (StringUtils.isEmpty(adhStr, true))
274
            return;
275
        final String clientStr = clientVals.getString(fieldName);
276
        if (StringUtils.isEmpty(clientStr, true)) {
277
            clientVals.put(fieldName, adhStr);
278
        } else {
279
            clientVals.put(fieldName, clientStr + ", " + adhStr);
280
        }
281
    }
282
 
283
    static private final Pattern diacriticalPattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
284
    static private final Pattern punctPattern = Pattern.compile("\\p{Punct}+");
285
    static private final Pattern spacePattern = Pattern.compile("\\p{Space}+");
286
 
287
    // remove punctation, multiple spaces and accents
288
    static private String normalize(final String s) {
289
        final String noMarks = diacriticalPattern.matcher(Normalizer.normalize(s, Form.NFD)).replaceAll("");
290
        final String noPunct = punctPattern.matcher(noMarks).replaceAll("_");
291
        return spacePattern.matcher(noPunct.trim()).replaceAll(" ").toLowerCase();
292
    }
293
 
43 ilm 294
    @Override
295
    protected void setupElements(SQLElementDirectory dir) {
296
        super.setupElements(dir);
297
 
298
        final ComptaSQLConfElement entreeElement = new ComptaSQLConfElement("ENTREE", "une entrée", "entrées") {
299
 
300
            @Override
301
            protected List<String> getListFields() {
302
                final List<String> l = new ArrayList<String>();
303
                l.add("DATE");
304
                l.add("NUMERO_CARTE");
305
                l.add("ADHERENT");
306
                l.add("MOTIF");
307
                l.add("ACCEPTE");
308
                return l;
309
            }
310
 
311
            @Override
312
            public Set<String> getReadOnlyFields() {
313
                Set<String> s = new HashSet<String>(super.getReadOnlyFields());
314
                s.add("NUMERO_CARTE");
315
                return s;
316
            }
317
 
318
            @Override
319
            protected List<String> getComboFields() {
320
                final List<String> l = new ArrayList<String>();
321
                l.add("NUMERO_CARTE");
322
                l.add("DATE");
323
                return l;
324
            }
325
 
326
            @Override
118 ilm 327
            public ListMap<String, String> getShowAs() {
328
                return ListMap.singleton(null, getComboFields());
43 ilm 329
            }
330
 
331
            @Override
332
            public SQLComponent createComponent() {
333
                return new UISQLComponent(this) {
334
                    @Override
335
                    protected void addViews() {
336
                        this.addView("NUMERO_CARTE");
337
                        this.addView("DATE");
338
                    }
339
                };
340
            }
341
        };
342
        dir.addSQLElement(entreeElement);
343
        dir.addSQLElement(new PlageHoraireSQLElement());
344
        dir.addSQLElement(new AdherentSQLElement());
345
    }
346
 
347
    private IListPanel getPanelEntree(boolean filtered) {
348
        final SQLElement element = Configuration.getInstance().getDirectory().getElement("ENTREE");
349
 
350
        final SQLTableModelSourceOnline tableModelEntree = element.getTableSource(true);
351
 
352
        if (filtered) {
353
            Calendar cal = Calendar.getInstance();
354
            cal.add(Calendar.DAY_OF_MONTH, -15);
355
            Where wAttente = new Where(element.getTable().getField("DATE"), ">=", cal.getTime());
356
            tableModelEntree.getReq().setWhere(wAttente);
357
        }
358
        tableModelEntree.getColumn(element.getTable().getField("DATE")).setRenderer(new DefaultTableCellRenderer() {
359
 
360
            DateFormat format = new SimpleDateFormat("EEEE dd MMMM yyyy HH:mm:ss");
361
 
362
            @Override
363
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
364
                final String format2 = format.format((Date) value);
365
                return super.getTableCellRendererComponent(table, format2, isSelected, hasFocus, row, column);
366
 
367
            }
368
        });
369
 
370
        final IListPanel panel = new ListeViewPanel(element, new IListe(tableModelEntree));
371
 
98 ilm 372
        final Action createAction = RowAction.createAction("Assigner à", (Icon) null, new IClosure<List<? extends SQLRowAccessor>>() {
43 ilm 373
            @Override
98 ilm 374
            public void executeChecked(List<? extends SQLRowAccessor> input) {
43 ilm 375
                SQLRowAccessor row = input.get(0);
376
                PanelFrame frame = new PanelFrame(new AssignationPanel(row.getString("NUMERO_CARTE")), "Assignation d'une carte");
377
                frame.setLocationRelativeTo(null);
378
                frame.setVisible(true);
379
 
380
            }
381
        });
382
 
383
        panel.getListe().addRowAction(createAction);
384
 
385
        return panel;
386
    }
387
 
388
    @Override
389
    protected void setupComponents(ComponentsContext ctxt) {
153 ilm 390
        final Group g = new Group("customerrelationship.customer.adherent", LayoutHints.DEFAULT_SEPARATED_GROUP_HINTS);
391
        ctxt.getElement("CLIENT").getDefaultGroup().add(g);
392
        g.addItem(CLIENT_ADH_FIELDNAME, new LayoutHints(true, true, true, true, true, true));
43 ilm 393
        ctxt.addFileDropHandler("ADHERENT", new FileDropHandler() {
394
 
395
            @Override
396
            public boolean handle(File f, Component source) {
397
                AdherentImporter importer;
398
                try {
399
                    importer = new AdherentImporter(f);
400
                    importer.importAdherent();
401
                } catch (Exception e) {
402
                    e.printStackTrace();
403
                }
404
                return true;
405
            }
406
 
407
            @Override
408
            public boolean canHandle(File f) {
409
                String n = f.getName().toLowerCase();
410
                return n.endsWith(".xls") || n.endsWith(".ods");
411
            }
412
        });
79 ilm 413
    }
414
 
415
    @Override
416
    protected void setupMenu(MenuContext ctxt) {
43 ilm 417
        ctxt.addMenuItem(new CreateFrameAbstractAction("Liste des entrées") {
418
 
419
            @Override
420
            public JFrame createFrame() {
421
 
422
                return new IListFrame(getPanelEntree(false));
423
            }
424
        }, MainFrame.LIST_MENU);
167 ilm 425
        ctxt.addMenuItem(ctxt.getMenuAndActions().getAction("preferences"), MainFrame.FILE_MENU);
43 ilm 426
    }
427
 
428
    @Override
429
    protected void start() {
430
        MainFrame.getInstance().getTabbedPane().addTab("Liste des entrées", getPanelEntree(true));
431
    }
432
 
433
    @Override
434
    protected void stop() {
435
    }
436
 
79 ilm 437
    public final static String ENTREE_PREF = "entreeAdmin";
438
 
439
    @Override
167 ilm 440
    public List<ModulePreferencePanelDesc> getPrefDescriptors(final DBRoot root) {
79 ilm 441
        return Arrays.<ModulePreferencePanelDesc> asList(new ModulePreferencePanelDesc("Gestion des entrées") {
442
            @Override
443
            protected ModulePreferencePanel createPanel() {
167 ilm 444
                return new ModulePreferencePanel(root, "Gestion des entrées") {
79 ilm 445
                    @Override
446
                    protected void addViews() {
447
                        this.addView(new SQLPrefView<Boolean>(PrefType.BOOLEAN_TYPE, "N'autoriser que les administrateurs à entrer ", ENTREE_PREF));
448
                    }
449
                };
450
            }
451
        }.setLocal(false).setKeywords("entrée"));
452
    }
453
 
43 ilm 454
}