OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
112 ilm 1
package org.openconcerto.modules.operation;
2
 
141 ilm 3
import java.sql.SQLException;
112 ilm 4
import java.util.ArrayList;
5
import java.util.Calendar;
6
import java.util.Collection;
7
import java.util.Collections;
8
import java.util.Date;
141 ilm 9
import java.util.HashMap;
112 ilm 10
import java.util.List;
141 ilm 11
import java.util.Map;
150 ilm 12
import java.util.Objects;
112 ilm 13
 
14
import javax.swing.SwingUtilities;
15
 
16
import org.jopencalendar.model.Flag;
17
import org.jopencalendar.model.JCalendarItem;
141 ilm 18
import org.jopencalendar.model.JCalendarItemGroup;
112 ilm 19
import org.jopencalendar.ui.JCalendarItemProvider;
20
import org.openconcerto.erp.config.ComptaPropsConfiguration;
150 ilm 21
import org.openconcerto.erp.core.project.element.CalendarItemGroupSQLElement;
22
import org.openconcerto.erp.core.project.element.CalendarItemSQLElement;
23
import org.openconcerto.sql.element.SQLElementDirectory;
112 ilm 24
import org.openconcerto.sql.model.DBRoot;
141 ilm 25
import org.openconcerto.sql.model.SQLRow;
26
import org.openconcerto.sql.model.SQLRowMode;
112 ilm 27
import org.openconcerto.sql.model.SQLRowValues;
28
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
29
import org.openconcerto.sql.model.SQLSelect;
141 ilm 30
import org.openconcerto.sql.model.SQLTable;
112 ilm 31
import org.openconcerto.sql.model.Where;
32
import org.openconcerto.sql.model.graph.Path;
33
import org.openconcerto.sql.model.graph.PathBuilder;
34
import org.openconcerto.sql.users.User;
35
import org.openconcerto.sql.users.UserManager;
141 ilm 36
import org.openconcerto.ui.date.DateRange;
112 ilm 37
import org.openconcerto.utils.CollectionUtils;
38
import org.openconcerto.utils.StringUtils;
39
import org.openconcerto.utils.cc.ITransformer;
40
 
