dolibarr  16.0.5
replenish.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
3  * Copyright (C) 2013-2018 Laurent Destaileur <ely@users.sourceforge.net>
4  * Copyright (C) 2014 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
6  * Copyright (C) 2016 ATM Consulting <support@atm-consulting.fr>
7  * Copyright (C) 2019 Frédéric France <frederic.france@netlogic.fr>
8  * Copyright (C) 2021 Ferran Marcet <fmarcet@2byte.es>
9  * Copyright (C) 2021 Antonin MARCHAL <antonin@letempledujeu.fr>
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <https://www.gnu.org/licenses/>.
23  */
24 
31 require '../../main.inc.php';
32 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
33 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
34 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
35 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
37 require_once './lib/replenishment.lib.php';
38 
39 // Load translation files required by the page
40 $langs->loadLangs(array('products', 'stocks', 'orders'));
41 
42 // Security check
43 if ($user->socid) {
44  $socid = $user->socid;
45 }
46 $result = restrictedArea($user, 'produit|service');
47 
48 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
49 $hookmanager->initHooks(array('stockreplenishlist'));
50 
51 //checks if a product has been ordered
52 
53 $action = GETPOST('action', 'aZ09');
54 $search_ref = GETPOST('search_ref', 'alpha');
55 $search_label = GETPOST('search_label', 'alpha');
56 $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
57 $type = GETPOST('type', 'int');
58 $tobuy = GETPOST('tobuy', 'int');
59 $salert = GETPOST('salert', 'alpha');
60 $includeproductswithoutdesiredqty = GETPOST('includeproductswithoutdesiredqty', 'alpha');
61 $mode = GETPOST('mode', 'alpha');
62 $draftorder = GETPOST('draftorder', 'alpha');
63 
64 
65 $fourn_id = GETPOST('fourn_id', 'int');
66 $fk_supplier = GETPOST('fk_supplier', 'int');
67 $fk_entrepot = GETPOST('fk_entrepot', 'int');
68 
69 // List all visible warehouses
70 $resWar = $db->query("SELECT rowid FROM " . MAIN_DB_PREFIX . "entrepot WHERE entity IN (" . $db->sanitize(getEntity('stock')) .")");
71 $listofqualifiedwarehousesid = "";
72 $count = 0;
73 while ($tmpobj = $db->fetch_object($resWar)) {
74  if (!empty($listofqualifiedwarehousesid)) {
75  $listofqualifiedwarehousesid .= ",";
76  }
77  $listofqualifiedwarehousesid .= $tmpobj->rowid;
78  $lastWarehouseID = $tmpobj->rowid;
79  $count++;
80 };
81 
82 //MultiCompany : If only 1 Warehouse is visible, filter will automatically be set to it.
83 if ($count == 1 && (empty($fk_entrepot) || $fk_entrepot <= 0) && !empty($conf->global->MULTICOMPANY_PRODUCT_SHARING_ENABLED)) {
84  $fk_entrepot = $lastWarehouseID;
85 };
86 
87 $texte = '';
88 
89 $sortfield = GETPOST('sortfield', 'aZ09comma');
90 $sortorder = GETPOST('sortorder', 'aZ09comma');
91 $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
92 if (empty($page) || $page == -1) {
93  $page = 0;
94 } // If $page is not defined, or '' or -1
95 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
96 $offset = $limit * $page;
97 
98 if (!$sortfield) {
99  $sortfield = 'p.ref';
100 }
101 
102 if (!$sortorder) {
103  $sortorder = 'ASC';
104 }
105 
106 // Define virtualdiffersfromphysical
107 $virtualdiffersfromphysical = 0;
108 if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)
109  || !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)
110  || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)
111  || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)
112  || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)
113  || !empty($conf->mrp->enabled)) {
114  $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs.
115 }
116 
117 if ($virtualdiffersfromphysical) {
118  $usevirtualstock = empty($conf->global->STOCK_USE_REAL_STOCK_BY_DEFAULT_FOR_REPLENISHMENT) ? 1 : 0;
119 } else {
120  $usevirtualstock = 0;
121 }
122 if ($mode == 'physical') {
123  $usevirtualstock = 0;
124 }
125 if ($mode == 'virtual') {
126  $usevirtualstock = 1;
127 }
128 
129 $parameters = array();
130 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
131 if ($reshook < 0) {
132  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
133 }
134 
135 
136 /*
137  * Actions
138  */
139 
140 if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers
141  $search_ref = '';
142  $search_label = '';
143  $sall = '';
144  $salert = '';
145  $includeproductswithoutdesiredqty = '';
146  $draftorder = '';
147 }
148 if ($draftorder == 'on') {
149  $draftchecked = "checked";
150 }
151 
152 // Create orders
153 if ($action == 'order' && GETPOST('valid')) {
154  $linecount = GETPOST('linecount', 'int');
155  $box = 0;
156  $errorQty = 0;
157  unset($_POST['linecount']);
158  if ($linecount > 0) {
159  $db->begin();
160 
161  $suppliers = array();
162  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
163  $productsupplier = new ProductFournisseur($db);
164  for ($i = 0; $i < $linecount; $i++) {
165  if (GETPOST('choose'.$i, 'alpha') === 'on' && GETPOST('fourn'.$i, 'int') > 0) {
166  //one line
167  $box = $i;
168  $supplierpriceid = GETPOST('fourn'.$i, 'int');
169  //get all the parameters needed to create a line
170  $qty = GETPOST('tobuy'.$i, 'int');
171  $idprod = $productsupplier->get_buyprice($supplierpriceid, $qty);
172  $res = $productsupplier->fetch($idprod);
173  if ($res && $idprod > 0) {
174  if ($qty) {
175  //might need some value checks
176  $line = new CommandeFournisseurLigne($db);
177  $line->qty = $qty;
178  $line->fk_product = $idprod;
179 
180  //$product = new Product($db);
181  //$product->fetch($obj->fk_product);
182  if (!empty($conf->global->MAIN_MULTILANGS)) {
183  $productsupplier->getMultiLangs();
184  }
185 
186  // if we use supplier description of the products
187  if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
188  $desc = $productsupplier->desc_supplier;
189  } else {
190  $desc = $productsupplier->description;
191  }
192  $line->desc = $desc;
193  if (!empty($conf->global->MAIN_MULTILANGS)) {
194  // TODO Get desc in language of thirdparty
195  }
196 
197  $line->tva_tx = $productsupplier->vatrate_supplier;
198  $line->subprice = $productsupplier->fourn_pu;
199  $line->total_ht = $productsupplier->fourn_pu * $qty;
200  $tva = $line->tva_tx / 100;
201  $line->total_tva = $line->total_ht * $tva;
202  $line->total_ttc = $line->total_ht + $line->total_tva;
203  $line->remise_percent = $productsupplier->remise_percent;
204  $line->ref_fourn = $productsupplier->ref_supplier;
205  $line->type = $productsupplier->type;
206  $line->fk_unit = $productsupplier->fk_unit;
207  $suppliers[$productsupplier->fourn_socid]['lines'][] = $line;
208  }
209  } elseif ($idprod == -1) {
210  $errorQty++;
211  } else {
212  $error = $db->lasterror();
213  dol_print_error($db);
214  }
215 
216  unset($_POST['fourn'.$i]);
217  }
218  unset($_POST[$i]);
219  }
220 
221  //we now know how many orders we need and what lines they have
222  $i = 0;
223  $fail = 0;
224  $orders = array();
225  $suppliersid = array_keys($suppliers);
226  foreach ($suppliers as $supplier) {
227  $order = new CommandeFournisseur($db);
228 
229  // Check if an order for the supplier exists
230  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur";
231  $sql .= " WHERE fk_soc = ".((int) $suppliersid[$i]);
232  $sql .= " AND source = ".((int) $order::SOURCE_ID_REPLENISHMENT)." AND fk_statut = ".((int) $order::STATUS_DRAFT);
233  $sql .= " AND entity IN (".getEntity('commande_fournisseur').")";
234  $sql .= " ORDER BY date_creation DESC";
235  $resql = $db->query($sql);
236  if ($resql && $db->num_rows($resql) > 0) {
237  $obj = $db->fetch_object($resql);
238 
239  $order->fetch($obj->rowid);
240  $order->fetch_thirdparty();
241 
242  foreach ($supplier['lines'] as $line) {
243  if (empty($line->remise_percent)) {
244  $line->remise_percent = $order->thirdparty->remise_supplier_percent;
245  }
246  $result = $order->addline(
247  $line->desc,
248  $line->subprice,
249  $line->qty,
250  $line->tva_tx,
251  $line->localtax1_tx,
252  $line->localtax2_tx,
253  $line->fk_product,
254  0,
255  $line->ref_fourn,
256  $line->remise_percent,
257  'HT',
258  0,
259  $line->type,
260  0,
261  false,
262  null,
263  null,
264  0,
265  $line->fk_unit
266  );
267  }
268  if ($result < 0) {
269  $fail++;
270  $msg = $langs->trans('OrderFail')."&nbsp;:&nbsp;";
271  $msg .= $order->error;
272  setEventMessages($msg, null, 'errors');
273  } else {
274  $id = $result;
275  }
276  } else {
277  $order->socid = $suppliersid[$i];
278  $order->fetch_thirdparty();
279 
280  // Trick to know which orders have been generated using the replenishment feature
281  $order->source = $order::SOURCE_ID_REPLENISHMENT;
282 
283  foreach ($supplier['lines'] as $line) {
284  if (empty($line->remise_percent)) {
285  $line->remise_percent = $order->thirdparty->remise_supplier_percent;
286  }
287  $order->lines[] = $line;
288  }
289  $order->cond_reglement_id = $order->thirdparty->cond_reglement_supplier_id;
290  $order->mode_reglement_id = $order->thirdparty->mode_reglement_supplier_id;
291 
292  $id = $order->create($user);
293  if ($id < 0) {
294  $fail++;
295  $msg = $langs->trans('OrderFail')."&nbsp;:&nbsp;";
296  $msg .= $order->error;
297  setEventMessages($msg, null, 'errors');
298  }
299  $i++;
300  }
301  }
302 
303  if ($errorQty) {
304  setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings');
305  }
306 
307  if (!$fail && $id) {
308  $db->commit();
309 
310  setEventMessages($langs->trans('OrderCreated'), null, 'mesgs');
311  header('Location: replenishorders.php');
312  exit;
313  } else {
314  $db->rollback();
315  }
316  }
317  if ($box == 0) {
318  setEventMessages($langs->trans('SelectProductWithNotNullQty'), null, 'warnings');
319  }
320 }
321 
322 
323 /*
324  * View
325  */
326 
327 $form = new Form($db);
328 $formproduct = new FormProduct($db);
329 $prod = new Product($db);
330 
331 $title = $langs->trans('MissingStocks');
332 
333 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
334  $sqldesiredtock = $db->ifsql("pse.desiredstock IS NULL", "p.desiredstock", "pse.desiredstock");
335  $sqlalertstock = $db->ifsql("pse.seuil_stock_alerte IS NULL", "p.seuil_stock_alerte", "pse.seuil_stock_alerte");
336 } else {
337  $sqldesiredtock = 'p.desiredstock';
338  $sqlalertstock = 'p.seuil_stock_alerte';
339 }
340 
341 $sql = 'SELECT p.rowid, p.ref, p.label, p.description, p.price,';
342 $sql .= ' p.price_ttc, p.price_base_type, p.fk_product_type,';
343 $sql .= ' p.tms as datem, p.duration, p.tobuy,';
344 $sql .= ' p.desiredstock, p.seuil_stock_alerte,';
345 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
346  $sql .= ' pse.desiredstock as desiredstockpse, pse.seuil_stock_alerte as seuil_stock_alertepse,';
347 }
348 $sql .= " ".$sqldesiredtock." as desiredstockcombined, ".$sqlalertstock." as seuil_stock_alertecombined,";
349 $sql .= ' s.fk_product,';
350 $sql .= " SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").') as stock_physique';
351 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
352  $sql .= ", SUM(".$db->ifsql("s.reel IS NULL OR s.fk_entrepot <> ".$fk_entrepot, "0", "s.reel").') as stock_real_warehouse';
353 }
354 
355 // Add fields from hooks
356 $parameters = array();
357 $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
358 $sql .= $hookmanager->resPrint;
359 
360 $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
361 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s ON p.rowid = s.fk_product';
362 $list_warehouse = (empty($listofqualifiedwarehousesid) ? '0' : $listofqualifiedwarehousesid);
363 $sql .= ' AND s.fk_entrepot IN ('.$db->sanitize($list_warehouse) .')';
364 
365 //$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot AS ent ON s.fk_entrepot = ent.rowid AND ent.entity IN('.getEntity('stock').')';
366 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
367  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_warehouse_properties AS pse ON (p.rowid = pse.fk_product AND pse.fk_entrepot = '.((int) $fk_entrepot).')';
368 }
369 // Add fields from hooks
370 $parameters = array();
371 $reshook = $hookmanager->executeHooks('printFieldListJoin', $parameters); // Note that $action and $object may have been modified by hook
372 $sql .= $hookmanager->resPrint;
373 
374 $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
375 if ($sall) {
376  $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall);
377 }
378 // if the type is not 1, we show all products (type = 0,2,3)
379 if (dol_strlen($type)) {
380  if ($type == 1) {
381  $sql .= ' AND p.fk_product_type = 1';
382  } else {
383  $sql .= ' AND p.fk_product_type <> 1';
384  }
385 }
386 if ($search_ref) {
387  $sql .= natural_search('p.ref', $search_ref);
388 }
389 if ($search_label) {
390  $sql .= natural_search('p.label', $search_label);
391 }
392 $sql .= ' AND p.tobuy = 1';
393 if (!empty($conf->variants->eabled) && empty($conf->global->VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT)) { // Add test to exclude products that has variants
394  $sql .= ' AND p.rowid NOT IN (SELECT pac.fk_product_parent FROM '.MAIN_DB_PREFIX.'product_attribute_combination as pac WHERE pac.entity IN ('.getEntity('product').'))';
395 }
396 if ($fk_supplier > 0) {
397  $sql .= ' AND EXISTS (SELECT pfp.rowid FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp WHERE pfp.fk_product = p.rowid AND pfp.fk_soc = '.((int) $fk_supplier).' AND pfp.entity IN ('.getEntity('product_fournisseur_price').'))';
398 }
399 // Add where from hooks
400 $parameters = array();
401 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
402 $sql .= $hookmanager->resPrint;
403 
404 $sql .= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price';
405 $sql .= ', p.price_ttc, p.price_base_type,p.fk_product_type, p.tms';
406 $sql .= ', p.duration, p.tobuy';
407 $sql .= ', p.desiredstock';
408 $sql .= ', p.seuil_stock_alerte';
409 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
410  $sql .= ', pse.desiredstock';
411  $sql .= ', pse.seuil_stock_alerte';
412 }
413 $sql .= ', s.fk_product';
414 
415 if ($usevirtualstock) {
416  if (!empty($conf->commande->enabled)) {
417  $sqlCommandesCli = "(SELECT ".$db->ifsql("SUM(cd1.qty) IS NULL", "0", "SUM(cd1.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL
418  $sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd1, ".MAIN_DB_PREFIX."commande as c1";
419  $sqlCommandesCli .= " WHERE c1.rowid = cd1.fk_commande AND c1.entity IN (".getEntity(!empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'commande').")";
420  $sqlCommandesCli .= " AND cd1.fk_product = p.rowid";
421  $sqlCommandesCli .= " AND c1.fk_statut IN (1,2))";
422  } else {
423  $sqlCommandesCli = '0';
424  }
425 
426  if (!empty($conf->expedition->enabled)) {
427  $sqlExpeditionsCli = "(SELECT ".$db->ifsql("SUM(ed2.qty) IS NULL", "0", "SUM(ed2.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL
428  $sqlExpeditionsCli .= " FROM ".MAIN_DB_PREFIX."expedition as e2,";
429  $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."expeditiondet as ed2,";
430  $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."commande as c2,";
431  $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."commandedet as cd2";
432  $sqlExpeditionsCli .= " WHERE ed2.fk_expedition = e2.rowid AND cd2.rowid = ed2.fk_origin_line AND e2.entity IN (".getEntity(!empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'expedition').")";
433  $sqlExpeditionsCli .= " AND cd2.fk_commande = c2.rowid";
434  $sqlExpeditionsCli .= " AND c2.fk_statut IN (1,2)";
435  $sqlExpeditionsCli .= " AND cd2.fk_product = p.rowid";
436  $sqlExpeditionsCli .= " AND e2.fk_statut IN (1,2))";
437  } else {
438  $sqlExpeditionsCli = '0';
439  }
440 
441  if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled)) {
442  $sqlCommandesFourn = "(SELECT ".$db->ifsql("SUM(cd3.qty) IS NULL", "0", "SUM(cd3.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL
443  $sqlCommandesFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd3,";
444  $sqlCommandesFourn .= " ".MAIN_DB_PREFIX."commande_fournisseur as c3";
445  $sqlCommandesFourn .= " WHERE c3.rowid = cd3.fk_commande";
446  $sqlCommandesFourn .= " AND c3.entity IN (".getEntity(!empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
447  $sqlCommandesFourn .= " AND cd3.fk_product = p.rowid";
448  $sqlCommandesFourn .= " AND c3.fk_statut IN (3,4))";
449 
450  $sqlReceptionFourn = "(SELECT ".$db->ifsql("SUM(fd4.qty) IS NULL", "0", "SUM(fd4.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL
451  $sqlReceptionFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf4,";
452  $sqlReceptionFourn .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd4";
453  $sqlReceptionFourn .= " WHERE fd4.fk_commande = cf4.rowid AND cf4.entity IN (".getEntity(!empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
454  $sqlReceptionFourn .= " AND fd4.fk_product = p.rowid";
455  $sqlReceptionFourn .= " AND cf4.fk_statut IN (3,4))";
456  } else {
457  $sqlCommandesFourn = '0';
458  $sqlReceptionFourn = '0';
459  }
460 
461  if (!empty($conf->mrp->enabled)) {
462  $sqlProductionToConsume = "(SELECT GREATEST(0, ".$db->ifsql("SUM(".$db->ifsql("mp5.role = 'toconsume'", 'mp5.qty', '- mp5.qty').") IS NULL", "0", "SUM(".$db->ifsql("mp5.role = 'toconsume'", 'mp5.qty', '- mp5.qty').")").") as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL
463  $sqlProductionToConsume .= " FROM ".MAIN_DB_PREFIX."mrp_mo as mm5,";
464  $sqlProductionToConsume .= " ".MAIN_DB_PREFIX."mrp_production as mp5";
465  $sqlProductionToConsume .= " WHERE mm5.rowid = mp5.fk_mo AND mm5.entity IN (".getEntity(!empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mo').")";
466  $sqlProductionToConsume .= " AND mp5.fk_product = p.rowid";
467  $sqlProductionToConsume .= " AND mp5.role IN ('toconsume', 'consumed')";
468  $sqlProductionToConsume .= " AND mm5.status IN (1,2))";
469 
470  $sqlProductionToProduce = "(SELECT GREATEST(0, ".$db->ifsql("SUM(".$db->ifsql("mp5.role = 'toproduce'", 'mp5.qty', '- mp5.qty').") IS NULL", "0", "SUM(".$db->ifsql("mp5.role = 'toconsume'", 'mp5.qty', '- mp5.qty').")").") as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL
471  $sqlProductionToProduce .= " FROM ".MAIN_DB_PREFIX."mrp_mo as mm5,";
472  $sqlProductionToProduce .= " ".MAIN_DB_PREFIX."mrp_production as mp5";
473  $sqlProductionToProduce .= " WHERE mm5.rowid = mp5.fk_mo AND mm5.entity IN (".getEntity(!empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mo').")";
474  $sqlProductionToProduce .= " AND mp5.fk_product = p.rowid";
475  $sqlProductionToProduce .= " AND mp5.role IN ('toproduce', 'produced')";
476  $sqlProductionToProduce .= " AND mm5.status IN (1,2))";
477  } else {
478  $sqlProductionToConsume = '0';
479  $sqlProductionToProduce = '0';
480  }
481 
482  $sql .= ' HAVING (';
483  $sql .= " (".$sqldesiredtock." >= 0 AND (".$sqldesiredtock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").')';
484  $sql .= " - (".$sqlCommandesCli." - ".$sqlExpeditionsCli.") + (".$sqlCommandesFourn." - ".$sqlReceptionFourn.") + (".$sqlProductionToProduce." - ".$sqlProductionToConsume.")))";
485  $sql .= ' OR';
486  if ($includeproductswithoutdesiredqty == 'on') {
487  $sql .= " ((".$sqlalertstock." >= 0 OR ".$sqlalertstock." IS NULL) AND (".$db->ifsql($sqlalertstock." IS NULL", "0", $sqlalertstock)." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").")";
488  } else {
489  $sql .= " (".$sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").')';
490  }
491  $sql .= " - (".$sqlCommandesCli." - ".$sqlExpeditionsCli.") + (".$sqlCommandesFourn." - ".$sqlReceptionFourn.") + (".$sqlProductionToProduce." - ".$sqlProductionToConsume.")))";
492  $sql .= ")";
493 
494  if ($salert == 'on') { // Option to see when stock is lower than alert
495  $sql .= ' AND (';
496  if ($includeproductswithoutdesiredqty == 'on') {
497  $sql .= "(".$sqlalertstock." >= 0 OR ".$sqlalertstock." IS NULL) AND (".$db->ifsql($sqlalertstock." IS NULL", "0", $sqlalertstock)." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").")";
498  } else {
499  $sql .= $sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").")";
500  }
501  $sql .= " - (".$sqlCommandesCli." - ".$sqlExpeditionsCli.") + (".$sqlCommandesFourn." - ".$sqlReceptionFourn.") + (".$sqlProductionToProduce." - ".$sqlProductionToConsume."))";
502  $sql .= ")";
503  $alertchecked = 'checked';
504  }
505 } else {
506  $sql .= ' HAVING (';
507  $sql .= "(".$sqldesiredtock." >= 0 AND (".$sqldesiredtock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").")))";
508  $sql .= ' OR';
509  if ($includeproductswithoutdesiredqty == 'on') {
510  $sql .= " ((".$sqlalertstock." >= 0 OR ".$sqlalertstock." IS NULL) AND (".$db->ifsql($sqlalertstock." IS NULL", "0", $sqlalertstock)." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").')))';
511  } else {
512  $sql .= " (".$sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").')))';
513  }
514  $sql .= ')';
515 
516  if ($salert == 'on') { // Option to see when stock is lower than alert
517  $sql .= " AND (";
518  if ($includeproductswithoutdesiredqty == 'on') {
519  $sql .= " (".$sqlalertstock." >= 0 OR ".$sqlalertstock." IS NULL) AND (".$db->ifsql($sqlalertstock." IS NULL", "0", $sqlalertstock)." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel")."))";
520  } else {
521  $sql .= " ".$sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").'))';
522  }
523  $sql .= ')';
524  $alertchecked = 'checked';
525  }
526 }
527 
528 $includeproductswithoutdesiredqtychecked = '';
529 if ($includeproductswithoutdesiredqty == 'on') {
530  $includeproductswithoutdesiredqtychecked = 'checked';
531 }
532 
533 $nbtotalofrecords = '';
534 if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
535  $result = $db->query($sql);
536  $nbtotalofrecords = $db->num_rows($result);
537  if (($page * $limit) > $nbtotalofrecords) {
538  $page = 0;
539  $offset = 0;
540  }
541 }
542 
543 $sql .= $db->order($sortfield, $sortorder);
544 $sql .= $db->plimit($limit + 1, $offset);
545 
546 //print $sql;
547 $resql = $db->query($sql);
548 if (empty($resql)) {
549  dol_print_error($db);
550  exit;
551 }
552 
553 $num = $db->num_rows($resql);
554 $i = 0;
555 
556 $helpurl = 'EN:Module_Stocks_En|FR:Module_Stock|';
557 $helpurl .= 'ES:M&oacute;dulo_Stocks';
558 
559 llxHeader('', $title, $helpurl, '');
560 
561 $head = array();
562 
563 $head[0][0] = DOL_URL_ROOT.'/product/stock/replenish.php';
564 $head[0][1] = $title;
565 $head[0][2] = 'replenish';
566 
567 $head[1][0] = DOL_URL_ROOT.'/product/stock/replenishorders.php';
568 $head[1][1] = $langs->trans("ReplenishmentOrders");
569 $head[1][2] = 'replenishorders';
570 
571 
572 print load_fiche_titre($langs->trans('Replenishment'), '', 'stock');
573 
574 print dol_get_fiche_head($head, 'replenish', '', -1, '');
575 
576 print '<span class="opacitymedium">'.$langs->trans("ReplenishmentStatusDesc").'</span>'."\n";
577 
578 //$link = '<a title=' .$langs->trans("MenuNewWarehouse"). ' href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create">'.$langs->trans("MenuNewWarehouse").'</a>';
579 
580 if (empty($fk_entrepot) && !empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) {
581  print '<span class="opacitymedium">'.$langs->trans("ReplenishmentStatusDescPerWarehouse").'</span>'."\n";
582 }
583 print '<br><br>';
584 if ($usevirtualstock == 1) {
585  print $langs->trans("CurentSelectionMode").': ';
586  print '<span class="a-mesure">'.$langs->trans("UseVirtualStock").'</span>';
587  print ' <a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=physical'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UsePhysicalStock").'</a>';
588  print '<br>';
589 }
590 if ($usevirtualstock == 0) {
591  print $langs->trans("CurentSelectionMode").': ';
592  print '<a class="a-mesure-disabled" href="'.$_SERVER["PHP_SELF"].'?mode=virtual'.($fk_supplier > 0 ? '&fk_supplier='.$fk_supplier : '').($fk_entrepot > 0 ? '&fk_entrepot='.$fk_entrepot : '').'">'.$langs->trans("UseVirtualStock").'</a>';
593  print ' <span class="a-mesure">'.$langs->trans("UsePhysicalStock").'</span>';
594  print '<br>';
595 }
596 print '<br>'."\n";
597 
598 print '<form name="formFilterWarehouse" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
599 print '<input type="hidden" name="token" value="'.newToken().'">';
600 print '<input type="hidden" name="action" value="filter">';
601 print '<input type="hidden" name="search_ref" value="'.$search_ref.'">';
602 print '<input type="hidden" name="search_label" value="'.$search_label.'">';
603 print '<input type="hidden" name="salert" value="'.$salert.'">';
604 print '<input type="hidden" name="includeproductswithoutdesiredqty" value="'.$includeproductswithoutdesiredqty.'">';
605 print '<input type="hidden" name="draftorder" value="'.$draftorder.'">';
606 print '<input type="hidden" name="mode" value="'.$mode.'">';
607 if ($limit > 0 && $limit != $conf->liste_limit) {
608  print '<input type="hidden" name="limit" value="'.$limit.'">';
609 }
610 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE)) {
611  print '<div class="inline-block valignmiddle" style="padding-right: 20px;">';
612  print $langs->trans('Warehouse').' '.$formproduct->selectWarehouses($fk_entrepot, 'fk_entrepot', '', 1);
613  print '</div>';
614 }
615 print '<div class="inline-block valignmiddle" style="padding-right: 20px;">';
616 print $langs->trans('Supplier').' '.$form->select_company($fk_supplier, 'fk_supplier', 'fournisseur=1', 1);
617 print '</div>';
618 
619 $parameters = array();
620 $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
621 if (empty($reshook)) {
622  print $hookmanager->resPrint;
623 }
624 
625 print '<div class="inline-block valignmiddle">';
626 print '<input type="submit" class="button smallpaddingimp" name="valid" value="'.$langs->trans('ToFilter').'">';
627 print '</div>';
628 
629 print '</form>';
630 
631 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">';
632 print '<input type="hidden" name="token" value="'.newToken().'">';
633 print '<input type="hidden" name="fk_supplier" value="'.$fk_supplier.'">';
634 print '<input type="hidden" name="fk_entrepot" value="'.$fk_entrepot.'">';
635 print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
636 print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
637 print '<input type="hidden" name="type" value="'.$type.'">';
638 print '<input type="hidden" name="linecount" value="'.$num.'">';
639 print '<input type="hidden" name="action" value="order">';
640 print '<input type="hidden" name="mode" value="'.$mode.'">';
641 
642 
643 if ($search_ref || $search_label || $sall || $salert || $draftorder || GETPOST('search', 'alpha')) {
644  $filters = '&search_ref='.urlencode($search_ref).'&search_label='.urlencode($search_label);
645  $filters .= '&sall='.urlencode($sall);
646  $filters .= '&salert='.urlencode($salert);
647  $filters .= '&draftorder='.urlencode($draftorder);
648  $filters .= '&mode='.urlencode($mode);
649  if ($fk_supplier > 0) {
650  $filters .= '&fk_supplier='.urlencode($fk_supplier);
651  }
652  if ($fk_entrepot > 0) {
653  $filters .= '&fk_entrepot='.urlencode($fk_entrepot);
654  }
655 } else {
656  $filters = '&search_ref='.urlencode($search_ref).'&search_label='.urlencode($search_label);
657  $filters .= '&fourn_id='.urlencode($fourn_id);
658  $filters .= (isset($type) ? '&type='.urlencode($type) : '');
659  $filters .= '&='.urlencode($salert);
660  $filters .= '&draftorder='.urlencode($draftorder);
661  $filters .= '&mode='.urlencode($mode);
662  if ($fk_supplier > 0) {
663  $filters .= '&fk_supplier='.urlencode($fk_supplier);
664  }
665  if ($fk_entrepot > 0) {
666  $filters .= '&fk_entrepot='.urlencode($fk_entrepot);
667  }
668 }
669 if ($limit > 0 && $limit != $conf->liste_limit) {
670  $filters .= '&limit='.urlencode($limit);
671 }
672 if (!empty($includeproductswithoutdesiredqty)) $filters .= '&includeproductswithoutdesiredqty='.urlencode($includeproductswithoutdesiredqty);
673 if (!empty($salert)) $filters .= '&salert='.urlencode($salert);
674 
675 $param = (isset($type) ? '&type='.urlencode($type) : '');
676 $param .= '&fourn_id='.urlencode($fourn_id).'&search_label='.urlencode($search_label).'&includeproductswithoutdesiredqty='.urlencode($includeproductswithoutdesiredqty).'&salert='.urlencode($salert).'&draftorder='.urlencode($draftorder);
677 $param .= '&search_ref='.urlencode($search_ref);
678 $param .= '&mode='.urlencode($mode);
679 $param .= '&fk_supplier='.urlencode($fk_supplier);
680 $param .= '&fk_entrepot='.urlencode($fk_entrepot);
681 if (!empty($includeproductswithoutdesiredqty)) $param .= '&includeproductswithoutdesiredqty='.urlencode($includeproductswithoutdesiredqty);
682 if (!empty($salert)) $param .= '&salert='.urlencode($salert);
683 
684 $stocklabel = $langs->trans('Stock');
685 $stocklabelbis = $langs->trans('Stock');
686 if ($usevirtualstock == 1) {
687  $stocklabel = $langs->trans('VirtualStock');
688 }
689 if ($usevirtualstock == 0) {
690  $stocklabel = $langs->trans('PhysicalStock');
691 }
692 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
693  $stocklabelbis = $stocklabel.' (Selected warehouse)';
694  $stocklabel .= ' ('.$langs->trans("AllWarehouses").')';
695 }
696 $texte = $langs->trans('Replenishment');
697 
698 print '<br>';
699 
700 print '<div class="div-table-responsive-no-min">';
701 
702 if (!empty($conf->global->REPLENISH_ALLOW_VARIABLESIZELIST)) {
704  $texte,
705  $page,
706  'replenish.php',
707  $filters,
708  $sortfield,
709  $sortorder,
710  '',
711  $num,
712  $nbtotalofrecords,
713  '',
714  0,
715  '',
716  '',
717  $limit
718  );
719 } else {
721  $texte,
722  $page,
723  'replenish.php',
724  $filters,
725  $sortfield,
726  $sortorder,
727  '',
728  $num,
729  $nbtotalofrecords,
730  ''
731  );
732 }
733 
734 print '<table class="liste centpercent">';
735 
736 // Fields title search
737 print '<tr class="liste_titre_filter">';
738 print '<td class="liste_titre">&nbsp;</td>';
739 print '<td class="liste_titre"><input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'"></td>';
740 print '<td class="liste_titre"><input class="flat" type="text" name="search_label" size="8" value="'.dol_escape_htmltag($search_label).'"></td>';
741 if (!empty($conf->service->enabled) && $type == 1) {
742  print '<td class="liste_titre">&nbsp;</td>';
743 }
744 print '<td class="liste_titre right">'.$form->textwithpicto($langs->trans('IncludeEmptyDesiredStock'), $langs->trans('IncludeProductWithUndefinedAlerts')).'&nbsp;<input type="checkbox" id="includeproductswithoutdesiredqty" name="includeproductswithoutdesiredqty" '.(!empty($includeproductswithoutdesiredqtychecked) ? $includeproductswithoutdesiredqtychecked : '').'></td>';
745 print '<td class="liste_titre right"></td>';
746 print '<td class="liste_titre right">'.$langs->trans('AlertOnly').'&nbsp;<input type="checkbox" id="salert" name="salert" '.(!empty($alertchecked) ? $alertchecked : '').'></td>';
747 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
748  print '<td class="liste_titre">&nbsp;</td>';
749 }
750 print '<td class="liste_titre right">';
751 if (!empty($conf->global->STOCK_REPLENISH_ADD_CHECKBOX_INCLUDE_DRAFT_ORDER)) {
752  print $langs->trans('IncludeAlsoDraftOrders').'&nbsp;<input type="checkbox" id="draftorder" name="draftorder" '.(!empty($draftchecked) ? $draftchecked : '').'>';
753 }
754 print '</td>';
755 print '<td class="liste_titre">&nbsp;</td>';
756 // Fields from hook
757 $parameters = array('param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
758 $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
759 print $hookmanager->resPrint;
760 
761 print '<td class="liste_titre maxwidthsearch right">';
762 $searchpicto = $form->showFilterAndCheckAddButtons(0);
763 print $searchpicto;
764 print '</td>';
765 print '</tr>';
766 
767 // Lines of title
768 print '<tr class="liste_titre">';
769 print_liste_field_titre('<input type="checkbox" onClick="toggle(this)" />', $_SERVER["PHP_SELF"], '');
770 print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'p.ref', $param, '', '', $sortfield, $sortorder);
771 print_liste_field_titre('Label', $_SERVER["PHP_SELF"], 'p.label', $param, '', '', $sortfield, $sortorder);
772 if (!empty($conf->service->enabled) && $type == 1) {
773  print_liste_field_titre('Duration', $_SERVER["PHP_SELF"], 'p.duration', $param, '', '', $sortfield, $sortorder, 'center ');
774 }
775 print_liste_field_titre('DesiredStock', $_SERVER["PHP_SELF"], 'p.desiredstock', $param, '', '', $sortfield, $sortorder, 'right ');
776 print_liste_field_titre('StockLimitShort', $_SERVER["PHP_SELF"], 'p.seuil_stock_alerte', $param, '', '', $sortfield, $sortorder, 'right ');
777 print_liste_field_titre($stocklabel, $_SERVER["PHP_SELF"], 'stock_physique', $param, '', '', $sortfield, $sortorder, 'right ');
778 if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
779  print_liste_field_titre($stocklabelbis, $_SERVER["PHP_SELF"], 'stock_real_warehouse', $param, '', '', $sortfield, $sortorder, 'right ');
780 }
781 print_liste_field_titre('Ordered', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
782 print_liste_field_titre('StockToBuy', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
783 print_liste_field_titre('SupplierRef', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
784 
785 // Hook fields
786 $parameters = array('param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
787 $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
788 print $hookmanager->resPrint;
789 
790 print "</tr>\n";
791 
792 while ($i < ($limit ? min($num, $limit) : $num)) {
793  $objp = $db->fetch_object($resql);
794 
795  if (!empty($conf->global->STOCK_SUPPORTS_SERVICES) || $objp->fk_product_type == 0) {
796  $result = $prod->fetch($objp->rowid);
797  if ($result < 0) {
798  dol_print_error($db);
799  exit;
800  }
801 
802  $prod->load_stock('warehouseopen, warehouseinternal'.(!$usevirtualstock?', novirtual':''), $draftchecked);
803 
804  // Multilangs
805  if (!empty($conf->global->MAIN_MULTILANGS)) {
806  $sql = 'SELECT label,description';
807  $sql .= ' FROM '.MAIN_DB_PREFIX.'product_lang';
808  $sql .= ' WHERE fk_product = '.((int) $objp->rowid);
809  $sql .= " AND lang = '".$db->escape($langs->getDefaultLang())."'";
810  $sql .= ' LIMIT 1';
811 
812  $resqlm = $db->query($sql);
813  if ($resqlm) {
814  $objtp = $db->fetch_object($resqlm);
815  if (!empty($objtp->description)) {
816  $objp->description = $objtp->description;
817  }
818  if (!empty($objtp->label)) {
819  $objp->label = $objtp->label;
820  }
821  }
822  }
823 
824  $stockwarehouse = 0;
825  if ($usevirtualstock) {
826  // If option to increase/decrease is not on an object validation, virtual stock may differs from physical stock.
827  $stock = $prod->stock_theorique;
828  //TODO $stockwarehouse = $prod->stock_warehouse[$fk_entrepot]->;
829  } else {
830  $stock = $prod->stock_reel;
831  $stockwarehouse = $prod->stock_warehouse[$fk_entrepot]->real;
832  }
833 
834  // Force call prod->load_stats_xxx to choose status to count (otherwise it is loaded by load_stock function)
835  if (isset($draftchecked)) {
836  $result = $prod->load_stats_commande_fournisseur(0, '0,1,2,3,4');
837  } elseif (!$usevirtualstock) {
838  $result = $prod->load_stats_commande_fournisseur(0, '1,2,3,4');
839  }
840 
841  if (!$usevirtualstock) {
842  $result = $prod->load_stats_reception(0, '4');
843  }
844 
845  //print $prod->stats_commande_fournisseur['qty'].'<br>'."\n";
846  //print $prod->stats_reception['qty'];
847  $ordered = $prod->stats_commande_fournisseur['qty'] - $prod->stats_reception['qty'];
848 
849  $desiredstock = $objp->desiredstock;
850  $alertstock = $objp->seuil_stock_alerte;
851  $desiredstockwarehouse = ($objp->desiredstockpse ? $objp->desiredstockpse : 0);
852  $alertstockwarehouse = ($objp->seuil_stock_alertepse ? $objp->seuil_stock_alertepse : 0);
853 
854  $warning = '';
855  if ($alertstock && ($stock < $alertstock)) {
856  $warning = img_warning($langs->trans('StockTooLow')).' ';
857  }
858  $warningwarehouse = '';
859  if ($alertstockwarehouse && ($stockwarehouse < $alertstockwarehouse)) {
860  $warningwarehouse = img_warning($langs->trans('StockTooLow')).' ';
861  }
862 
863  //depending on conf, use either physical stock or
864  //virtual stock to compute the stock to buy value
865 
866  if (empty($usevirtualstock)) {
867  $stocktobuy = max(max($desiredstock, $alertstock) - $stock - $ordered, 0);
868  } else {
869  $stocktobuy = max(max($desiredstock, $alertstock) - $stock, 0); //ordered is already in $stock in virtual mode
870  }
871  if (empty($usevirtualstock)) {
872  $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse - $ordered, 0);
873  } else {
874  $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse, 0); //ordered is already in $stock in virtual mode
875  }
876 
877  $picto = '';
878  if ($ordered > 0) {
879  $stockforcompare = ($usevirtualstock ? $stock : $stock + $ordered);
880  /*if ($stockforcompare >= $desiredstock)
881  {
882  $picto = img_picto('', 'help');
883  } else {
884  $picto = img_picto('', 'help');
885  }*/
886  } else {
887  $picto = img_picto($langs->trans("NoPendingReceptionOnSupplierOrder"), 'help');
888  }
889 
890  print '<tr class="oddeven">';
891 
892  // Select field
893  print '<td><input type="checkbox" class="check" name="choose'.$i.'"></td>';
894 
895  print '<td class="nowrap">'.$prod->getNomUrl(1, 'stock').'</td>';
896 
897  print '<td class="tdoverflowmax200" title="'.dol_escape_htmltag($objp->label).'">';
898  print dol_escape_htmltag($objp->label);
899  print '<input type="hidden" name="desc'.$i.'" value="'.dol_escape_htmltag($objp->description).'">'; // TODO Remove this and make a fetch to get description when creating order instead of a GETPOST
900  print '</td>';
901 
902  if (!empty($conf->service->enabled) && $type == 1) {
903  $regs = array();
904  if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) {
905  $duration = $regs[1].' '.$langs->trans('DurationYear');
906  } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) {
907  $duration = $regs[1].' '.$langs->trans('DurationMonth');
908  } elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) {
909  $duration = $regs[1].' '.$langs->trans('DurationDay');
910  } else {
911  $duration = $objp->duration;
912  }
913  print '<td class="center">'.$duration.'</td>';
914  }
915 
916  // Desired stock
917  print '<td class="right">'.((!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) > 0 ? $desiredstockwarehouse : $desiredstock).'</td>';
918 
919  // Limit stock for alert
920  print '<td class="right">'.((!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) > 0 ? $alertstockwarehouse : $alertstock).'</td>';
921 
922  // Current stock (all warehouses)
923  print '<td class="right">'.$warning.$stock;
924  print '<!-- stock returned by main sql is '.$objp->stock_physique.' -->';
925  print '</td>';
926 
927  // Current stock (warehouse selected only)
928  if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) {
929  print '<td class="right">'.$warningwarehouse.$stockwarehouse.'</td>';
930  }
931 
932  // Already ordered
933  print '<td class="right"><a href="replenishorders.php?search_product='.$prod->id.'">'.$ordered.'</a> '.$picto.'</td>';
934 
935  // To order
936  print '<td class="right"><input type="text" size="4" name="tobuy'.$i.'" value="'.((!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entrepot > 0) > 0 ? $stocktobuywarehouse : $stocktobuy).'"></td>';
937 
938  // Supplier
939  print '<td class="right">';
940  print $form->select_product_fourn_price($prod->id, 'fourn'.$i, $fk_supplier);
941  print '</td>';
942 
943  // Fields from hook
944  $parameters = array('objp'=>$objp);
945  $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
946  print $hookmanager->resPrint;
947 
948  print '</tr>';
949  }
950  $i++;
951 }
952 
953 $parameters = array('sql'=>$sql);
954 $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
955 print $hookmanager->resPrint;
956 
957 print '</table>';
958 print '</div>';
959 
960 $db->free($resql);
961 
962 print dol_get_fiche_end();
963 
964 
965 $value = $langs->trans("CreateOrders");
966 print '<div class="center"><input type="submit" class="button" name="valid" value="'.$value.'"></div>';
967 
968 
969 print '</form>';
970 
971 
972 // TODO Replace this with jquery
973 print '
974 <script type="text/javascript">
975 function toggle(source)
976 {
977  checkboxes = document.getElementsByClassName("check");
978  for (var i=0; i < checkboxes.length;i++) {
979  if (!checkboxes[i].disabled) {
980  checkboxes[i].checked = source.checked;
981  }
982  }
983 }
984 </script>';
985 
986 
987 llxFooter();
988 
989 $db->close();
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1468
restrictedArea
restrictedArea($user, $features, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.
Definition: security.lib.php:234
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:73
ProductFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.product.class.php:41
load_fiche_titre
load_fiche_titre($titre, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
Definition: functions.lib.php:5204
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
img_warning
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
Definition: functions.lib.php:4521
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
getEntity
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
Definition: functions.lib.php:148
print_barre_liste
print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='generic', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $hideselectlimit=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow='')
Print a title with navigation controls for pagination.
Definition: functions.lib.php:5257
dol_get_fiche_head
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
Show tabs of a record.
Definition: functions.lib.php:1822
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
FormProduct
Class with static methods for building HTML components related to products Only components common to ...
Definition: html.formproduct.class.php:30
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2018
CommandeFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.commande.class.php:47
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:386
print_liste_field_titre
print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
Definition: functions.lib.php:5026
natural_search
natural_search($fields, $value, $mode=0, $nofirstand=0)
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
Definition: functions.lib.php:9420
Product
Class to manage products or services.
Definition: product.class.php:46
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
CommandeFournisseurLigne
Class to manage line orders.
Definition: fournisseur.commande.class.php:3550
llxHeader
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOCSRFCHECK')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:59