OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
156 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.supplychain.stock.element;
15
 
16
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
17
import org.openconcerto.erp.core.sales.product.model.ProductHelper;
18
import org.openconcerto.erp.core.sales.product.model.ProductHelper.SupplierPriceField;
19
import org.openconcerto.erp.importer.ArrayTableModel;
20
import org.openconcerto.erp.importer.DataImporter;
21
import org.openconcerto.sql.Configuration;
22
import org.openconcerto.sql.model.DBRoot;
23
import org.openconcerto.sql.model.SQLRow;
24
import org.openconcerto.sql.model.SQLRowAccessor;
25
import org.openconcerto.sql.model.SQLRowValues;
26
import org.openconcerto.sql.model.SQLRowValuesCluster.StoreMode;
27
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
28
import org.openconcerto.sql.model.SQLTable;
29
import org.openconcerto.sql.utils.SQLUtils;
30
 
31
import java.io.File;
32
import java.io.IOException;
33
import java.math.BigDecimal;
34
import java.sql.SQLException;
35
import java.util.ArrayList;
36
import java.util.Calendar;
37
import java.util.Collection;
38
import java.util.Date;
39
import java.util.HashMap;
40
import java.util.List;
41
import java.util.Map;
42
import java.util.Set;
43
 
44
import org.apache.commons.dbutils.ResultSetHandler;
45
 