41
public class OperationCalendarManager extends JCalendarItemProvider {
150 ilm 42
    private final DBRoot root;
43
    private final SQLElementDirectory dir;
44
    private final UserManager userMngr;
45
    private List<User> users;
46
    private List<String> states;
47
    private boolean hideLocked = false;
48
    private boolean hideUnlocked = false;
141 ilm 49
 
112 ilm 50
    public OperationCalendarManager(String name) {
150 ilm 51
        this(name, ComptaPropsConfiguration.getInstanceCompta());
112 ilm 52
    }
53
 
150 ilm 54
    public OperationCalendarManager(final String name, final ComptaPropsConfiguration comptaConf) {
55
        this(name, comptaConf.getRootSociete(), comptaConf.getDirectory(), comptaConf.getUserManager());
56
    }
57
 
58
    public OperationCalendarManager(final String name, final DBRoot root, final SQLElementDirectory dir, final UserManager userMngr) {
141 ilm 59
        super(name);
60
        this.root = root;
150 ilm 61
        this.dir = dir;
62
        this.userMngr = userMngr;
141 ilm 63
    }
64
 
181 ilm 65
    public UserManager getUserMngr() {
66
        return userMngr;
67
    }
68
 
150 ilm 69
    public final SQLElementDirectory getDirectory() {
70
        return this.dir;
71
    }
112 ilm 72
 
150 ilm 73
    private final SQLTable getCalendarItemTable() {
74
        return this.dir.getElement(CalendarItemSQLElement.class).getTable();
75
    }
76
 
77
    private final SQLTable getCalendarItemGroupTable() {
78
        return this.dir.getElement(CalendarItemGroupSQLElement.class).getTable();
79
    }
80
 
81
    /*
112 ilm 82
     * Set the filter to retrieve items
83
     *
84
     * @param users if null don't limit to specific users
150 ilm 85
     *
86
     * @param states if null don't limit to specific states
112 ilm 87
     */
150 ilm 88
    synchronized public boolean setFilter(List<User> users, List<String> states, boolean hideLocked, boolean hideUnlocked) {
89
        boolean res = false;
90
        if (!Objects.equals(this.users, users)) {
91
            this.users = users;
92
            res = true;
93
        }
94
        if (!Objects.equals(this.states, states)) {
95
            this.states = states;
96
            res = true;
97
        }
98
        if (this.hideLocked != hideLocked) {
99
            this.hideLocked = hideLocked;
100
            res = true;
101
        }
102
        if (this.hideUnlocked != hideUnlocked) {
103
            this.hideUnlocked = hideUnlocked;
104
            res = true;
105
        }
106
        return res;
112 ilm 107
    }
108
 
109
    @Override
110
    synchronized public List<JCalendarItem> getItemInWeek(int week, int year) {
111
        assert !SwingUtilities.isEventDispatchThread();
112
        return getItemInWeek(week, year, this.users, this.states);
113
    }
114
 
141 ilm 115
    @Override
116
    public List<JCalendarItem> getItemInYear(int year, int week1, int week2) {
117
        final Calendar c = Calendar.getInstance();
118
        c.clear();
119
        c.set(Calendar.YEAR, year);
120
        c.set(Calendar.WEEK_OF_YEAR, week1);
121
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
122
        final Date date1 = c.getTime();
123
        c.set(Calendar.WEEK_OF_YEAR, week2);
124
        final Date date2 = c.getTime();
125
        return getItemIn(date1, date2, this.users, this.states);
126
    }
127
 
112 ilm 128
    private List<JCalendarItem> getItemInWeek(final int week, final int year, final List<User> selectedUsers, final List<String> selectedStates) {
129
        final Calendar c = Calendar.getInstance();
130
        c.clear();
131
        c.set(Calendar.YEAR, year);
132
        c.set(Calendar.WEEK_OF_YEAR, week);
133
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
134
        final Date date1 = c.getTime();
135
        c.add(Calendar.WEEK_OF_YEAR, 1);
136
        final Date date2 = c.getTime();
137
        return getItemIn(date1, date2, selectedUsers, selectedStates);
138
    }
139
 
140
    public List<JCalendarItem> getItemIn(final Date date1, final Date date2, List<User> selectedUsers, final List<String> selectedStates) {
141 ilm 141
        return getItemIn(date1, date2, selectedUsers, selectedStates, null);
142
    }
143
 
144
    public List<JCalendarItem> getItemIn(final Date date1, final Date date2, List<User> selectedUsers, final List<String> selectedStates, final String uid) {
112 ilm 145
        final List<User> users = new ArrayList<User>();
146
        if (selectedUsers == null) {
150 ilm 147
            users.addAll(this.userMngr.getAllActiveUsers());
112 ilm 148
        } else {
149
            users.addAll(selectedUsers);
150
        }
151
        if (users.isEmpty()) {
152
            return Collections.emptyList();
153
        }
154
        if (selectedStates != null && selectedStates.isEmpty()) {
155
            return Collections.emptyList();
156
        }
150 ilm 157
        final SQLRowValues valCalendarItems = new SQLRowValues(getCalendarItemTable());
141 ilm 158
        valCalendarItems.putNulls("START", "END", "DURATION_S", "SUMMARY", "DESCRIPTION", "FLAGS", "STATUS", "SOURCE_ID", "SOURCE_TABLE", "UID", "LOCATION");
112 ilm 159
        final SQLRowValues valsCalendarItemsGroup = valCalendarItems.putRowValues("ID_CALENDAR_ITEM_GROUP");
160
        valsCalendarItemsGroup.put("NAME", null);
161
 
162
        final SQLRowValues valSite = new SQLRowValues(root.getTable(ModuleOperation.TABLE_SITE));
163
        valSite.putNulls("NAME", "COMMENT");
164
 
165
        final SQLRowValues valOperation = new SQLRowValues(root.getTable(ModuleOperation.TABLE_OPERATION));
150 ilm 166
        final SQLRowValues userVals = valOperation.putRowValues("ID_USER_COMMON").putNulls("NOM", "PRENOM");
112 ilm 167
        valOperation.put("ID_CALENDAR_ITEM_GROUP", valsCalendarItemsGroup);
168
        valOperation.put("ID_SITE", valSite);
169
        valOperation.putNulls("STATUS", "TYPE", "PLANNER_XML", "PLANNER_UID");
170
 
171
        final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(valCalendarItems);
150 ilm 172
        fetcher.setReturnedRowsUnmodifiable(true);
112 ilm 173
        fetcher.setFullOnly(true);
174
        fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
175
 
176
            @Override
177
            public SQLSelect transformChecked(SQLSelect input) {
141 ilm 178
                if (date1 != null && date2 != null) {
179
                    input.andWhere(new Where(valCalendarItems.getTable().getField("START"), date1, true, date2, false));
180
                }
181
                if (uid != null) {
182
                    Where ww = new Where(valCalendarItems.getTable().getField("UID"), "=", uid);
183
                    try {
184
                        int i = Integer.parseInt(uid);
185
                        ww = ww.or(new Where(valCalendarItems.getTable().getKey(), "=", i));
186
                    } catch (Exception e) {
187
 
188
                    }
189
 
190
                    input.andWhere(ww);
191
                }
112 ilm 192
                return input;
193
            }
194
        });
