OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
132 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.sql.ui.light;
15
 
16
import org.openconcerto.sql.Configuration;
17
import org.openconcerto.sql.Log;
18
import org.openconcerto.sql.element.SQLElement;
19
import org.openconcerto.sql.model.FieldMapper;
20
import org.openconcerto.sql.model.SQLField;
21
import org.openconcerto.sql.model.SQLRow;
22
import org.openconcerto.sql.model.SQLRowValues;
23
import org.openconcerto.sql.model.SQLTable;
24
import org.openconcerto.sql.view.EditPanel.EditMode;
142 ilm 25
import org.openconcerto.sql.view.list.ListSQLLine;
26
import org.openconcerto.sql.view.list.SQLTableModelLinesSourceOffline;
132 ilm 27
import org.openconcerto.ui.group.Group;
28
import org.openconcerto.ui.group.Item;
29
import org.openconcerto.ui.light.CustomEditorProvider;
30
import org.openconcerto.ui.light.JSONToLightUIConvertor;
31
import org.openconcerto.ui.light.LightUICheckBox;
32
import org.openconcerto.ui.light.LightUIComboBox;
33
import org.openconcerto.ui.light.LightUIDate;
34
import org.openconcerto.ui.light.LightUIElement;
35
import org.openconcerto.ui.light.LightUIFrame;
36
import org.openconcerto.utils.io.JSONConverter;
37
 
142 ilm 38
import java.math.BigDecimal;
132 ilm 39
import java.sql.SQLException;
40
import java.sql.Timestamp;
41
import java.util.Date;
42
import java.util.Map;
142 ilm 43
import java.util.concurrent.Future;
132 ilm 44
 
45
import net.minidev.json.JSONObject;
46
 
