OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
93 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.sales.product.model;
15
 
16
import org.openconcerto.sql.model.DBRoot;
17
import org.openconcerto.sql.model.SQLDataSource;
18
import org.openconcerto.sql.model.SQLRow;
19
import org.openconcerto.sql.model.SQLRowAccessor;
20
import org.openconcerto.sql.model.SQLRowListRSH;
21
import org.openconcerto.sql.model.SQLRowValues;
22
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
23
import org.openconcerto.sql.model.SQLSelect;
24
import org.openconcerto.sql.model.SQLTable;
25
import org.openconcerto.sql.model.Where;
26
import org.openconcerto.utils.DecimalUtils;
156 ilm 27
import org.openconcerto.utils.ListMap;
177 ilm 28
import org.openconcerto.utils.Tuple2;
93 ilm 29
import org.openconcerto.utils.cc.ITransformer;
30
 
31
import java.math.BigDecimal;
132 ilm 32
import java.math.RoundingMode;
93 ilm 33
import java.util.ArrayList;
34
import java.util.Calendar;
35
import java.util.Collection;
36
import java.util.Date;
37
import java.util.HashMap;
38
import java.util.HashSet;
39
import java.util.List;
40
import java.util.Map;
41
import java.util.Set;
42
 
43
public class ProductHelper {
44
 
45
    private DBRoot root;
46
 
47
    public ProductHelper(DBRoot root) {
48
        this.root = root;
49
    }
50
 
132 ilm 51
    public interface PriceField {
52
    };
53
 
54
    public enum SupplierPriceField implements PriceField {
55
        PRIX_ACHAT, COEF_TRANSPORT_PORT, COEF_TAXE_D, COEF_TRANSPORT_SIEGE, COEF_FRAIS_MOULE, COEF_FRAIS_INDIRECTS, COEF_PRIX_MINI
56
    };
57
 
58
    public BigDecimal getEnumPrice(final SQLRowAccessor r, PriceField field) {
59
        final PriceField[] values = field.getClass().getEnumConstants();
60
        BigDecimal result = r.getBigDecimal(values[0].toString());
61
        if (result == null) {
62
            return null;
63
        }
64
 
65
        for (int i = 1; i < values.length; i++) {
66
 
67
            BigDecimal m0 = r.getBigDecimal(values[i].toString());
68
            if (m0 != null && m0.floatValue() > 0) {
69
                result = result.divide(m0, 2, RoundingMode.HALF_UP);
70
            }
71
            if (values[i] == field) {
72
                break;
73
            }
74
        }
75
        return result;
76
    }
77
 
174 ilm 78
    /**
79
     * Fill productComponents with items (SQLrowAccessor of TABLE_ELEMENT)
80
     *
81
     * @param items
82
     * @param productComponents
83
     * @param qte
84
     * @param index
85
     * @param level
86
     */
87
    public void fillProductComponent(List<? extends SQLRowAccessor> itemsTableElement, List<ProductComponent> productComponents, int qte, int index, int level) {
88
        if (level > 0) {
89
            for (int i = index; i < itemsTableElement.size(); i++) {
90
                SQLRowAccessor r = itemsTableElement.get(i);
91
 
92
                if (!r.getTable().contains("NIVEAU") || r.getInt("NIVEAU") >= level) {
93
                    // On ne calcul pas les stocks pour les éléments ayant des fils (le mouvement de
94
                    // stock
95
                    // des fils impactera les stocks automatiquement)
96
                    if (r.getTable().contains("NIVEAU")) {
97
                        if (i + 1 < itemsTableElement.size()) {
98
                            SQLRowAccessor rNext = itemsTableElement.get(i + 1);
99
                            if (rNext.getInt("NIVEAU") > r.getInt("NIVEAU")) {
100
                                fillProductComponent(itemsTableElement, productComponents, qte * r.getInt("QTE"), i + 1, rNext.getInt("NIVEAU"));
101
                                continue;
102
                            }
103
                        }
104
                    }
105
                    if ((!r.getTable().contains("NIVEAU") || r.getInt("NIVEAU") == level) && r.getForeign("ID_ARTICLE") != null && !r.isForeignEmpty("ID_ARTICLE")) {
106
                        productComponents.add(ProductComponent.createFrom(r, qte, r));
107
                    }
108
                } else if (r.getInt("NIVEAU") < level) {
109
                    // BREAK si on sort de l'article composé
110
                    break;
111
                }
112
            }
113
        }
114
    }
115
 
93 ilm 116
    public BigDecimal getUnitCostForQuantity(SQLRowAccessor rArticle, int qty) {
117
 
118
        Collection<? extends SQLRowAccessor> l = rArticle.getReferentRows(rArticle.getTable().getTable("ARTICLE_PRIX_REVIENT"));
119
        BigDecimal result = null;
120
 
121
        for (SQLRowAccessor row : l) {
122
 
123
            if (row.getLong("QTE") > qty) {
124
                break;
125
            }
126
            result = row.getBigDecimal("PRIX");
127
        }
128
        if (result == null) {
129
            // Can occur during editing
130
            result = BigDecimal.ZERO;
131
        }
132
        return result;
133
    }
134
 
135
    @SuppressWarnings("unchecked")
136
    public List<String> getRequiredProperties(int categoryId) {
137
        final SQLTable table = root.getTable("FAMILLE_CARACTERISTIQUE");
138
        final SQLSelect sel = new SQLSelect();
139
        sel.addSelect(table.getField("NOM"));
140
        sel.setWhere(table.getField("ID_FAMILLE_ARTICLE"), "=", categoryId);
141
        final SQLDataSource src = root.getDBSystemRoot().getDataSource();
142
        return (List<String>) src.executeCol(sel.asString());
143
    }
144
 
145
    /**
146
     * Get the minimum quantity used to provide a cost for a product
147
     *
148
     * @return -1 if no quantity are provided
132 ilm 149
     */
93 ilm 150
    public int getMinQuantityForCostCalculation(int productId) {
151
        final SQLTable costTable = root.getTable("ARTICLE_PRIX_REVIENT");
152
        final SQLSelect sel = new SQLSelect();
153
        sel.addSelect(costTable.getKey());
154
        sel.addSelect(costTable.getField("ID_ARTICLE"));
155
        sel.addSelect(costTable.getField("QTE"));
156
        sel.setWhere(new Where(costTable.getField("ID_ARTICLE"), "=", productId));
157
        final SQLDataSource src = root.getDBSystemRoot().getDataSource();
158
        final List<SQLRow> l = (List<SQLRow>) src.execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
159
        if (l.isEmpty()) {
160
            return -1;
161
        }
162
        int min = Integer.MAX_VALUE;
163
        for (SQLRow sqlRow : l) {
164
            int n = sqlRow.getInt("QTE");
165
            if (n < min) {
166
                min = n;
167
            }
168
        }
169
        return min;
170
    }
171
 
172
    /**
173
     * Get the cost for products and quantities
174
     *
175
     * @return for each product ID the unit cost
132 ilm 176
     */
93 ilm 177
    public Map<Long, BigDecimal> getUnitCost(Map<Long, Integer> productQties, TypePrice type) {
178
        final Map<Long, BigDecimal> result = new HashMap<Long, BigDecimal>();
132 ilm 179
 
142 ilm 180
        String fieldPrice = (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR || type == TypePrice.ARTICLE_TARIF_FOURNISSEUR_DDP ? "PRIX_ACHAT_DEVISE_F" : "PRIX");
181
        String fieldDate = (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR || type == TypePrice.ARTICLE_TARIF_FOURNISSEUR_DDP ? "DATE_PRIX" : "DATE");
132 ilm 182
 
93 ilm 183
        // get all costs
142 ilm 184
        final SQLTable costTable = root.getTable(type == TypePrice.ARTICLE_TARIF_FOURNISSEUR_DDP ? "ARTICLE_TARIF_FOURNISSEUR" : type.name());
93 ilm 185
        final SQLSelect sel = new SQLSelect();
186
        sel.addSelect(costTable.getKey());
187
        sel.addSelect(costTable.getField("ID_ARTICLE"));
188
        sel.addSelect(costTable.getField("QTE"));
132 ilm 189
        sel.addSelect(costTable.getField(fieldPrice));
142 ilm 190
        if (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR_DDP) {
191
            for (SupplierPriceField f : SupplierPriceField.values()) {
192
                sel.addSelect(costTable.getField(f.name()));
193
            }
194
        }
132 ilm 195
        sel.addSelect(costTable.getField(fieldDate));
93 ilm 196
        sel.setWhere(new Where(costTable.getField("ID_ARTICLE"), true, productQties.keySet()));
197
        sel.addFieldOrder(costTable.getField("QTE"));
132 ilm 198
        sel.addFieldOrder(costTable.getField(fieldDate));
93 ilm 199
        final SQLDataSource src = root.getDBSystemRoot().getDataSource();
200
        @SuppressWarnings("unchecked")
201
        final List<SQLRow> l = (List<SQLRow>) src.execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
202
        for (SQLRow sqlRow : l) {
203
            System.out.println(sqlRow.getID() + ":" + sqlRow.getAllValues());
204
        }
205
        final int size = l.size();
142 ilm 206
        if (size == 0 && type == TypePrice.ARTICLE_PRIX_REVIENT) {
207
            return getUnitCost(productQties, TypePrice.ARTICLE_TARIF_FOURNISSEUR_DDP);
208
        } else {
209
            for (Long id : productQties.keySet()) {
210
                BigDecimal cost = BigDecimal.ZERO;
211
                final int qty = productQties.get(id);
212
                for (int i = 0; i < size; i++) {
213
                    final SQLRow row = l.get(i);
214
                    if (row.getInt("ID_ARTICLE") == id.intValue()) {
215
                        // stop when the max qty is found
216
                        if (row.getLong("QTE") > qty) {
217
                            if (cost == null) {
218
                                if (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR_DDP) {
219
                                    cost = getEnumPrice(row, SupplierPriceField.COEF_TRANSPORT_SIEGE);
220
                                } else {
221
                                    cost = row.getBigDecimal(fieldPrice);
222
                                }
223
                            }
224
                            break;
225
                        }
226
                        if (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR_DDP) {
227
                            cost = getEnumPrice(row, SupplierPriceField.COEF_TRANSPORT_SIEGE);
228
                        } else {
132 ilm 229
                            cost = row.getBigDecimal(fieldPrice);
93 ilm 230
                        }
142 ilm 231
 
93 ilm 232
                    }
142 ilm 233
                }
234
                if (cost == null) {
235
                    cost = BigDecimal.ZERO;
236
                }
93 ilm 237
 
142 ilm 238
                result.put(id, cost);
93 ilm 239
            }
142 ilm 240
            return result;
93 ilm 241
        }
242
    }
243
 
244
    /**
245
     *
246
     * @param items List de SQLRowAccessor avec ID_ARTICLE, QTE, QTE_UV
247
     * @return Map article qty
248
     */
249
    public List<ProductComponent> getChildWithQtyFrom(final List<ProductComponent> items) {
250
 
251
        return getChildWithQtyFrom(items, new HashSet<Integer>());
252
    }
253
 
156 ilm 254
    private List<ProductComponent> getChildWithQtyFrom(List<ProductComponent> items, Set<Integer> ancestorsOrigin) {
93 ilm 255
 
256
        if (root.contains("ARTICLE_ELEMENT")) {
257
 
156 ilm 258
            int originalAncestorsSize = ancestorsOrigin.size();
259
            Set<Integer> ancestors = new HashSet<Integer>(ancestorsOrigin);
93 ilm 260
 
261
            List<ProductComponent> result = new ArrayList<ProductComponent>();
262
 
263
            // liste des ids parents
264
            final List<Integer> parentsArticleIDs = new ArrayList<Integer>();
265
 
156 ilm 266
            // ID Article -- component
267
            ListMap<Integer, ProductComponent> productCompByID = new ListMap<Integer, ProductComponent>();
268
 
93 ilm 269
            // Quantité par parents
156 ilm 270
            // final ListMap<Integer, BigDecimal> qtyParentIDSource = new HashMap<Integer,
271
            // BigDecimal>();
93 ilm 272
            for (ProductComponent p : items) {
156 ilm 273
                productCompByID.add(p.getProduct().getID(), p);
274
                int idSource = p.getProduct().getID();
275
                parentsArticleIDs.add(idSource);
276
                // BigDecimal qty = BigDecimal.ZERO;
277
                // if (qtyParent.get(idSource) != null) {
278
                // qty = qtyParent.get(idSource);
279
                // }
280
                // qtyParent.put(idSource, qty.add(p.getQty()));
93 ilm 281
            }
282
 
283
            // get all childs
284
            final SQLTable costTable = root.getTable("ARTICLE_ELEMENT");
285
 
286
            SQLRowValues rowVals = new SQLRowValues(costTable);
287
 
174 ilm 288
            final SQLRowValues artRowValues = rowVals.putRowValues("ID_ARTICLE").putNulls("ID", "GESTION_STOCK", "CODE", "NOM", "ID_DEPOT_STOCK", "ID_UNITE_VENTE", "ID_FOURNISSEUR");
156 ilm 289
            SQLRowValues stockRowVals = new SQLRowValues(root.getTable("STOCK"));
290
            stockRowVals.putNulls("QTE_TH", "QTE_RECEPT_ATTENTE", "QTE_REEL", "QTE_LIV_ATTENTE", "ID_DEPOT_STOCK");
291
            stockRowVals.put("ID_ARTICLE", artRowValues);
93 ilm 292
            rowVals.putRowValues("ID_ARTICLE_PARENT").put("ID", null);
293
            rowVals.put("QTE", null);
294
            rowVals.put("QTE_UNITAIRE", null);
295
 
296
            SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
297
            fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
298
 
299
                @Override
300
                public SQLSelect transformChecked(SQLSelect input) {
301
 
302
                    input.setWhere(new Where(costTable.getField("ID_ARTICLE_PARENT"), parentsArticleIDs));
303
                    return input;
304
                }
305
            });
306
 
307
            List<SQLRowValues> childs = fetcher.fetch();
308
 
309
            if (childs.size() > 0) {
310
 
311
                for (SQLRowValues childRowValues : childs) {
312
                    final SQLRowAccessor foreignArticleParent = childRowValues.getForeign("ID_ARTICLE_PARENT");
313
 
156 ilm 314
                    if (childRowValues.getObject("ID_ARTICLE") != null && !childRowValues.isForeignEmpty("ID_ARTICLE")) {
315
 
316
                        List<ProductComponent> source = productCompByID.get(foreignArticleParent.getID());
142 ilm 317
                        // Test pour éviter les boucles dans les boms
156 ilm 318
                        if (!ancestorsOrigin.contains(foreignArticleParent.getID())) {
142 ilm 319
                            ancestors.add(foreignArticleParent.getID());
156 ilm 320
                            for (ProductComponent productParent : source) {
142 ilm 321
 
156 ilm 322
                                final SQLRowAccessor foreignArticle = childRowValues.getForeign("ID_ARTICLE");
323
                                ProductComponent childComponent = ProductComponent.createFromRowArticle(foreignArticle, productParent.getSource());
324
 
325
                                // parentsArticleIDs.remove(foreignArticleParent.getID());
326
                                // Calcul de la quantité qte_unit * qte * qteMergedParent
327
                                childComponent.setQty(childComponent.getQty().multiply(productParent.getQty(), DecimalUtils.HIGH_PRECISION));
328
 
329
                                // Cumul des valeurs si l'article est présent plusieurs fois dans le
330
                                // bom
331
                                // ProductComponent existProduct =
332
                                // productCompByID.get(childComponent.getProduct().getID());
333
                                // if (existProduct == null) {
334
                                // Maintenant on garde une ligne disctincte pour chaque kit
142 ilm 335
                                result.add(childComponent);
156 ilm 336
                                // productCompByID.put(childComponent.getProduct().getID(),
337
                                // childComponent);
338
                                // } else {
339
                                // existProduct.addQty(childComponent.getQty());
340
                                // }
142 ilm 341
                            }
93 ilm 342
                        }
343
                    }
344
                }
345
 
346
                // Recherche si un kit est présent parmis les articles
347
                final List<ProductComponent> bomFromChilds = getChildWithQtyFrom(new ArrayList(result), ancestors);
348
                // Merge des valeurs
349
                for (ProductComponent s : bomFromChilds) {
350
 
156 ilm 351
                    // ProductComponent existProduct = productCompByID.get(s.getProduct().getID());
352
                    // if (existProduct == null) {
353
                    result.add(s);
354
                    // productCompByID.put(s.getProduct().getID(), s);
355
                    // } else {
356
                    // existProduct.addQty(s.getQty());
357
                    // }
93 ilm 358
                }
359
            }
360
 
361
            // Ajout des articles présents dans l'ensemble de départ
362
            if (originalAncestorsSize == 0) {
363
                for (ProductComponent p : items) {
156 ilm 364
                    // ProductComponent existProduct = productCompByID.get(p.getProduct().getID());
365
                    // if (existProduct == null) {
366
                    result.add(p);
367
                    // productCompByID.put(p.getProduct().getID(), p);
368
                    // } else {
369
                    // existProduct.addQty(p.getQty());
370
                    // }
93 ilm 371
                }
372
            }
373
 
374
            // On supprime les ancestors (kits) du result
375
            for (Integer anc : ancestors) {
156 ilm 376
                // ProductComponent comp = productCompByID.get(anc);
377
                if (productCompByID.containsKey(anc)) {
378
                    result.removeAll(productCompByID.get(anc));
93 ilm 379
                }
380
            }
381
 
382
            return result;
383
        } else {
384
            return items;
385
        }