195
 
196
        final Path item2Operation = new PathBuilder(valCalendarItems.getTable()).addForeignField("ID_CALENDAR_ITEM_GROUP").addReferentTable(ModuleOperation.TABLE_OPERATION).build();
197
        try {
198
            CollectionUtils.getSole(fetcher.getFetchers(item2Operation).allValues()).setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
199
                @Override
200
                public SQLSelect transformChecked(SQLSelect input) {
201
                    if (selectedStates != null) {
202
                        // Le status utilisé est celui de OPERATION
203
                        input.andWhere(new Where(input.getAlias(valOperation.getTable()).getField("STATUS"), selectedStates));
204
                    }
205
                    return input;
206
                }
207
            });
208
        } catch (Exception e) {
209
            e.printStackTrace();
210
        }
211
        final Path p = item2Operation.addForeignField("ID_USER_COMMON");
212
        final Path pItemToOperation = p.minusLast();
213
        final Collection<SQLRowValuesListFetcher> fetchers = fetcher.getFetchers(p).allValues();
214
        if (fetchers.size() != 1)
215
            throw new IllegalStateException("Not one fetcher : " + fetchers);
216
        final SQLRowValuesListFetcher userFetcher = fetchers.iterator().next();
217
        final ITransformer<SQLSelect, SQLSelect> prevTransf = userFetcher.getSelTransf();
218
        userFetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
219
            @Override
220
            public SQLSelect transformChecked(SQLSelect input) {
221
                final List<Number> userIDs = new ArrayList<Number>();
222
                for (User user : users) {
223
                    userIDs.add(user.getId());
224
                }
225
                input.andWhere(new Where(input.getAlias(userVals.getTable()).getKey(), userIDs));
226
                // Because it can be the same fetcher that the previous on OPERATION
227
                return prevTransf == null ? input : prevTransf.transformChecked(input);
228
            }
229
        });
230
 
231
        final List<SQLRowValues> rows = fetcher.fetch();
232
 
141 ilm 233
        final Map<String, JCalendarItemGroup> groups = new HashMap<String, JCalendarItemGroup>();
234
 
112 ilm 235
        final List<JCalendarItem> result = new ArrayList<JCalendarItem>(rows.size());