46
public class InventaireFromEtatStockImporter {
47
 
48
    Map<String, SQLRowValues> kits = new HashMap<String, SQLRowValues>();
49
    List<String> codeKits = new ArrayList<String>();
50
 
51
    public InventaireFromEtatStockImporter() {
52
 
53
    }
54
 
55
    public void importArticles(File file, DBRoot root) throws IOException, SQLException {
56
 
57
        final SQLTable table = root.findTable("ARTICLE");
58
        final SQLTable tableArtElt = root.findTable("ARTICLE_ELEMENT");
59
 
60
        Map<String, SQLRowValues> articles = getArticles();
61
 
62
        final DataImporter importer = new DataImporter(table) {
63
            @Override
64
            protected void customizeRowValuesToFetch(SQLRowValues vals) {
65
 
66
                vals.putRowValues("ID_STOCK").putNulls("ID", "QTE_REEL", "QTE_TH", "ID_DEPOT_STOCK");
67
            }
68
        };
69
        importer.setSkipFirstLine(true);
70
 
71
        ArrayTableModel m = importer.createModelFrom(file);
72
 
73
        Calendar c = Calendar.getInstance();
74
        // c.set(Calendar.DAY_OF_MONTH, 1);
75
        // c.set(Calendar.MONTH, Calendar.JANUARY);
76
        // c.set(Calendar.HOUR_OF_DAY, 0);
77
        Date today = c.getTime();
78
 
79
        // TODO ne pas vider les stocks des kits, recalculer les stocks des kits
80
 
81
        SQLRowValues rowVals = new SQLRowValues(table.getTable("ETAT_STOCK"));
82
        rowVals.put("DATE", today);
83
        rowVals.put("INVENTAIRE", Boolean.TRUE);
84
        SQLRow rowEtat = rowVals.commit();
85
 
86
        for (int i = 1; i < m.getRowCount(); i++) {
87
            List<Object> o = m.getLineValuesAt(i);
88
            if (o.size() >= 5) {
89
                System.err.println(o);
90
                String code = o.get(1).toString();
91
                if (code.trim().length() > 0) {
92
 
93
                    final String stringQty = o.get(4).toString();
94
                    Double qty = stringQty.trim().length() == 0 ? 0 : Double.valueOf(stringQty);
95
                    final String stringQtyOld = o.get(3).toString();
96
                    float qtyOld = stringQtyOld.trim().length() == 0 ? 0 : Float.valueOf(stringQtyOld);
97
 
98
                    SQLRowValues match = articles.get(code);
99
                    if (match != null) {
100
 
101
                        SQLRowAccessor stockValues = match.getForeign("ID_STOCK");
102
 
103
                        final SQLTable tableMvt = table.getTable("MOUVEMENT_STOCK");
104
                        SQLRowValues rowValsMvtStockClotureFermeture = new SQLRowValues(tableMvt);
105
                        rowValsMvtStockClotureFermeture.put("QTE", -qtyOld);
106
                        rowValsMvtStockClotureFermeture.put("NOM", "Clôture stock avant inventaire");
107
                        rowValsMvtStockClotureFermeture.put("ID_ARTICLE", match.getID());
108
                        rowValsMvtStockClotureFermeture.put("DATE", today);
109
                        rowValsMvtStockClotureFermeture.put("REEL", Boolean.TRUE);
110
                        rowValsMvtStockClotureFermeture.put("ID_STOCK", stockValues.getID());
111
 
112
                        BigDecimal prc = getPRC(match, Math.round(qtyOld), today);
113
                        if (prc == null) {
114
                            prc = BigDecimal.ZERO;
115
                        }
116
                        if (tableMvt.contains("PRICE")) {
117
                            rowValsMvtStockClotureFermeture.put("PRICE", prc);
118
                        }
119
                        rowValsMvtStockClotureFermeture.put("CLOTURE", Boolean.TRUE);
120
                        rowValsMvtStockClotureFermeture.put("ID_ETAT_STOCK", rowEtat.getID());
121
                        rowValsMvtStockClotureFermeture.getGraph().store(StoreMode.COMMIT, false);
122
 
123
                        SQLRowValues rowValsItem = new SQLRowValues(table.getTable("ETAT_STOCK_ELEMENT"));
124
                        rowValsItem.put("ID_ETAT_STOCK", rowEtat.getID());
125
                        rowValsItem.put("PA", prc);
126
                        rowValsItem.put("PV", BigDecimal.ZERO);
127
                        rowValsItem.put("QTE", qtyOld);
128
                        rowValsItem.put("T_PA", prc.multiply(new BigDecimal(qtyOld)));
129
                        rowValsItem.put("T_PV", BigDecimal.ZERO);
130
                        rowValsItem.put("CODE", match.getString("CODE"));
131
                        rowValsItem.put("NOM", match.getString("NOM"));
132
                        rowValsItem.put("ID_ARTICLE", match.getID());
133
                        rowValsItem.getGraph().store(StoreMode.COMMIT, false);
134
 
135
                        SQLRowValues rowValsMvtStockClotureOuverture = new SQLRowValues(tableMvt);
136
                        rowValsMvtStockClotureOuverture.put("QTE", qty);
137
                        rowValsMvtStockClotureOuverture.put("NOM", "Mise en stock inventaire");
138
                        rowValsMvtStockClotureOuverture.put("ID_ETAT_STOCK", rowEtat.getID());
139
                        rowValsMvtStockClotureOuverture.put("ID_ARTICLE", match.getID());
140
                        rowValsMvtStockClotureOuverture.put("DATE", today);
141
                        rowValsMvtStockClotureOuverture.put("REEL", Boolean.TRUE);
142
                        rowValsMvtStockClotureOuverture.put("ID_STOCK", stockValues.getID());
143
                        rowValsMvtStockClotureOuverture.put("OUVERTURE", Boolean.TRUE);
144
                        if (tableMvt.contains("PRICE")) {
145
                            rowValsMvtStockClotureOuverture.put("PRICE", getPRC(match, qty.intValue(), today));
146
                        }
147
                        rowValsMvtStockClotureOuverture.getGraph().store(StoreMode.COMMIT, false);
148
 
149
                        if (!match.isForeignEmpty("ID_STOCK")) {
150
                            match.getForeign("ID_STOCK").createEmptyUpdateRow().put("QTE_REEL", qty).commit();
151
                        } else {
152
                            final SQLRowValues createEmptyUpdateRow = match.createEmptyUpdateRow();
153
                            createEmptyUpdateRow.putRowValues("ID_STOCK").put("QTE_REEL", qty);
154
                            createEmptyUpdateRow.getGraph().store(StoreMode.COMMIT, false);
155
 
156
                        }
157
 
158
                    } else {
159
                        System.err.println("Aucun article correspondant au code " + code);
160
                    }
161
                }
162
            }
163
        }
164
 
165
        /**
166
         * Mise à jour des kits
167
         */
168
 
169
        List<String> reqs = new ArrayList<String>();
170
        for (String code : codeKits) {
171
            System.err.println(code);
172
            SQLRowValues rowValsKit = kits.get(code);
173
            StockItem item = new StockItem(rowValsKit, rowValsKit.getForeign("ID_STOCK"));
174
            Collection<SQLRowValues> elts = rowValsKit.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT"));
175
            for (SQLRowValues sqlRowValues : elts) {
176
                if (sqlRowValues.getForeign("ID_ARTICLE") != null) {
177
                    item.addItemComponent(new StockItemComponent(new StockItem(sqlRowValues.getForeign("ID_ARTICLE"), sqlRowValues.getForeign("ID_ARTICLE").getForeign("ID_STOCK")),
178
                            sqlRowValues.getBigDecimal("QTE_UNITAIRE"), sqlRowValues.getInt("QTE")));
179
                }
180
            }
181
            item.updateQtyFromChildren();
182
            reqs.add(item.getUpdateRequest());
183
        }
184
 
185
        List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(reqs.size());
186
        for (String s : reqs) {
187
            handlers.add(null);
188
        }
189
        // FIXME FIRE TABLE CHANGED TO UPDATE ILISTE ??
190
        SQLUtils.executeMultiple(table.getDBSystemRoot(), reqs, handlers);
191
 
192
        /**
193
         * Mise à jour des prix mini
194
         */
195
        // for (SQLRowValues rowValsArt : rowValsArtNonSync) {
196
        // SQLRow rowArt = rowValsArt.asRow();
197
        // List<SQLRow> rowsPVMin =
198
        // rowArt.getReferentRows(tableArtElt.getTable("ARTICLE_PRIX_MIN_VENTE"));
199
        // List<SQLRow> rowsPA =
200
        // rowArt.getReferentRows(tableArtElt.getTable("ARTICLE_TARIF_FOURNISSEUR"));
201
        //
202
        // // On récupére les derniers prix min valides
203
        // Map<Integer, SQLRow> mapLastValidRows = new HashMap<Integer, SQLRow>();
204
        // for (SQLRow rowPVMin : rowsPVMin) {
205
        // final int qteMinPrice = rowPVMin.getInt("QTE");
206
        // SQLRow rowValsLastValid = mapLastValidRows.get(qteMinPrice);
207
        // if (rowValsLastValid == null || rowValsLastValid.getDate("DATE") == null ||
208
        // rowValsLastValid.getDate("DATE").before(rowPVMin.getDate("DATE"))) {
209
        // mapLastValidRows.put(qteMinPrice, rowPVMin);
210
        // }
211
        // }
212
        //
213
        // // On récupére les derniers Prix d'achat valide
214
        // Map<Integer, SQLRow> mapLastValidAchatRows = new HashMap<Integer, SQLRow>();
215
        // for (SQLRow rowPA : rowsPA) {
216
        // final int qtePRC = rowPA.getInt("QTE");
217
        // SQLRow rowValsLastValid = mapLastValidAchatRows.get(qtePRC);
218
        // if (rowValsLastValid == null || rowValsLastValid.getDate("DATE_PRIX") == null ||
219
        // rowValsLastValid.getDate("DATE_PRIX").before(rowPA.getDate("DATE_PRIX"))) {
220
        // mapLastValidAchatRows.put(qtePRC, rowPA);
221
        // }
222
        // }
223
        //
224
        // // Mise à jour, si Prix < au prix min, du PRC et des prix min
225
        // for (Integer qte : mapLastValidAchatRows.keySet()) {
226
        // SQLRow rowVals = mapLastValidAchatRows.get(qte);
227
        // checkMinPrice(rowVals, mapLastValidRows.get(qte));
228
        // }
229
        // }
230
 
231
    }
232
 
233
    private void checkMinPrice(SQLRow rowValsSuplierLastValid, SQLRow lastValidRow) {
234
        boolean update = false;
235
        final ProductHelper helper = new ProductHelper(rowValsSuplierLastValid.getTable().getDBRoot());
236
 
237
        BigDecimal result = helper.getEnumPrice(rowValsSuplierLastValid, SupplierPriceField.COEF_PRIX_MINI);
238
        if (result != null) {
239
            final int qteSuplier = rowValsSuplierLastValid.getInt("QTE");
240
 
241
            final Calendar date2 = rowValsSuplierLastValid.getDate("DATE_PRIX");
242
            if (date2 != null) {
243
                if (lastValidRow != null) {
244
                    final Calendar date1 = lastValidRow.getDate("DATE");
245
                    if ((date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR) && date1.get(Calendar.MONTH) == date2.get(Calendar.MONTH)
246
                            && date1.get(Calendar.DAY_OF_MONTH) == date2.get(Calendar.DAY_OF_MONTH)) || date1.after(date2)) {
247
                        if (lastValidRow.getBigDecimal("PRIX") != null && lastValidRow.getInt("QTE") <= qteSuplier) {
248
                            try {
249
                                lastValidRow.asRowValues().put("PRIX", result).commit();
250
                            } catch (SQLException e) {
251
                                // TODO Auto-generated catch block
252
                                e.printStackTrace();
253
                            }
254
                            // purchaseMinPriceListTable.setPriceMin(result);
255
                            update = true;
256
                        }
257
                    } else {
258
                        if (date1.before(date2)) {
259
                            SQLRowValues rowValsToInsert = new SQLRowValues(lastValidRow.getTable());
260
                            rowValsToInsert.put("PRIX", result);
261
                            rowValsToInsert.put("DATE", rowValsSuplierLastValid.getObject("DATE_PRIX"));
262
                            rowValsToInsert.put("QTE", rowValsSuplierLastValid.getObject("QTE"));
263
                            rowValsToInsert.put("ID_ARTICLE", rowValsSuplierLastValid.getInt("ID_ARTICLE"));
264
                            try {
265
                                rowValsToInsert.commit();
266
                            } catch (SQLException e) {
267
                                // TODO Auto-generated catch block
268
                                e.printStackTrace();
269
                            }
270
                        }
271
                    }
272
                }
273
            }
274
        }
275
 
276
    }