386
    }
387
 
388
    public Map<Long, Integer> getBOM(Long productId) {
389
        final Map<Long, Integer> result = new HashMap<Long, Integer>();
390
        // get all costs
391
        final SQLTable costTable = root.getTable("ARTICLE_ELEMENT");
392
        final SQLSelect sel = new SQLSelect();
393
 
394
        sel.addSelect(costTable.getField("ID_ARTICLE"));
395
        sel.addSelect(costTable.getField("QTE"));
396
 
397
        sel.setWhere(new Where(costTable.getField("ID_ARTICLE_PARENT"), "=", productId));
398
        sel.addFieldOrder(costTable.getField("QTE"));
399
        final SQLDataSource src = root.getDBSystemRoot().getDataSource();
400
        @SuppressWarnings("unchecked")
401
        final List<SQLRow> l = (List<SQLRow>) src.execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
402
        final int size = l.size();
403
        for (int i = 0; i < size; i++) {
404
            final SQLRow row = l.get(i);
405
            final long id = row.getLong("ID_ARTICLE");
406
            Integer qte = result.get(id);
407
            if (qte == null) {
408
                qte = row.getInt("QTE");
409
            } else {
410
                qte = qte + row.getInt("QTE");
411
            }
412
            result.put(id, qte);
413
        }
414
 
415
        return result;
416
    }
