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