OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | 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");
180 ilm 323
                                int childQ = childRowValues.getInt("QTE");
324
                                BigDecimal childqD = childRowValues.getBigDecimal("QTE_UNITAIRE");
325
                                ProductComponent childComponent = ProductComponent.createFromRowArticle(foreignArticle, childqD.multiply(new BigDecimal(childQ)), productParent.getSource());
156 ilm 326
 
327
                                // parentsArticleIDs.remove(foreignArticleParent.getID());
328
                                // Calcul de la quantité qte_unit * qte * qteMergedParent
329
                                childComponent.setQty(childComponent.getQty().multiply(productParent.getQty(), DecimalUtils.HIGH_PRECISION));
330
 
331
                                // Cumul des valeurs si l'article est présent plusieurs fois dans le
332
                                // bom
333
                                // ProductComponent existProduct =
334
                                // productCompByID.get(childComponent.getProduct().getID());
335
                                // if (existProduct == null) {
336
                                // Maintenant on garde une ligne disctincte pour chaque kit
142 ilm 337
                                result.add(childComponent);
156 ilm 338
                                // productCompByID.put(childComponent.getProduct().getID(),
339
                                // childComponent);
340
                                // } else {
341
                                // existProduct.addQty(childComponent.getQty());
342
                                // }
142 ilm 343
                            }
93 ilm 344
                        }
345
                    }
346
                }
347
 
348
                // Recherche si un kit est présent parmis les articles
349
                final List<ProductComponent> bomFromChilds = getChildWithQtyFrom(new ArrayList(result), ancestors);
350
                // Merge des valeurs
351
                for (ProductComponent s : bomFromChilds) {
352
 
156 ilm 353
                    // ProductComponent existProduct = productCompByID.get(s.getProduct().getID());
354
                    // if (existProduct == null) {
355
                    result.add(s);
356
                    // productCompByID.put(s.getProduct().getID(), s);
357
                    // } else {
358
                    // existProduct.addQty(s.getQty());
359
                    // }
93 ilm 360
                }
361
            }
362
 
363
            // Ajout des articles présents dans l'ensemble de départ
364
            if (originalAncestorsSize == 0) {
365
                for (ProductComponent p : items) {
156 ilm 366
                    // ProductComponent existProduct = productCompByID.get(p.getProduct().getID());
367
                    // if (existProduct == null) {
368
                    result.add(p);
369
                    // productCompByID.put(p.getProduct().getID(), p);
370
                    // } else {
371
                    // existProduct.addQty(p.getQty());
372
                    // }
93 ilm 373
                }
374
            }
375
 
376
            // On supprime les ancestors (kits) du result
377
            for (Integer anc : ancestors) {
156 ilm 378
                // ProductComponent comp = productCompByID.get(anc);
379
                if (productCompByID.containsKey(anc)) {
380
                    result.removeAll(productCompByID.get(anc));
93 ilm 381
                }
382
            }
383
 
384
            return result;
385
        } else {
386
            return items;
387
        }
388
    }
389
 
390
    public Map<Long, Integer> getBOM(Long productId) {
391
        final Map<Long, Integer> result = new HashMap<Long, Integer>();
392
        // get all costs
393
        final SQLTable costTable = root.getTable("ARTICLE_ELEMENT");
394
        final SQLSelect sel = new SQLSelect();
395
 
396
        sel.addSelect(costTable.getField("ID_ARTICLE"));
397
        sel.addSelect(costTable.getField("QTE"));
398
 
399
        sel.setWhere(new Where(costTable.getField("ID_ARTICLE_PARENT"), "=", productId));
400
        sel.addFieldOrder(costTable.getField("QTE"));
401
        final SQLDataSource src = root.getDBSystemRoot().getDataSource();
402
        @SuppressWarnings("unchecked")
403
        final List<SQLRow> l = (List<SQLRow>) src.execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
404
        final int size = l.size();
405
        for (int i = 0; i < size; i++) {
406
            final SQLRow row = l.get(i);
407
            final long id = row.getLong("ID_ARTICLE");
408
            Integer qte = result.get(id);
409
            if (qte == null) {
410
                qte = row.getInt("QTE");
411
            } else {
412
                qte = qte + row.getInt("QTE");
413
            }
414
            result.put(id, qte);
415
        }
416
 
417
        return result;
418
    }