417
 
418
    public enum TypePrice {
142 ilm 419
        ARTICLE_PRIX_REVIENT, ARTICLE_PRIX_MIN_VENTE, ARTICLE_PRIX_PUBLIC, ARTICLE_TARIF_FOURNISSEUR, ARTICLE_TARIF_FOURNISSEUR_DDP
93 ilm 420
    };
421
 
422
    public BigDecimal getBomPriceForQuantity(int qty, Collection<? extends SQLRowAccessor> rowValuesProductItems, TypePrice type) {
423
        final Map<Long, Integer> productQties = new HashMap<Long, Integer>();
424
        int count = rowValuesProductItems.size();
425
        for (SQLRowAccessor v : rowValuesProductItems) {
426
            if (v.getObject("ID_ARTICLE") != null) {
427
                System.out.println("id:" + v.getObject("ID_ARTICLE"));
428
                int id = v.getForeignID("ID_ARTICLE");
429
                int qte = v.getInt("QTE") * qty;
430
                Integer qteForId = productQties.get(Long.valueOf(id));
431
                if (qteForId == null) {
432
                    productQties.put(Long.valueOf(id), qte);
433
                } else {
434
                    productQties.put(Long.valueOf(id), qte + qteForId);
435
                }
436
            }
437
        }
438
        Map<Long, BigDecimal> costs = getUnitCost(productQties, type);
439
        BigDecimal cost = null;
440
        for (SQLRowAccessor v : rowValuesProductItems) {
441
            if (v.getObject("ID_ARTICLE") != null) {
442
                int id = v.getForeignID("ID_ARTICLE");
443
                int qte = v.getInt("QTE");
444
                final BigDecimal unitCost = costs.get(Long.valueOf(id));
94 ilm 445
                BigDecimal lineCost = unitCost.multiply(BigDecimal.valueOf(qte)).multiply(v.getBigDecimal("QTE_UNITAIRE"));
93 ilm 446
                if (cost == null) {
447
                    cost = BigDecimal.ZERO;
448
                }
449
                cost = cost.add(lineCost);
450
            }
451
        }
452
        return cost;
453
 
454
    }