277
 
278
    public BigDecimal getPRC(SQLRowValues rowVals, int qty, Date d) {
279
        // SQLTable table = rowVals.getTable().getDBRoot().getTable("ARTICLE_PRIX_REVIENT");
280
        // Collection<SQLRow> prcs = rowVals.asRow().getReferentRows(table);
281
        //
282
        // BigDecimal result = null;
283
        // final List<PriceByQty> prices = new ArrayList<PriceByQty>();
284
        //
285
        // for (SQLRow row : prcs) {
286
        // Calendar date = Calendar.getInstance();
287
        // date.set(Calendar.DAY_OF_MONTH, 1);
288
        // date.set(Calendar.MONTH, 1);
289
        // date.set(Calendar.YEAR, 2001);
290
        // if (row.getObject("DATE") != null) {
291
        // date = row.getDate("DATE");
292
        // }
293
        // prices.add(new PriceByQty(row.getLong("QTE"), row.getBigDecimal("PRIX"),
294
        // date.getTime()));
295
        // }
296
        //
297
        // result = PriceByQty.getPriceForQty(qty, prices, d);
298
        // if (result == null) {
299
        // // Can occur during editing
300
        // result = BigDecimal.ZERO;
301
        // }
302
 
303
        ProductComponent comp = new ProductComponent(rowVals, new BigDecimal(qty), null, null);
304
        return comp.getPRC(d);
305
        // return result;
306
    }