419
 
420
    public enum TypePrice {
142 ilm 421
        ARTICLE_PRIX_REVIENT, ARTICLE_PRIX_MIN_VENTE, ARTICLE_PRIX_PUBLIC, ARTICLE_TARIF_FOURNISSEUR, ARTICLE_TARIF_FOURNISSEUR_DDP
93 ilm 422
    };
423
 
424
    public BigDecimal getBomPriceForQuantity(int qty, Collection<? extends SQLRowAccessor> rowValuesProductItems, TypePrice type) {
425
        final Map<Long, Integer> productQties = new HashMap<Long, Integer>();
426
        int count = rowValuesProductItems.size();
427
        for (SQLRowAccessor v : rowValuesProductItems) {
428
            if (v.getObject("ID_ARTICLE") != null) {
429
                System.out.println("id:" + v.getObject("ID_ARTICLE"));
430
                int id = v.getForeignID("ID_ARTICLE");
431
                int qte = v.getInt("QTE") * qty;
432
                Integer qteForId = productQties.get(Long.valueOf(id));
433
                if (qteForId == null) {
434
                    productQties.put(Long.valueOf(id), qte);
435
                } else {
436
                    productQties.put(Long.valueOf(id), qte + qteForId);
437
                }
438
            }
439
        }
440
        Map<Long, BigDecimal> costs = getUnitCost(productQties, type);
441
        BigDecimal cost = null;
442
        for (SQLRowAccessor v : rowValuesProductItems) {
443
            if (v.getObject("ID_ARTICLE") != null) {
444
                int id = v.getForeignID("ID_ARTICLE");
445
                int qte = v.getInt("QTE");
446
                final BigDecimal unitCost = costs.get(Long.valueOf(id));
94 ilm 447
                BigDecimal lineCost = unitCost.multiply(BigDecimal.valueOf(qte)).multiply(v.getBigDecimal("QTE_UNITAIRE"));
93 ilm 448
                if (cost == null) {
449
                    cost = BigDecimal.ZERO;
450
                }
451
                cost = cost.add(lineCost);
452
            }
453
        }
454
        return cost;
455
 
456
    }
457
 
177 ilm 458
    public Tuple2<BigDecimal, BigDecimal> getStandardBomPrices(Collection<? extends SQLRowAccessor> rowValuesProductItems) {
459
        final Map<Long, Integer> productQties = new HashMap<Long, Integer>();
460
        for (SQLRowAccessor v : rowValuesProductItems) {
461
            if (v.getObject("ID_ARTICLE") != null) {
462
                System.out.println("id:" + v.getObject("ID_ARTICLE"));
463
                int id = v.getForeignID("ID_ARTICLE");
464
                int qte = v.getInt("QTE");
465
                Integer qteForId = productQties.get(Long.valueOf(id));
466
                if (qteForId == null) {
467
                    productQties.put(Long.valueOf(id), qte);
468
                } else {
469
                    productQties.put(Long.valueOf(id), qte + qteForId);
470
                }
471
            }
472
        }
473
        BigDecimal costPV = null;
474
        BigDecimal costPA = null;
475
 
476
        for (SQLRowAccessor v : rowValuesProductItems) {
477
            if (v.getObject("ID_ARTICLE") != null) {
478
                SQLRowAccessor rowChild = v.getForeign("ID_ARTICLE");
479
                int qte = v.getInt("QTE");
480
                BigDecimal unitCostPV = rowChild.getBigDecimal("PV_HT");
481
                BigDecimal unitCostPA = rowChild.getBigDecimal("PA_HT");
482
                BigDecimal lineCostPV = unitCostPV.multiply(BigDecimal.valueOf(qte)).multiply(v.getBigDecimal("QTE_UNITAIRE"));
483
                if (costPV == null) {
484
                    costPV = BigDecimal.ZERO;
485
                }
486
                costPV = costPV.add(lineCostPV);
487
                BigDecimal lineCostPA = unitCostPA.multiply(BigDecimal.valueOf(qte)).multiply(v.getBigDecimal("QTE_UNITAIRE"));
488
                if (costPA == null) {
489
                    costPA = BigDecimal.ZERO;
490
                }
491
                costPA = costPA.add(lineCostPA);
492
            }
493
        }
494
        return Tuple2.create(costPA, costPV);
495
 
496
    }