455
 
177 ilm 456
    public Tuple2<BigDecimal, BigDecimal> getStandardBomPrices(Collection<? extends SQLRowAccessor> rowValuesProductItems) {
457
        final Map<Long, Integer> productQties = new HashMap<Long, Integer>();
458
        for (SQLRowAccessor v : rowValuesProductItems) {
459
            if (v.getObject("ID_ARTICLE") != null) {
460
                System.out.println("id:" + v.getObject("ID_ARTICLE"));
461
                int id = v.getForeignID("ID_ARTICLE");
462
                int qte = v.getInt("QTE");
463
                Integer qteForId = productQties.get(Long.valueOf(id));
464
                if (qteForId == null) {
465
                    productQties.put(Long.valueOf(id), qte);
466
                } else {
467
                    productQties.put(Long.valueOf(id), qte + qteForId);
468
                }
469
            }
470
        }
471
        BigDecimal costPV = null;
472
        BigDecimal costPA = null;
473
 
474
        for (SQLRowAccessor v : rowValuesProductItems) {
475
            if (v.getObject("ID_ARTICLE") != null) {
476
                SQLRowAccessor rowChild = v.getForeign("ID_ARTICLE");
477
                int qte = v.getInt("QTE");
478
                BigDecimal unitCostPV = rowChild.getBigDecimal("PV_HT");
479
                BigDecimal unitCostPA = rowChild.getBigDecimal("PA_HT");
480
                BigDecimal lineCostPV = unitCostPV.multiply(BigDecimal.valueOf(qte)).multiply(v.getBigDecimal("QTE_UNITAIRE"));
481
                if (costPV == null) {
482
                    costPV = BigDecimal.ZERO;
483
                }
484
                costPV = costPV.add(lineCostPV);
485
                BigDecimal lineCostPA = unitCostPA.multiply(BigDecimal.valueOf(qte)).multiply(v.getBigDecimal("QTE_UNITAIRE"));
486
                if (costPA == null) {
487
                    costPA = BigDecimal.ZERO;
488
                }
489
                costPA = costPA.add(lineCostPA);
490
            }
491
        }
492
        return Tuple2.create(costPA, costPV);
493
 
494
    }