236
        for (SQLRowValues r : rows) {
237
            final SQLRowValues user = r.followPath(p);
238
 
239
            if (user != null) {
240
                final SQLRowValues operation = r.followPath(pItemToOperation);
150 ilm 241
                final JCalendarItemDB item = new JCalendarItemDB(this.dir, r);
141 ilm 242
 
112 ilm 243
                item.setDayOnly(false);
244
                item.setDtStart(r.getDate("START"));
245
                item.setDtEnd(r.getDate("END"));
246
                item.setSummary(r.getString("SUMMARY"));
141 ilm 247
                item.setLocation(r.getString("LOCATION"));
112 ilm 248
 
141 ilm 249
                final String string = r.getForeign("ID_CALENDAR_ITEM_GROUP").getString("NAME");
250
 
251
                JCalendarItemGroup g = groups.get(string);
252
                if (g == null) {
253
                    g = new JCalendarItemGroup();
254
                    g.setName(string);
255
                    groups.put(string, g);
256
                }
257
                item.setGroup(g);
258
 
112 ilm 259
                if (r.getString("FLAGS") != null) {
260
                    List<String> str = StringUtils.fastSplit(r.getString("FLAGS"), ',');
261
 
262
                    for (String fId : str) {
263
                        Flag f = Flag.getFlag(fId);
264
                        if (f == null) {
265
                            f = new Flag(fId, null, fId, "");
266
                            Flag.register(f);
267
                        }
268
                        item.addFlag(f);
269
                    }
270
 
271
                }
272
                String desc = "";
273
                if (r.getString("DESCRIPTION") != null) {
274
                    desc += r.getString("DESCRIPTION") + "\n";
275
                }
276
                item.setDescription(desc);
277
                item.setColor(UserColor.getInstance().getColor(user.getID()));
278
                item.setCookie(user);
279
                item.setUserId(user.getID());
280
                item.setOperationStatus(operation.getString("STATUS"));
281
                item.setOperationType(operation.getString("TYPE"));
282
                item.setPlannerXML(operation.getString("PLANNER_XML"));
283
                item.setPlannerUID(operation.getString("PLANNER_UID"));
141 ilm 284
                if (operation.getForeign("ID_SITE") != null) {
285
                    item.setSiteName(operation.getForeign("ID_SITE").getString("NAME"));
286
                    item.setSiteId(operation.getForeign("ID_SITE").getIDNumber());
287
                    item.setSiteComment(operation.getForeign("ID_SITE").getString("COMMENT"));
288
                } else {
289
                    item.setSiteName("");
290
                    item.setSiteId(-1);
291
                    item.setSiteComment("");
292
                }
293
 
294
                String ruid = r.getString("UID");
295
                if (ruid == null || ruid.isEmpty()) {
296
                    ruid = String.valueOf(r.getID());
297
                }
298
                item.setUId(ruid);
112 ilm 299
                boolean isLocked = item.hasFlag(Flag.getFlag("locked"));
300
                if (!this.hideLocked && isLocked) {
301
                    result.add(item);
302
                } else if (!this.hideUnlocked && !isLocked) {
303
                    result.add(item);
304
                }
305
 
306
            }
307
        }
308
        return result;
309
    }
141 ilm 310
 