497
 
93 ilm 498
    public BigDecimal getUnitCost(int id, int qty, TypePrice type) {
499
        Map<Long, Integer> productQties = new HashMap<Long, Integer>();
500
        productQties.put(Long.valueOf(id), Integer.valueOf(qty));
501
        final Map<Long, BigDecimal> unitCost = getUnitCost(productQties, type);
502
        System.out.println(">" + unitCost);
503
        return unitCost.get(Long.valueOf(id));
504
    }
505
 
506
    public Date getUnitCostDate(int id, int qty, TypePrice type) {
507
        Map<Long, Integer> productQties = new HashMap<Long, Integer>();
508
        productQties.put(Long.valueOf(id), Integer.valueOf(qty));
509
        final Map<Long, Date> unitCost = getUnitCostDate(productQties, type);
510
        System.out.println(">" + unitCost);
511
        return unitCost.get(Long.valueOf(id));
512
    }
513
 
514
    private Map<Long, Date> getUnitCostDate(Map<Long, Integer> productQties, TypePrice type) {
515
        final Map<Long, Date> result = new HashMap<Long, Date>();
132 ilm 516
 
517
        String fieldPrice = (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR ? "PRIX_ACHAT_DEVISE_F" : "PRIX");
518
        String fieldDate = (type == TypePrice.ARTICLE_TARIF_FOURNISSEUR ? "DATE_PRIX" : "DATE");
519
 
93 ilm 520
        // get all costs
521
        final SQLTable costTable = root.getTable(type.name());
522
        final SQLSelect sel = new SQLSelect();
523
        sel.addSelect(costTable.getKey());
524
        sel.addSelect(costTable.getField("ID_ARTICLE"));
525
        sel.addSelect(costTable.getField("QTE"));
132 ilm 526
        sel.addSelect(costTable.getField(fieldPrice));
527
        sel.addSelect(costTable.getField(fieldDate));
93 ilm 528
        sel.setWhere(new Where(costTable.getField("ID_ARTICLE"), true, productQties.keySet()));
529
        sel.addFieldOrder(costTable.getField("QTE"));
132 ilm 530
        sel.addFieldOrder(costTable.getField(fieldDate));
93 ilm 531
        final SQLDataSource src = root.getDBSystemRoot().getDataSource();
532
        @SuppressWarnings("unchecked")
533
        final List<SQLRow> l = (List<SQLRow>) src.execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
534
        for (SQLRow sqlRow : l) {
535
            System.out.println(sqlRow.getID() + ":" + sqlRow.getAllValues());
536
        }
537
        final int size = l.size();
538
        for (Long id : productQties.keySet()) {
539
            Calendar cost = null;
540
            final int qty = productQties.get(id);
541
            for (int i = 0; i < size; i++) {
542
                final SQLRow row = l.get(i);
543
                if (row.getInt("ID_ARTICLE") == id.intValue()) {
544
                    // stop when the max qty is found
545
                    if (row.getLong("QTE") > qty) {
546
                        if (cost == null) {
547
                            cost = row.getDate("DATE");
548
                        }
549
                        break;
550
                    }
551
                    cost = row.getDate("DATE");
552
 
553
                }
554
            }
555
            if (cost != null)
556
                result.put(id, cost.getTime());
557
            else
558
                result.put(id, new Date());
559
        }
560
        return result;
561
    }
562
}