495
 
93 ilm 496
    public BigDecimal getUnitCost(int id, int qty, TypePrice type) {
497
        Map<Long, Integer> productQties = new HashMap<Long, Integer>();
498
        productQties.put(Long.valueOf(id), Integer.valueOf(qty));
499
        final Map<Long, BigDecimal> unitCost = getUnitCost(productQties, type);
500
        System.out.println(">" + unitCost);
501
        return unitCost.get(Long.valueOf(id));
502
    }
503
 
504
    public Date getUnitCostDate(int id, int qty, TypePrice type) {
505
        Map<Long, Integer> productQties = new HashMap<Long, Integer>();
506
        productQties.put(Long.valueOf(id), Integer.valueOf(qty));
507
        final Map<Long, Date> unitCost = getUnitCostDate(productQties, type);
508
        System.out.println(">" + unitCost);
509
        return unitCost.get(Long.valueOf(id));
510
    }
511
 
512
    private Map<Long, Date> getUnitCostDate(Map<Long, Integer> productQties, TypePrice type) {
513
        final Map<Long, Date> result = new HashMap<Long, Date>();
132 ilm 514
 
515
        String fieldPrice = (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR ? "PRIX_ACHAT_DEVISE_F" : "PRIX");
516
        String fieldDate = (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR ? "DATE_PRIX" : "DATE");
517
 
93 ilm 518
        // get all costs
519
        final SQLTable costTable = root.getTable(type.name());
520
        final SQLSelect sel = new SQLSelect();
521
        sel.addSelect(costTable.getKey());
522
        sel.addSelect(costTable.getField("ID_ARTICLE"));
523
        sel.addSelect(costTable.getField("QTE"));
132 ilm 524
        sel.addSelect(costTable.getField(fieldPrice));
525
        sel.addSelect(costTable.getField(fieldDate));
93 ilm 526
        sel.setWhere(new Where(costTable.getField("ID_ARTICLE"), true, productQties.keySet()));
527
        sel.addFieldOrder(costTable.getField("QTE"));
132 ilm 528
        sel.addFieldOrder(costTable.getField(fieldDate));
93 ilm 529
        final SQLDataSource src = root.getDBSystemRoot().getDataSource();
530
        @SuppressWarnings("unchecked")
531
        final List<SQLRow> l = (List<SQLRow>) src.execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
532
        for (SQLRow sqlRow : l) {
533
            System.out.println(sqlRow.getID() + ":" + sqlRow.getAllValues());
534
        }
535
        final int size = l.size();
536
        for (Long id : productQties.keySet()) {
537
            Calendar cost = null;
538
            final int qty = productQties.get(id);
539
            for (int i = 0; i < size; i++) {
540
                final SQLRow row = l.get(i);
541
                if (row.getInt("ID_ARTICLE") == id.intValue()) {
542
                    // stop when the max qty is found
543
                    if (row.getLong("QTE") > qty) {
544
                        if (cost == null) {
545
                            cost = row.getDate("DATE");
546
                        }
547
                        break;
548
                    }
549
                    cost = row.getDate("DATE");
550
 
551
                }
552
            }
553
            if (cost != null)
554
                result.put(id, cost.getTime());
555
            else
556
                result.put(id, new Date());
557
        }
558
        return result;
559
    }
560
}