OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

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