47
public class LightEditFrame extends LightUIFrame {
48
    private static final String EDIT_MODE_JSON_KEY = "edit-mode";
49
 
50
    private Group group;
51
    private SQLRowValues sqlRow;
52
 
53
    private EditMode editMode = EditMode.READONLY;
54
 
55
    // Init from json constructor
56
    public LightEditFrame(final JSONObject json) {
57
        super(json);
58
    }
59
 
60
    // Clone constructor
61
    public LightEditFrame(final LightEditFrame frame) {
62
        super(frame);
63
        this.sqlRow = frame.sqlRow;
64
        this.group = frame.group;
65
        this.editMode = frame.editMode;
66
    }
67
 
68
    public LightEditFrame(final Configuration conf, final Group group, final SQLRowValues sqlRow, final LightUIFrame parentFrame, final EditMode editMode) {
69
        super(group.getId() + ".edit.frame");
70
        this.setType(TYPE_FRAME);
71
        this.setParent(parentFrame);
72
 
73
        this.sqlRow = sqlRow;
74
        this.group = group;
75
 
76
        this.setEditMode(editMode);
77
    }
78
 
79
    public void setEditMode(final EditMode editMode) {
80
        this.editMode = editMode;
81
        if (editMode.equals(EditMode.READONLY)) {
82
            this.setReadOnly(true);
83
        } else {
84
            this.setReadOnly(false);
85
        }
86
    }
87
 
88
    /**
89
     * Commit the SQLRowValues attached to this frame
90
     *
142 ilm 91
     * @param configuration - Current configuration
92
     *
132 ilm 93
     * @return The inserted SQLRow
142 ilm 94
     *
95
     * @throws SQLException When an error occur in SQLRowValues.commit()
132 ilm 96
     */
142 ilm 97
    public SQLRow commitSqlRow(final Configuration configuration) throws SQLException {
132 ilm 98
        if (this.editMode.equals(EditMode.READONLY)) {
99
            throw new IllegalArgumentException("Impossible to commit values when the frame is read only");
100
        }
101
        final SQLElement sqlElement = configuration.getDirectory().getElement(this.sqlRow.getTable());
102
        try {
103
            return this.sqlRow.prune(sqlElement.getPrivateGraph()).commit();
104
        } catch (final SQLException ex) {
142 ilm 105
            throw ex;
132 ilm 106
        }
107
    }
108
 
109
    public EditMode getEditMode() {
110
        return this.editMode;
111
    }
112
 
113
    public Group getGroup() {
114
        return this.group;
115
    }
116
 
117
    public SQLRowValues getSqlRow() {
118
        return this.sqlRow;
119
    }
120
 
121
    /**
122
     * Update the SQLRowValues attached to this frame
123
     *
124
     * @param conf
125
     * @param userId
126
     */
142 ilm 127
    public void updateRow(final Configuration configuration, final String sessionSecurityToken, final int userId) {
132 ilm 128
        if (this.editMode.equals(EditMode.READONLY)) {
129
            throw new IllegalArgumentException("Impossible to update values when the frame is read only");
130
        }
142 ilm 131
        this.updateRow(configuration, this.group, sessionSecurityToken, userId);
132 ilm 132
    }
133
 
142 ilm 134
    private void updateRow(final Configuration configuration, final Group group, final String sessionSecurityToken, final int userId) {
132 ilm 135
        final FieldMapper fieldMapper = configuration.getFieldMapper();
136
        if (fieldMapper == null) {
137
            throw new IllegalStateException("null field mapper");
138
        }
139
 
140
        final SQLElement sqlElement = configuration.getDirectory().getElement(this.sqlRow.getTable());
141
 
142 ilm 142
        final Map<String, CustomEditorProvider> customEditors;
132 ilm 143
        if (this.editMode.equals(EditMode.CREATION)) {
142 ilm 144
            customEditors = sqlElement.getCustomEditorProviderForCreation(configuration, sessionSecurityToken);
132 ilm 145
        } else {
142 ilm 146
            customEditors = sqlElement.getCustomEditorProviderForModification(configuration, this.sqlRow, sessionSecurityToken);
132 ilm 147
        }
148
 
142 ilm 149
        this.createRowValues(configuration, sqlElement, fieldMapper, this.group, customEditors);
132 ilm 150
        this.setMetaData(userId);
151
    }
152
 
142 ilm 153
    final protected void createRowValues(final Configuration configuration, final SQLElement sqlElement, final FieldMapper fieldMapper, final Group group,
132 ilm 154
            final Map<String, CustomEditorProvider> customEditors) {
155
        final int itemCount = group.getSize();
156
        for (int i = 0; i < itemCount; i++) {
157
            final Item item = group.getItem(i);
158
            if (item instanceof Group) {
142 ilm 159
                this.createRowValues(configuration, sqlElement, fieldMapper, (Group) item, customEditors);
132 ilm 160
            } else {
161
                final SQLField field = fieldMapper.getSQLFieldForItem(item.getId());
162
                if (field != null) {
163
                    final LightUIElement uiElement = this.findChild(item.getId(), false);
164
 
165
                    if (uiElement == null) {
166
                        throw new IllegalArgumentException("Impossible to find UI Element with id: " + item.getId());
167
                    }
168
 
142 ilm 169
                    if (!uiElement.isNotSaved()) {
170
                        this.putValueFromUserControl(configuration, sqlElement, field, uiElement, customEditors);
132 ilm 171
                    }
172
                } else {
173
                    Log.get().warning("No field attached to " + item.getId());
174
                }
175
            }
176
        }
177
    }
178
 
142 ilm 179
    final protected void putValueFromUserControl(final Configuration configuration, final SQLElement sqlElement, final SQLField sqlField, final LightUIElement uiElement,
180
            final Map<String, CustomEditorProvider> customEditors) {
181
        if (!uiElement.isNotSaved()) {
182
            final Class<?> fieldType = sqlField.getType().getJavaType();
183
            if (customEditors.containsKey(uiElement.getId())) {
184
                final CustomEditorProvider customEditor = customEditors.get(uiElement.getId());
185
                if (customEditor instanceof SavableCustomEditorProvider) {
186
                    ((SavableCustomEditorProvider) customEditor).save(this.sqlRow, sqlField, uiElement);
187
                }
188
            } else {
189
                final String fieldName = sqlField.getFieldName();
190
                if (sqlField.isKey()) {
191
                    if (!(uiElement instanceof LightUIComboBox)) {
192
                        throw new IllegalArgumentException("Invalid UI Element for field: " + fieldName + ". When field is foreign key, UI Element must be a LightUIDate");
193
                    }
194
                    final LightUIComboBox combo = (LightUIComboBox) uiElement;
132 ilm 195
 
142 ilm 196
                    if (combo.hasSelectedValue()) {
197
                        this.sqlRow.put(fieldName, combo.getSelectedValue().getId());
198
                    } else {
199
                        this.sqlRow.put(fieldName, null);
200
                    }
201
                } else {
202
                    final String value = uiElement.getValue();
203
                    if (value == null && !sqlField.isNullable()) {
204
                        Log.get().warning("ignoring null value for not nullable field " + fieldName + " from table " + sqlField.getTable().getName());
205
                    } else {
206
                        if (fieldType.equals(String.class)) {
207
                            // FIXME check string size against field size
208
                            this.sqlRow.put(fieldName, value);
209
                        } else if (fieldType.equals(Date.class)) {
210
                            if (!(uiElement instanceof LightUIDate)) {
211
                                throw new IllegalArgumentException("Invalid UI Element for field: " + fieldName + ". When field is Date, UI Element must be a LightUIDate");
212
                            }
213
                            this.sqlRow.put(fieldName, ((LightUIDate) uiElement).getValueAsDate());
214
                        } else if (fieldType.equals(Boolean.class)) {
215
                            if (!(uiElement instanceof LightUICheckBox)) {
216
                                throw new IllegalArgumentException("Invalid UI Element for field: " + fieldName + ". When field is Boolean, UI Element must be a LightUICheckBox");
217
                            }
218
                            this.sqlRow.put(fieldName, ((LightUICheckBox) uiElement).isChecked());
219
                        } else if (fieldType.equals(Timestamp.class)) {
220
                            if (!(uiElement instanceof LightUIDate)) {
221
                                throw new IllegalArgumentException("Invalid UI Element for field: " + fieldName + ". When field is Date, UI Element must be a LightUIDate");
222
                            }
223
                            this.sqlRow.put(fieldName, ((LightUIDate) uiElement).getValueAsDate());
224
                        } else if (fieldType.equals(Integer.class)) {
225
                            if (value != null && !value.trim().isEmpty()) {
226
                                if (!value.matches("^-?\\d+$")) {
227
                                    throw new IllegalArgumentException("Invalid value for field: " + fieldName + " value: " + value);
228
                                }
229
                                this.sqlRow.put(fieldName, Integer.parseInt(value));
230
                            } else {
231
                                this.sqlRow.put(fieldName, null);
232
                            }
233
                        } else if (fieldType.equals(Double.class) || fieldType.equals(Float.class) || fieldType.equals(BigDecimal.class)) {
234
                            if (value != null && !value.trim().isEmpty()) {
235
                                try {
236
                                    this.sqlRow.put(fieldName, new BigDecimal(value));
237
                                } catch (final Exception ex) {
238
                                    throw new IllegalArgumentException("Invalid value for field: " + fieldName + " value: " + value);
239
                                }
132 ilm 240
 
142 ilm 241
                            } else {
242
                                this.sqlRow.put(fieldName, null);
243
                            }
244
                        } else {
245
                            Log.get().warning("unsupported type " + fieldName);
246
                        }
247
                    }
132 ilm 248
                }
249
            }
250
        }
251
    }
252
 
253
    /**
254
     * Save all referent rows store in LightRowValuesTable
255
     *
256
     * @param group Element edit group
257
     * @param frame Element edit frame
258
     * @param row Element saved row
259
     * @param customEditors List of custom editors used in element edit frame
260
     */
142 ilm 261
    final public void saveReferentRows(final Configuration configuration, final SQLRow parentSqlRow, final Map<String, CustomEditorProvider> customEditors, final String sessionSecurityToken) {
262
        this.saveReferentRows(configuration, this.group, parentSqlRow, customEditors, sessionSecurityToken);
132 ilm 263
    }
264
 
142 ilm 265
    final private void saveReferentRows(final Configuration configuration, final Group group, final SQLRow parentSqlRow, final Map<String, CustomEditorProvider> customEditors,
266
            final String sessionSecurityToken) {
132 ilm 267
        for (int i = 0; i < group.getSize(); i++) {
268
            final Item item = group.getItem(i);
269
            if (item instanceof Group) {
142 ilm 270
                this.saveReferentRows(configuration, (Group) item, parentSqlRow, customEditors, sessionSecurityToken);
132 ilm 271
            } else if (customEditors.containsKey(item.getId())) {
272
                final LightUIElement element = this.findChild(item.getId(), false);
142 ilm 273
                if (element instanceof LightForeignRowValuesTableOffline) {
274
                    final LightForeignRowValuesTableOffline foreignTable = (LightForeignRowValuesTableOffline) element;
275
                    for (int j = 0; j < foreignTable.getRowsCount(); j++) {
276
                        final ListSQLLine listLine = foreignTable.getModel().getRow(j);
277
                        final SQLRowValues rowVals = listLine.getRow().createEmptyUpdateRow();
278
                        rowVals.put(foreignTable.getForeignField().getName(), parentSqlRow.getID());
279
                        ((SQLTableModelLinesSourceOffline) foreignTable.getModel().getLinesSource()).updateRow(listLine.getID(), rowVals);
132 ilm 280
                    }
142 ilm 281
                    final Future<?> fCommit = foreignTable.commitRows();
282
 
283
                    try {
284
                        fCommit.get();
285
                    } catch (final Exception ex) {
286
                        throw new IllegalArgumentException(ex);
287
                    }
132 ilm 288
                }
289
            }
290
        }
291
    }
292
 
293
    final protected void setMetaData(final int userId) {
294
        final SQLTable sqlTable = this.sqlRow.getTable();
295
        if (this.sqlRow.getObject(sqlTable.getCreationUserField().getName()) == null || this.sqlRow.getObject(sqlTable.getCreationDateField().getName()) == null) {
296
            this.sqlRow.put(sqlTable.getCreationUserField().getName(), userId);
297
            this.sqlRow.put(sqlTable.getCreationDateField().getName(), new Date());
298
        }
299
        this.sqlRow.put(sqlTable.getModifUserField().getName(), userId);
300
        this.sqlRow.put(sqlTable.getModifDateField().getName(), new Date());
301
    }
302
 
303
    @Override
304
    public String getClassName() {
305
        return this.getClass().getName();
306
    }
307
 
308
    @Override
309
    public JSONToLightUIConvertor getConvertor() {
310
        return new JSONToLightUIConvertor() {
311
 
312
            @Override
313
            public LightUIElement convert(JSONObject json) {
314
                return new LightEditFrame(json);
315
            }
316
        };
317
    }
318
 
319
    @Override
320
    public LightUIElement clone() {
321
        return new LightEditFrame(this);
322
    }
323
 
324
    // TODO: implement JSONAble on SQLRowValues and Group
325
    @Override
326
    public JSONObject toJSON() {
327
        final JSONObject json = super.toJSON();
328
        if (!this.editMode.equals(EditMode.READONLY)) {
329
            if (this.editMode.equals(EditMode.CREATION)) {
330
                json.put(EDIT_MODE_JSON_KEY, 1);
331
            } else if (this.editMode.equals(EditMode.MODIFICATION)) {
332
                json.put(EDIT_MODE_JSON_KEY, 2);
333
            }
334
        }
335
        return json;
336
    }
337
 
338
    @Override
339
    public void fromJSON(final JSONObject json) {
340
        super.fromJSON(json);
341
        final int jsonEditMode = JSONConverter.getParameterFromJSON(json, EDIT_MODE_JSON_KEY, Integer.class, 3);
342
        if (jsonEditMode == 1) {
343
            this.editMode = EditMode.CREATION;
344
        } else if (jsonEditMode == 2) {
345
            this.editMode = EditMode.MODIFICATION;
346
        } else if (jsonEditMode == 3) {
347
            this.editMode = EditMode.READONLY;
348
        }
349
    }
350
}