311
    public void addOrUpdateOperation(int idUser, String uid, Date start, Date end, String summary, String description, String location) throws SQLException {
312
        JCalendarItem i = this.getItemFromUid(uid);
313
        final SQLTable tOperation = root.getTable(ModuleOperation.TABLE_OPERATION);
314
        if (i == null) {
315
            // Create all from scratch
316
 
317
            SQLRowValues vOperation = new SQLRowValues(tOperation);
318
            vOperation.put("ID_SITE", null);
319
            vOperation.put("ID_USER_COMMON", idUser);
320
            vOperation.put("TYPE", "Inconnu");
321
            vOperation.put("STATUS", "Non classé");
322
            vOperation.put("DESCRIPTION", description);
323
 
324
            final SQLRow operationRow = vOperation.commit();
325
            SQLRow calendarGroupRow = operationRow.getForeignRow("ID_CALENDAR_ITEM_GROUP", SQLRowMode.DEFINED);
326
 
150 ilm 327
            final SQLRowValues rowItemGroup = new SQLRowValues(getCalendarItemGroupTable());
141 ilm 328
            rowItemGroup.put("NAME", summary);
329
            rowItemGroup.put("DESCRIPTION", description);
330
 
331
            calendarGroupRow = rowItemGroup.commit();
332
            // Update Operation
333
            SQLRowValues operationSQLRowValues = operationRow.asRowValues();
334
            operationSQLRowValues.put("ID_CALENDAR_ITEM_GROUP", calendarGroupRow.getID());
335
            operationSQLRowValues.commit();
336
            // Insert Calendar Items
337
            DateRange dateRange = new DateRange();
338
            dateRange.setStart(start.getTime());
339
            dateRange.setStop(end.getTime());
150 ilm 340
            final SQLRowValues rowItem = new SQLRowValues(getCalendarItemTable());
141 ilm 341
            rowItem.put("START", new Date(dateRange.getStart()));
342
            rowItem.put("END", new Date(dateRange.getStop()));
343
            rowItem.put("DURATION_S", (dateRange.getStop() - dateRange.getStart()) / 1000);
344
            rowItem.put("SUMMARY", summary);
345
            rowItem.put("DESCRIPTION", description);
346
            rowItem.put("LOCATION", location);
347
            rowItem.put("FLAGS", "");
348
            rowItem.put("STATUS", operationRow.getString("STATUS"));
349
            rowItem.put("ID_CALENDAR_ITEM_GROUP", calendarGroupRow.getID());
350
            rowItem.put("SOURCE_ID", operationRow.getID());
351
            rowItem.put("SOURCE_TABLE", ModuleOperation.TABLE_OPERATION);
352
            rowItem.put("UID", uid);
353
            rowItem.commit();
354
        } else {
355
            if (i instanceof JCalendarItemDB) {
356
                JCalendarItemDB item = (JCalendarItemDB) i;
357
                //
150 ilm 358
                final SQLRowValues vOperation = item.getSource().createEmptyUpdateRow();
141 ilm 359
                vOperation.put("DESCRIPTION", description);
360
                vOperation.commit();
361
                // group
150 ilm 362
                final SQLRowValues rowItemGroup = item.getCalendarGroup().createEmptyUpdateRow();
141 ilm 363
                rowItemGroup.put("NAME", summary);
364
                rowItemGroup.put("DESCRIPTION", description);
365
                rowItemGroup.commit();
366
                // item
367
                DateRange dateRange = new DateRange();
368
                dateRange.setStart(start.getTime());
369
                dateRange.setStop(end.getTime());
150 ilm 370
                final SQLRowValues rowItem = item.getRow().createEmptyUpdateRow();
141 ilm 371
                rowItem.put("START", new Date(dateRange.getStart()));
372
                rowItem.put("END", new Date(dateRange.getStop()));
373
                rowItem.put("DURATION_S", (dateRange.getStop() - dateRange.getStart()) / 1000);
374
                rowItem.put("SUMMARY", summary);
375
                rowItem.put("DESCRIPTION", description);
376
                rowItem.put("LOCATION", location);
377
                rowItem.commit();
378
            }
379
        }
380
 
381
    }
382
 
383
    public boolean delete(JCalendarItem item) {
384
        // TODO Auto-generated method stub
385
        return false;
386
    }
387
 
388
    public JCalendarItem getItemFromUid(String uid) {
389
        List<JCalendarItem> l = getItemIn(null, null, null, null, uid);
390
        if (l.isEmpty()) {
391
            System.err.println("OperationCalendarManager.getItemFromUid() nothing in db for uid: " + uid);
392
            return null;
393
        }
394
        return l.get(0);
395
    }
181 ilm 396
 
397
    /**
398
     * Enabled or disabled users
399
     */
400
    public List<User> getAllUsers() {
401
        final List<User> result = new ArrayList<>();
402
        for (User user : this.userMngr.getUsers().values()) {
403
            result.add(user);
404
        }
405
        return result;
406
    }
112 ilm 407
}