307
 
308
    private Map<String, SQLRowValues> getArticles() throws SQLException {
309
        final SQLTable table = Configuration.getInstance().getRoot().findTable("ARTICLE");
310
        SQLRowValues graph = new SQLRowValues(table);
311
        graph.put("ID", null);
312
        graph.put("CODE", null);
313
        graph.put("NOM", null);
314
        graph.put("NOM", null);
315
        graph.putRowValues("ID_STOCK").putNulls("ID_DEPOT_STOCK", "ID", "QTE_REEL", "QTE_TH", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
316
 
317
        final SQLTable tableArtElt = table.getTable("ARTICLE_ELEMENT");
318
        SQLRowValues artElt = new SQLRowValues(tableArtElt);
319
        artElt.put("ID", null);
320
        artElt.put("QTE", null);
321
        artElt.put("QTE_UNITAIRE", null);
322
        artElt.put("ID_ARTICLE_PARENT", graph);
323
        artElt.putRowValues("ID_ARTICLE").putNulls("ID", "CODE", "NOM").putRowValues("ID_STOCK").putNulls("ID_DEPOT_STOCK", "QTE_TH", "QTE_REEL", "QTE_LIV_ATTENTE", "QTE_RECEPT_ATTENTE");
324
 
325
        SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(graph);
326
        List<SQLRowValues> results = fetcher.fetch();
327
 
328
        Calendar c = Calendar.getInstance();
329
        // c.set(Calendar.DAY_OF_MONTH, 1);
330
        c.add(Calendar.MONTH, -2);
331
        c.set(Calendar.DAY_OF_MONTH, 31);
332
        Date dEndYear = c.getTime();
333
 
334
        Map<String, SQLRowValues> vals = new HashMap<String, SQLRowValues>();
335
        for (SQLRowValues sqlRowValues : results) {
336
            final String code = sqlRowValues.getString("CODE");
337
            vals.put(code, sqlRowValues);
338
 
339
            final Set<SQLRowValues> referentRows = sqlRowValues.getReferentRows(tableArtElt.getField("ID_ARTICLE_PARENT"));
340
            if (referentRows.size() == 0) {
341
                // if (!sqlRowValues.isForeignEmpty("ID_STOCK")) {
342
                // SQLRowAccessor rowValsStock = sqlRowValues.getForeign("ID_STOCK");
343
                // int qteReel = rowValsStock.getInt("QTE_REEL");
344
                // {
345
                // SQLRowValues rowValsMvtStockCloture = new
346
                // SQLRowValues(table.getTable("MOUVEMENT_STOCK"));
347
                // rowValsMvtStockCloture.put("QTE", -qteReel);
348
                // rowValsMvtStockCloture.put("NOM", "Clôture du stock avant inventaire");
349
                // rowValsMvtStockCloture.put("ID_ARTICLE", sqlRowValues.getID());
350
                // rowValsMvtStockCloture.put("DATE", dEndYear);
351
                // rowValsMvtStockCloture.put("REEL", Boolean.TRUE);
352
                // rowValsMvtStockCloture.put("PRICE", getPRC(sqlRowValues, qteReel, dEndYear));
353
                // rowValsMvtStockCloture.commit();
354
                //
355
                // rowValsStock.createEmptyUpdateRow().put("QTE_REEL", 0).commit();
356
                // }
357
                //
358
                // } else {
359
                // sqlRowValues.putRowValues("ID_STOCK").commit();
360
                // }
361
            } else {
362
                boolean contains = false;
363
                for (SQLRowValues sqlRowValues2 : referentRows) {
364
                    if (!sqlRowValues2.isForeignEmpty("ID_ARTICLE") && sqlRowValues2.getForeign("ID_ARTICLE") != null && sqlRowValues2.getForeign("ID_ARTICLE").getString("CODE") != null) {
365
                        if (codeKits.contains(sqlRowValues2.getForeign("ID_ARTICLE").getString("CODE"))) {
366
                            contains = true;
367
                            break;
368
                        }
369
                    }
370
                }
371
                if (!contains) {
372
                    codeKits.add(0, code);
373
                } else {
374
                    codeKits.add(code);
375
                }
376
                kits.put(code, sqlRowValues);
377
                // if (sqlRowValues.isForeignEmpty("ID_STOCK")) {
378
                // sqlRowValues.putRowValues("ID_STOCK").commit();
379
                // }
380
            }
381
        }
382
        return vals;
383
    }
384
}