replenish.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. /**
  25. * \file htdocs/product/stock/replenish.php
  26. * \ingroup stock
  27. * \brief Page to list stocks to replenish
  28. */
  29. // Load Dolibarr environment
  30. require '../../main.inc.php';
  31. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  32. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  34. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  36. require_once './lib/replenishment.lib.php';
  37. // Load translation files required by the page
  38. $langs->loadLangs(array('products', 'stocks', 'orders'));
  39. // Security check
  40. if ($user->socid) {
  41. $socid = $user->socid;
  42. }
  43. $result = restrictedArea($user, 'produit|service');
  44. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  45. $hookmanager->initHooks(array('stockreplenishlist'));
  46. //checks if a product has been ordered
  47. $action = GETPOST('action', 'aZ09');
  48. $search_ref = GETPOST('search_ref', 'alpha');
  49. $search_label = GETPOST('search_label', 'alpha');
  50. $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml'));
  51. $type = GETPOST('type', 'int');
  52. $tobuy = GETPOST('tobuy', 'int');
  53. $salert = GETPOST('salert', 'alpha');
  54. $includeproductswithoutdesiredqty = GETPOST('includeproductswithoutdesiredqty', 'alpha');
  55. $mode = GETPOST('mode', 'alpha');
  56. $draftorder = GETPOST('draftorder', 'alpha');
  57. $fourn_id = GETPOST('fourn_id', 'int');
  58. $fk_supplier = GETPOST('fk_supplier', 'int');
  59. $fk_entrepot = GETPOST('fk_entrepot', 'int');
  60. // List all visible warehouses
  61. $resWar = $db->query("SELECT rowid FROM " . MAIN_DB_PREFIX . "entrepot WHERE entity IN (" . $db->sanitize(getEntity('stock')) .")");
  62. $listofqualifiedwarehousesid = "";
  63. $count = 0;
  64. while ($tmpobj = $db->fetch_object($resWar)) {
  65. if (!empty($listofqualifiedwarehousesid)) {
  66. $listofqualifiedwarehousesid .= ",";
  67. }
  68. $listofqualifiedwarehousesid .= $tmpobj->rowid;
  69. $lastWarehouseID = $tmpobj->rowid;
  70. $count++;
  71. }
  72. //MultiCompany : If only 1 Warehouse is visible, filter will automatically be set to it.
  73. if ($count == 1 && (empty($fk_entrepot) || $fk_entrepot <= 0) && getDolGlobalString('MULTICOMPANY_PRODUCT_SHARING_ENABLED')) {
  74. $fk_entrepot = $lastWarehouseID;
  75. }
  76. $texte = '';
  77. $sortfield = GETPOST('sortfield', 'aZ09comma');
  78. $sortorder = GETPOST('sortorder', 'aZ09comma');
  79. $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
  80. if (empty($page) || $page == -1) {
  81. $page = 0;
  82. } // If $page is not defined, or '' or -1
  83. $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
  84. $offset = $limit * $page;
  85. if (!$sortfield) {
  86. $sortfield = 'p.ref';
  87. }
  88. if (!$sortorder) {
  89. $sortorder = 'ASC';
  90. }
  91. // Define virtualdiffersfromphysical
  92. $virtualdiffersfromphysical = 0;
  93. if (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT')
  94. || getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER')
  95. || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE')
  96. || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION')
  97. || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION_CLOSE')
  98. || isModEnabled('mrp')) {
  99. $virtualdiffersfromphysical = 1; // According to increase/decrease stock options, virtual and physical stock may differs.
  100. }
  101. if ($virtualdiffersfromphysical) {
  102. $usevirtualstock = !getDolGlobalString('STOCK_USE_REAL_STOCK_BY_DEFAULT_FOR_REPLENISHMENT') ? 1 : 0;
  103. } else {
  104. $usevirtualstock = 0;
  105. }
  106. if ($mode == 'physical') {
  107. $usevirtualstock = 0;
  108. }
  109. if ($mode == 'virtual') {
  110. $usevirtualstock = 1;
  111. }
  112. $parameters = array();
  113. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  114. if ($reshook < 0) {
  115. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  116. }
  117. /*
  118. * Actions
  119. */
  120. 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
  121. $search_ref = '';
  122. $search_label = '';
  123. $sall = '';
  124. $salert = '';
  125. $includeproductswithoutdesiredqty = '';
  126. $draftorder = '';
  127. }
  128. $draftchecked = "";
  129. if ($draftorder == 'on') {
  130. $draftchecked = "checked";
  131. }
  132. // Create orders
  133. if ($action == 'order' && GETPOST('valid')) {
  134. $linecount = GETPOST('linecount', 'int');
  135. $box = 0;
  136. $errorQty = 0;
  137. unset($_POST['linecount']);
  138. if ($linecount > 0) {
  139. $db->begin();
  140. $suppliers = array();
  141. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  142. $productsupplier = new ProductFournisseur($db);
  143. for ($i = 0; $i < $linecount; $i++) {
  144. if (GETPOST('choose'.$i, 'alpha') === 'on' && GETPOST('fourn'.$i, 'int') > 0) {
  145. //one line
  146. $box = $i;
  147. $supplierpriceid = GETPOST('fourn'.$i, 'int');
  148. //get all the parameters needed to create a line
  149. $qty = GETPOST('tobuy'.$i, 'int');
  150. $idprod = $productsupplier->get_buyprice($supplierpriceid, $qty);
  151. $res = $productsupplier->fetch($idprod);
  152. if ($res && $idprod > 0) {
  153. if ($qty) {
  154. //might need some value checks
  155. $line = new CommandeFournisseurLigne($db);
  156. $line->qty = $qty;
  157. $line->fk_product = $idprod;
  158. //$product = new Product($db);
  159. //$product->fetch($obj->fk_product);
  160. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  161. $productsupplier->getMultiLangs();
  162. }
  163. // if we use supplier description of the products
  164. if (!empty($productsupplier->desc_supplier) && getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
  165. $desc = $productsupplier->desc_supplier;
  166. } else {
  167. $desc = $productsupplier->description;
  168. }
  169. $line->desc = $desc;
  170. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  171. // TODO Get desc in language of thirdparty
  172. }
  173. $line->tva_tx = $productsupplier->vatrate_supplier;
  174. $line->subprice = $productsupplier->fourn_pu;
  175. $line->total_ht = $productsupplier->fourn_pu * $qty;
  176. $tva = $line->tva_tx / 100;
  177. $line->total_tva = $line->total_ht * $tva;
  178. $line->total_ttc = $line->total_ht + $line->total_tva;
  179. $line->remise_percent = $productsupplier->remise_percent;
  180. $line->ref_fourn = $productsupplier->ref_supplier;
  181. $line->type = $productsupplier->type;
  182. $line->fk_unit = $productsupplier->fk_unit;
  183. $suppliers[$productsupplier->fourn_socid]['lines'][] = $line;
  184. }
  185. } elseif ($idprod == -1) {
  186. $errorQty++;
  187. } else {
  188. $error = $db->lasterror();
  189. dol_print_error($db);
  190. }
  191. unset($_POST['fourn'.$i]);
  192. }
  193. unset($_POST[$i]);
  194. }
  195. //we now know how many orders we need and what lines they have
  196. $i = 0;
  197. $fail = 0;
  198. $orders = array();
  199. $suppliersid = array_keys($suppliers);
  200. foreach ($suppliers as $supplier) {
  201. $order = new CommandeFournisseur($db);
  202. // Check if an order for the supplier exists
  203. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur";
  204. $sql .= " WHERE fk_soc = ".((int) $suppliersid[$i]);
  205. $sql .= " AND source = ".((int) $order::SOURCE_ID_REPLENISHMENT)." AND fk_statut = ".((int) $order::STATUS_DRAFT);
  206. $sql .= " AND entity IN (".getEntity('commande_fournisseur').")";
  207. $sql .= " ORDER BY date_creation DESC";
  208. $resql = $db->query($sql);
  209. if ($resql && $db->num_rows($resql) > 0) {
  210. $obj = $db->fetch_object($resql);
  211. $order->fetch($obj->rowid);
  212. $order->fetch_thirdparty();
  213. foreach ($supplier['lines'] as $line) {
  214. if (empty($line->remise_percent)) {
  215. $line->remise_percent = $order->thirdparty->remise_supplier_percent;
  216. }
  217. $result = $order->addline(
  218. $line->desc,
  219. $line->subprice,
  220. $line->qty,
  221. $line->tva_tx,
  222. $line->localtax1_tx,
  223. $line->localtax2_tx,
  224. $line->fk_product,
  225. 0,
  226. $line->ref_fourn,
  227. $line->remise_percent,
  228. 'HT',
  229. 0,
  230. $line->type,
  231. 0,
  232. false,
  233. null,
  234. null,
  235. 0,
  236. $line->fk_unit
  237. );
  238. }
  239. if ($result < 0) {
  240. $fail++;
  241. $msg = $langs->trans('OrderFail')."&nbsp;:&nbsp;";
  242. $msg .= $order->error;
  243. setEventMessages($msg, null, 'errors');
  244. } else {
  245. $id = $result;
  246. }
  247. } else {
  248. $order->socid = $suppliersid[$i];
  249. $order->fetch_thirdparty();
  250. // Trick to know which orders have been generated using the replenishment feature
  251. $order->source = $order::SOURCE_ID_REPLENISHMENT;
  252. foreach ($supplier['lines'] as $line) {
  253. if (empty($line->remise_percent)) {
  254. $line->remise_percent = $order->thirdparty->remise_supplier_percent;
  255. }
  256. $order->lines[] = $line;
  257. }
  258. $order->cond_reglement_id = $order->thirdparty->cond_reglement_supplier_id;
  259. $order->mode_reglement_id = $order->thirdparty->mode_reglement_supplier_id;
  260. $id = $order->create($user);
  261. if ($id < 0) {
  262. $fail++;
  263. $msg = $langs->trans('OrderFail')."&nbsp;:&nbsp;";
  264. $msg .= $order->error;
  265. setEventMessages($msg, null, 'errors');
  266. }
  267. $i++;
  268. }
  269. }
  270. if ($errorQty) {
  271. setEventMessages($langs->trans('ErrorOrdersNotCreatedQtyTooLow'), null, 'warnings');
  272. }
  273. if (!$fail && $id) {
  274. $db->commit();
  275. setEventMessages($langs->trans('OrderCreated'), null, 'mesgs');
  276. header('Location: replenishorders.php');
  277. exit;
  278. } else {
  279. $db->rollback();
  280. }
  281. }
  282. if ($box == 0) {
  283. setEventMessages($langs->trans('SelectProductWithNotNullQty'), null, 'warnings');
  284. }
  285. }
  286. /*
  287. * View
  288. */
  289. $form = new Form($db);
  290. $formproduct = new FormProduct($db);
  291. $prod = new Product($db);
  292. $title = $langs->trans('MissingStocks');
  293. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  294. $sqldesiredtock = $db->ifsql("pse.desiredstock IS NULL", "p.desiredstock", "pse.desiredstock");
  295. $sqlalertstock = $db->ifsql("pse.seuil_stock_alerte IS NULL", "p.seuil_stock_alerte", "pse.seuil_stock_alerte");
  296. } else {
  297. $sqldesiredtock = 'p.desiredstock';
  298. $sqlalertstock = 'p.seuil_stock_alerte';
  299. }
  300. $sql = 'SELECT p.rowid, p.ref, p.label, p.description, p.price,';
  301. $sql .= ' p.price_ttc, p.price_base_type, p.fk_product_type,';
  302. $sql .= ' p.tms as datem, p.duration, p.tobuy,';
  303. $sql .= ' p.desiredstock, p.seuil_stock_alerte,';
  304. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  305. $sql .= ' pse.desiredstock as desiredstockpse, pse.seuil_stock_alerte as seuil_stock_alertepse,';
  306. }
  307. $sql .= " ".$sqldesiredtock." as desiredstockcombined, ".$sqlalertstock." as seuil_stock_alertecombined,";
  308. $sql .= ' s.fk_product,';
  309. $sql .= " SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").') as stock_physique';
  310. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  311. $sql .= ", SUM(".$db->ifsql("s.reel IS NULL OR s.fk_entrepot <> ".$fk_entrepot, "0", "s.reel").') as stock_real_warehouse';
  312. }
  313. // Add fields from hooks
  314. $parameters = array();
  315. $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
  316. $sql .= $hookmanager->resPrint;
  317. $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
  318. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s ON p.rowid = s.fk_product';
  319. $list_warehouse = (empty($listofqualifiedwarehousesid) ? '0' : $listofqualifiedwarehousesid);
  320. $sql .= ' AND s.fk_entrepot IN ('.$db->sanitize($list_warehouse) .')';
  321. //$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot AS ent ON s.fk_entrepot = ent.rowid AND ent.entity IN('.getEntity('stock').')';
  322. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  323. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_warehouse_properties AS pse ON (p.rowid = pse.fk_product AND pse.fk_entrepot = '.((int) $fk_entrepot).')';
  324. }
  325. // Add fields from hooks
  326. $parameters = array();
  327. $reshook = $hookmanager->executeHooks('printFieldListJoin', $parameters); // Note that $action and $object may have been modified by hook
  328. $sql .= $hookmanager->resPrint;
  329. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  330. if ($sall) {
  331. $sql .= natural_search(array('p.ref', 'p.label', 'p.description', 'p.note'), $sall);
  332. }
  333. // if the type is not 1, we show all products (type = 0,2,3)
  334. if (dol_strlen($type)) {
  335. if ($type == 1) {
  336. $sql .= ' AND p.fk_product_type = 1';
  337. } else {
  338. $sql .= ' AND p.fk_product_type <> 1';
  339. }
  340. }
  341. if ($search_ref) {
  342. $sql .= natural_search('p.ref', $search_ref);
  343. }
  344. if ($search_label) {
  345. $sql .= natural_search('p.label', $search_label);
  346. }
  347. $sql .= ' AND p.tobuy = 1';
  348. if (!empty($conf->variants->eabled) && !getDolGlobalString('VARIANT_ALLOW_STOCK_MOVEMENT_ON_VARIANT_PARENT')) { // Add test to exclude products that has variants
  349. $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').'))';
  350. }
  351. if ($fk_supplier > 0) {
  352. $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').'))';
  353. }
  354. // Add where from hooks
  355. $parameters = array();
  356. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
  357. $sql .= $hookmanager->resPrint;
  358. $sql .= ' GROUP BY p.rowid, p.ref, p.label, p.description, p.price';
  359. $sql .= ', p.price_ttc, p.price_base_type,p.fk_product_type, p.tms';
  360. $sql .= ', p.duration, p.tobuy';
  361. $sql .= ', p.desiredstock';
  362. $sql .= ', p.seuil_stock_alerte';
  363. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  364. $sql .= ', pse.desiredstock';
  365. $sql .= ', pse.seuil_stock_alerte';
  366. }
  367. $sql .= ', s.fk_product';
  368. if ($usevirtualstock) {
  369. if (isModEnabled('commande')) {
  370. $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
  371. $sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd1, ".MAIN_DB_PREFIX."commande as c1";
  372. $sqlCommandesCli .= " WHERE c1.rowid = cd1.fk_commande AND c1.entity IN (".getEntity(getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'commande').")";
  373. $sqlCommandesCli .= " AND cd1.fk_product = p.rowid";
  374. $sqlCommandesCli .= " AND c1.fk_statut IN (1,2))";
  375. } else {
  376. $sqlCommandesCli = '0';
  377. }
  378. if (isModEnabled("expedition")) {
  379. $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
  380. $sqlExpeditionsCli .= " FROM ".MAIN_DB_PREFIX."expedition as e2,";
  381. $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."expeditiondet as ed2,";
  382. $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."commande as c2,";
  383. $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."commandedet as cd2";
  384. $sqlExpeditionsCli .= " WHERE ed2.fk_expedition = e2.rowid AND cd2.rowid = ed2.fk_origin_line AND e2.entity IN (".getEntity(getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'expedition').")";
  385. $sqlExpeditionsCli .= " AND cd2.fk_commande = c2.rowid";
  386. $sqlExpeditionsCli .= " AND c2.fk_statut IN (1,2)";
  387. $sqlExpeditionsCli .= " AND cd2.fk_product = p.rowid";
  388. $sqlExpeditionsCli .= " AND e2.fk_statut IN (1,2))";
  389. } else {
  390. $sqlExpeditionsCli = '0';
  391. }
  392. if (isModEnabled("supplier_order")) {
  393. $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
  394. $sqlCommandesFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd3,";
  395. $sqlCommandesFourn .= " ".MAIN_DB_PREFIX."commande_fournisseur as c3";
  396. $sqlCommandesFourn .= " WHERE c3.rowid = cd3.fk_commande";
  397. $sqlCommandesFourn .= " AND c3.entity IN (".getEntity(getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'supplier_order').")";
  398. $sqlCommandesFourn .= " AND cd3.fk_product = p.rowid";
  399. $sqlCommandesFourn .= " AND c3.fk_statut IN (3,4))";
  400. $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
  401. $sqlReceptionFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf4,";
  402. $sqlReceptionFourn .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd4";
  403. $sqlReceptionFourn .= " WHERE fd4.fk_commande = cf4.rowid AND cf4.entity IN (".getEntity(getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'supplier_order').")";
  404. $sqlReceptionFourn .= " AND fd4.fk_product = p.rowid";
  405. $sqlReceptionFourn .= " AND cf4.fk_statut IN (3,4))";
  406. } else {
  407. $sqlCommandesFourn = '0';
  408. $sqlReceptionFourn = '0';
  409. }
  410. if (isModEnabled('mrp')) {
  411. $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
  412. $sqlProductionToConsume .= " FROM ".MAIN_DB_PREFIX."mrp_mo as mm5,";
  413. $sqlProductionToConsume .= " ".MAIN_DB_PREFIX."mrp_production as mp5";
  414. $sqlProductionToConsume .= " WHERE mm5.rowid = mp5.fk_mo AND mm5.entity IN (".getEntity(getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'mo').")";
  415. $sqlProductionToConsume .= " AND mp5.fk_product = p.rowid";
  416. $sqlProductionToConsume .= " AND mp5.role IN ('toconsume', 'consumed')";
  417. $sqlProductionToConsume .= " AND mm5.status IN (1,2))";
  418. $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
  419. $sqlProductionToProduce .= " FROM ".MAIN_DB_PREFIX."mrp_mo as mm5,";
  420. $sqlProductionToProduce .= " ".MAIN_DB_PREFIX."mrp_production as mp5";
  421. $sqlProductionToProduce .= " WHERE mm5.rowid = mp5.fk_mo AND mm5.entity IN (".getEntity(getDolGlobalString('STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE') ? 'stock' : 'mo').")";
  422. $sqlProductionToProduce .= " AND mp5.fk_product = p.rowid";
  423. $sqlProductionToProduce .= " AND mp5.role IN ('toproduce', 'produced')";
  424. $sqlProductionToProduce .= " AND mm5.status IN (1,2))";
  425. } else {
  426. $sqlProductionToConsume = '0';
  427. $sqlProductionToProduce = '0';
  428. }
  429. $sql .= ' HAVING (';
  430. $sql .= " (".$sqldesiredtock." >= 0 AND (".$sqldesiredtock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").')';
  431. $sql .= " - (".$sqlCommandesCli." - ".$sqlExpeditionsCli.") + (".$sqlCommandesFourn." - ".$sqlReceptionFourn.") + (".$sqlProductionToProduce." - ".$sqlProductionToConsume.")))";
  432. $sql .= ' OR';
  433. if ($includeproductswithoutdesiredqty == 'on') {
  434. $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").")";
  435. } else {
  436. $sql .= " (".$sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").')';
  437. }
  438. $sql .= " - (".$sqlCommandesCli." - ".$sqlExpeditionsCli.") + (".$sqlCommandesFourn." - ".$sqlReceptionFourn.") + (".$sqlProductionToProduce." - ".$sqlProductionToConsume.")))";
  439. $sql .= ")";
  440. if ($salert == 'on') { // Option to see when stock is lower than alert
  441. $sql .= ' AND (';
  442. if ($includeproductswithoutdesiredqty == 'on') {
  443. $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").")";
  444. } else {
  445. $sql .= $sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").")";
  446. }
  447. $sql .= " - (".$sqlCommandesCli." - ".$sqlExpeditionsCli.") + (".$sqlCommandesFourn." - ".$sqlReceptionFourn.") + (".$sqlProductionToProduce." - ".$sqlProductionToConsume."))";
  448. $sql .= ")";
  449. $alertchecked = 'checked';
  450. }
  451. } else {
  452. $sql .= ' HAVING (';
  453. $sql .= "(".$sqldesiredtock." >= 0 AND (".$sqldesiredtock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").")))";
  454. $sql .= ' OR';
  455. if ($includeproductswithoutdesiredqty == 'on') {
  456. $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").')))';
  457. } else {
  458. $sql .= " (".$sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").')))';
  459. }
  460. $sql .= ')';
  461. if ($salert == 'on') { // Option to see when stock is lower than alert
  462. $sql .= " AND (";
  463. if ($includeproductswithoutdesiredqty == 'on') {
  464. $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")."))";
  465. } else {
  466. $sql .= " ".$sqlalertstock." >= 0 AND (".$sqlalertstock." > SUM(".$db->ifsql("s.reel IS NULL", "0", "s.reel").'))';
  467. }
  468. $sql .= ')';
  469. $alertchecked = 'checked';
  470. }
  471. }
  472. $includeproductswithoutdesiredqtychecked = '';
  473. if ($includeproductswithoutdesiredqty == 'on') {
  474. $includeproductswithoutdesiredqtychecked = 'checked';
  475. }
  476. $nbtotalofrecords = '';
  477. if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
  478. $result = $db->query($sql);
  479. $nbtotalofrecords = $db->num_rows($result);
  480. if (($page * $limit) > $nbtotalofrecords) {
  481. $page = 0;
  482. $offset = 0;
  483. }
  484. }
  485. $sql .= $db->order($sortfield, $sortorder);
  486. $sql .= $db->plimit($limit + 1, $offset);
  487. //print $sql;
  488. $resql = $db->query($sql);
  489. if (empty($resql)) {
  490. dol_print_error($db);
  491. exit;
  492. }
  493. $num = $db->num_rows($resql);
  494. $i = 0;
  495. $helpurl = 'EN:Module_Stocks_En|FR:Module_Stock|';
  496. $helpurl .= 'ES:M&oacute;dulo_Stocks';
  497. llxHeader('', $title, $helpurl, '');
  498. $head = array();
  499. $head[0][0] = DOL_URL_ROOT.'/product/stock/replenish.php';
  500. $head[0][1] = $title;
  501. $head[0][2] = 'replenish';
  502. $head[1][0] = DOL_URL_ROOT.'/product/stock/replenishorders.php';
  503. $head[1][1] = $langs->trans("ReplenishmentOrders");
  504. $head[1][2] = 'replenishorders';
  505. print load_fiche_titre($langs->trans('Replenishment'), '', 'stock');
  506. print dol_get_fiche_head($head, 'replenish', '', -1, '');
  507. print '<span class="opacitymedium">'.$langs->trans("ReplenishmentStatusDesc").'</span>'."\n";
  508. //$link = '<a title=' .$langs->trans("MenuNewWarehouse"). ' href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create">'.$langs->trans("MenuNewWarehouse").'</a>';
  509. if (empty($fk_entrepot) && getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE')) {
  510. print '<span class="opacitymedium">'.$langs->trans("ReplenishmentStatusDescPerWarehouse").'</span>'."\n";
  511. }
  512. print '<br><br>';
  513. if ($usevirtualstock == 1) {
  514. print $langs->trans("CurentSelectionMode").': ';
  515. print '<span class="a-mesure">'.$langs->trans("UseVirtualStock").'</span>';
  516. 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>';
  517. print '<br>';
  518. }
  519. if ($usevirtualstock == 0) {
  520. print $langs->trans("CurentSelectionMode").': ';
  521. 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>';
  522. print ' <span class="a-mesure">'.$langs->trans("UsePhysicalStock").'</span>';
  523. print '<br>';
  524. }
  525. print '<br>'."\n";
  526. print '<form name="formFilterWarehouse" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  527. print '<input type="hidden" name="token" value="'.newToken().'">';
  528. print '<input type="hidden" name="action" value="filter">';
  529. print '<input type="hidden" name="search_ref" value="'.$search_ref.'">';
  530. print '<input type="hidden" name="search_label" value="'.$search_label.'">';
  531. print '<input type="hidden" name="salert" value="'.$salert.'">';
  532. print '<input type="hidden" name="includeproductswithoutdesiredqty" value="'.$includeproductswithoutdesiredqty.'">';
  533. print '<input type="hidden" name="draftorder" value="'.$draftorder.'">';
  534. print '<input type="hidden" name="mode" value="'.$mode.'">';
  535. if ($limit > 0 && $limit != $conf->liste_limit) {
  536. print '<input type="hidden" name="limit" value="'.$limit.'">';
  537. }
  538. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE')) {
  539. print '<div class="inline-block valignmiddle" style="padding-right: 20px;">';
  540. print $langs->trans('Warehouse').' '.$formproduct->selectWarehouses($fk_entrepot, 'fk_entrepot', '', 1);
  541. print '</div>';
  542. }
  543. print '<div class="inline-block valignmiddle" style="padding-right: 20px;">';
  544. $filter = '(fournisseur:=:1)';
  545. print $langs->trans('Supplier').' '.$form->select_company($fk_supplier, 'fk_supplier', $filter, 1);
  546. print '</div>';
  547. $parameters = array();
  548. $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook
  549. if (empty($reshook)) {
  550. print $hookmanager->resPrint;
  551. }
  552. print '<div class="inline-block valignmiddle">';
  553. print '<input type="submit" class="button smallpaddingimp" name="valid" value="'.$langs->trans('ToFilter').'">';
  554. print '</div>';
  555. print '</form>';
  556. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formulaire">';
  557. print '<input type="hidden" name="token" value="'.newToken().'">';
  558. print '<input type="hidden" name="fk_supplier" value="'.$fk_supplier.'">';
  559. print '<input type="hidden" name="fk_entrepot" value="'.$fk_entrepot.'">';
  560. print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
  561. print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
  562. print '<input type="hidden" name="type" value="'.$type.'">';
  563. print '<input type="hidden" name="linecount" value="'.$num.'">';
  564. print '<input type="hidden" name="action" value="order">';
  565. print '<input type="hidden" name="mode" value="'.$mode.'">';
  566. if ($search_ref || $search_label || $sall || $salert || $draftorder || GETPOST('search', 'alpha')) {
  567. $filters = '&search_ref='.urlencode($search_ref).'&search_label='.urlencode($search_label);
  568. $filters .= '&sall='.urlencode($sall);
  569. $filters .= '&salert='.urlencode($salert);
  570. $filters .= '&draftorder='.urlencode($draftorder);
  571. $filters .= '&mode='.urlencode($mode);
  572. if ($fk_supplier > 0) {
  573. $filters .= '&fk_supplier='.urlencode($fk_supplier);
  574. }
  575. if ($fk_entrepot > 0) {
  576. $filters .= '&fk_entrepot='.urlencode($fk_entrepot);
  577. }
  578. } else {
  579. $filters = '&search_ref='.urlencode($search_ref).'&search_label='.urlencode($search_label);
  580. $filters .= '&fourn_id='.urlencode($fourn_id);
  581. $filters .= (isset($type) ? '&type='.urlencode($type) : '');
  582. $filters .= '&='.urlencode($salert);
  583. $filters .= '&draftorder='.urlencode($draftorder);
  584. $filters .= '&mode='.urlencode($mode);
  585. if ($fk_supplier > 0) {
  586. $filters .= '&fk_supplier='.urlencode($fk_supplier);
  587. }
  588. if ($fk_entrepot > 0) {
  589. $filters .= '&fk_entrepot='.urlencode($fk_entrepot);
  590. }
  591. }
  592. if ($limit > 0 && $limit != $conf->liste_limit) {
  593. $filters .= '&limit='.((int) $limit);
  594. }
  595. if (!empty($includeproductswithoutdesiredqty)) {
  596. $filters .= '&includeproductswithoutdesiredqty='.urlencode($includeproductswithoutdesiredqty);
  597. }
  598. if (!empty($salert)) {
  599. $filters .= '&salert='.urlencode($salert);
  600. }
  601. $param = (isset($type) ? '&type='.urlencode($type) : '');
  602. $param .= '&fourn_id='.urlencode($fourn_id).'&search_label='.urlencode($search_label).'&includeproductswithoutdesiredqty='.urlencode($includeproductswithoutdesiredqty).'&salert='.urlencode($salert).'&draftorder='.urlencode($draftorder);
  603. $param .= '&search_ref='.urlencode($search_ref);
  604. $param .= '&mode='.urlencode($mode);
  605. $param .= '&fk_supplier='.urlencode($fk_supplier);
  606. $param .= '&fk_entrepot='.urlencode($fk_entrepot);
  607. if (!empty($includeproductswithoutdesiredqty)) {
  608. $param .= '&includeproductswithoutdesiredqty='.urlencode($includeproductswithoutdesiredqty);
  609. }
  610. if (!empty($salert)) {
  611. $param .= '&salert='.urlencode($salert);
  612. }
  613. $stocklabel = $langs->trans('Stock');
  614. $stocklabelbis = $langs->trans('Stock');
  615. $stocktooltip = '';
  616. if ($usevirtualstock == 1) {
  617. $stocklabel = $langs->trans('VirtualStock');
  618. $stocktooltip = $langs->trans("VirtualStockDesc");
  619. }
  620. if ($usevirtualstock == 0) {
  621. $stocklabel = $langs->trans('PhysicalStock');
  622. }
  623. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  624. $stocklabelbis = $stocklabel.' (Selected warehouse)';
  625. $stocklabel .= ' ('.$langs->trans("AllWarehouses").')';
  626. }
  627. $texte = $langs->trans('Replenishment');
  628. print '<br>';
  629. if (getDolGlobalString('REPLENISH_ALLOW_VARIABLESIZELIST')) {
  630. print_barre_liste(
  631. $texte,
  632. $page,
  633. 'replenish.php',
  634. $filters,
  635. $sortfield,
  636. $sortorder,
  637. '',
  638. $num,
  639. $nbtotalofrecords,
  640. '',
  641. 0,
  642. '',
  643. '',
  644. $limit
  645. );
  646. } else {
  647. print_barre_liste(
  648. $texte,
  649. $page,
  650. 'replenish.php',
  651. $filters,
  652. $sortfield,
  653. $sortorder,
  654. '',
  655. $num,
  656. $nbtotalofrecords,
  657. ''
  658. );
  659. }
  660. print '<div class="div-table-responsive-no-min">';
  661. print '<table class="liste centpercent">';
  662. // Fields title search
  663. print '<tr class="liste_titre_filter">';
  664. print '<td class="liste_titre">&nbsp;</td>';
  665. print '<td class="liste_titre"><input class="flat" type="text" name="search_ref" size="8" value="'.dol_escape_htmltag($search_ref).'"></td>';
  666. print '<td class="liste_titre"><input class="flat" type="text" name="search_label" size="8" value="'.dol_escape_htmltag($search_label).'"></td>';
  667. if (isModEnabled("service") && $type == 1) {
  668. print '<td class="liste_titre">&nbsp;</td>';
  669. }
  670. 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>';
  671. print '<td class="liste_titre right"></td>';
  672. print '<td class="liste_titre right">'.$langs->trans('AlertOnly').'&nbsp;<input type="checkbox" id="salert" name="salert" '.(!empty($alertchecked) ? $alertchecked : '').'></td>';
  673. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  674. print '<td class="liste_titre">&nbsp;</td>';
  675. }
  676. print '<td class="liste_titre right">';
  677. if (getDolGlobalString('STOCK_REPLENISH_ADD_CHECKBOX_INCLUDE_DRAFT_ORDER')) {
  678. print $langs->trans('IncludeAlsoDraftOrders').'&nbsp;<input type="checkbox" id="draftorder" name="draftorder" '.(!empty($draftchecked) ? $draftchecked : '').'>';
  679. }
  680. print '</td>';
  681. print '<td class="liste_titre">&nbsp;</td>';
  682. // Fields from hook
  683. $parameters = array('param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
  684. $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook
  685. print $hookmanager->resPrint;
  686. print '<td class="liste_titre maxwidthsearch right">';
  687. $searchpicto = $form->showFilterAndCheckAddButtons(0);
  688. print $searchpicto;
  689. print '</td>';
  690. print '</tr>';
  691. // Lines of title
  692. print '<tr class="liste_titre">';
  693. print_liste_field_titre('<input type="checkbox" onClick="toggle(this)" />', $_SERVER["PHP_SELF"], '');
  694. print_liste_field_titre('ProductRef', $_SERVER["PHP_SELF"], 'p.ref', $param, '', '', $sortfield, $sortorder);
  695. print_liste_field_titre('Label', $_SERVER["PHP_SELF"], 'p.label', $param, '', '', $sortfield, $sortorder);
  696. if (isModEnabled("service") && $type == 1) {
  697. print_liste_field_titre('Duration', $_SERVER["PHP_SELF"], 'p.duration', $param, '', '', $sortfield, $sortorder, 'center ');
  698. }
  699. print_liste_field_titre('DesiredStock', $_SERVER["PHP_SELF"], 'p.desiredstock', $param, '', '', $sortfield, $sortorder, 'right ');
  700. print_liste_field_titre('StockLimitShort', $_SERVER["PHP_SELF"], 'p.seuil_stock_alerte', $param, '', '', $sortfield, $sortorder, 'right ');
  701. print_liste_field_titre($stocklabel, $_SERVER["PHP_SELF"], 'stock_physique', $param, '', '', $sortfield, $sortorder, 'right ', $stocktooltip);
  702. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  703. print_liste_field_titre($stocklabelbis, $_SERVER["PHP_SELF"], 'stock_real_warehouse', $param, '', '', $sortfield, $sortorder, 'right ');
  704. }
  705. print_liste_field_titre('Ordered', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
  706. print_liste_field_titre('StockToBuy', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
  707. print_liste_field_titre('SupplierRef', $_SERVER["PHP_SELF"], '', $param, '', '', $sortfield, $sortorder, 'right ');
  708. // Hook fields
  709. $parameters = array('param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
  710. $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook
  711. print $hookmanager->resPrint;
  712. print "</tr>\n";
  713. while ($i < ($limit ? min($num, $limit) : $num)) {
  714. $objp = $db->fetch_object($resql);
  715. if (getDolGlobalString('STOCK_SUPPORTS_SERVICES') || $objp->fk_product_type == 0) {
  716. $result = $prod->fetch($objp->rowid);
  717. if ($result < 0) {
  718. dol_print_error($db);
  719. exit;
  720. }
  721. $prod->load_stock('warehouseopen, warehouseinternal'.(!$usevirtualstock ? ', novirtual' : ''), $draftchecked);
  722. // Multilangs
  723. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  724. $sql = 'SELECT label,description';
  725. $sql .= ' FROM '.MAIN_DB_PREFIX.'product_lang';
  726. $sql .= ' WHERE fk_product = '.((int) $objp->rowid);
  727. $sql .= " AND lang = '".$db->escape($langs->getDefaultLang())."'";
  728. $sql .= ' LIMIT 1';
  729. $resqlm = $db->query($sql);
  730. if ($resqlm) {
  731. $objtp = $db->fetch_object($resqlm);
  732. if (!empty($objtp->description)) {
  733. $objp->description = $objtp->description;
  734. }
  735. if (!empty($objtp->label)) {
  736. $objp->label = $objtp->label;
  737. }
  738. }
  739. }
  740. $stockwarehouse = 0;
  741. if ($usevirtualstock) {
  742. // If option to increase/decrease is not on an object validation, virtual stock may differs from physical stock.
  743. $stock = $prod->stock_theorique;
  744. //TODO $stockwarehouse = $prod->stock_warehouse[$fk_entrepot]->;
  745. } else {
  746. $stock = $prod->stock_reel;
  747. $stockwarehouse = $prod->stock_warehouse[$fk_entrepot]->real;
  748. }
  749. // Force call prod->load_stats_xxx to choose status to count (otherwise it is loaded by load_stock function)
  750. if (isset($draftchecked)) {
  751. $result = $prod->load_stats_commande_fournisseur(0, '0,1,2,3,4');
  752. } elseif (!$usevirtualstock) {
  753. $result = $prod->load_stats_commande_fournisseur(0, '1,2,3,4');
  754. }
  755. if (!$usevirtualstock) {
  756. $result = $prod->load_stats_reception(0, '4');
  757. }
  758. //print $prod->stats_commande_fournisseur['qty'].'<br>'."\n";
  759. //print $prod->stats_reception['qty'];
  760. $ordered = $prod->stats_commande_fournisseur['qty'] - $prod->stats_reception['qty'];
  761. $desiredstock = $objp->desiredstock;
  762. $alertstock = $objp->seuil_stock_alerte;
  763. $desiredstockwarehouse = (!empty($objp->desiredstockpse) ? $objp->desiredstockpse : 0);
  764. $alertstockwarehouse = (!empty($objp->seuil_stock_alertepse) ? $objp->seuil_stock_alertepse : 0);
  765. $warning = '';
  766. if ($alertstock && ($stock < $alertstock)) {
  767. $warning = img_warning($langs->trans('StockTooLow')).' ';
  768. }
  769. $warningwarehouse = '';
  770. if ($alertstockwarehouse && ($stockwarehouse < $alertstockwarehouse)) {
  771. $warningwarehouse = img_warning($langs->trans('StockTooLow')).' ';
  772. }
  773. //depending on conf, use either physical stock or
  774. //virtual stock to compute the stock to buy value
  775. if (empty($usevirtualstock)) {
  776. $stocktobuy = max(max($desiredstock, $alertstock) - $stock - $ordered, 0);
  777. } else {
  778. $stocktobuy = max(max($desiredstock, $alertstock) - $stock, 0); //ordered is already in $stock in virtual mode
  779. }
  780. if (empty($usevirtualstock)) {
  781. $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse - $ordered, 0);
  782. } else {
  783. $stocktobuywarehouse = max(max($desiredstockwarehouse, $alertstockwarehouse) - $stockwarehouse, 0); //ordered is already in $stock in virtual mode
  784. }
  785. $picto = '';
  786. if ($ordered > 0) {
  787. $stockforcompare = ($usevirtualstock ? $stock : $stock + $ordered);
  788. /*if ($stockforcompare >= $desiredstock)
  789. {
  790. $picto = img_picto('', 'help');
  791. } else {
  792. $picto = img_picto('', 'help');
  793. }*/
  794. } else {
  795. $picto = img_picto($langs->trans("NoPendingReceptionOnSupplierOrder"), 'help');
  796. }
  797. print '<tr class="oddeven">';
  798. // Select field
  799. print '<td><input type="checkbox" class="check" name="choose'.$i.'"></td>';
  800. print '<td class="nowrap">'.$prod->getNomUrl(1, 'stock').'</td>';
  801. print '<td class="tdoverflowmax200" title="'.dol_escape_htmltag($objp->label).'">';
  802. print dol_escape_htmltag($objp->label);
  803. 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
  804. print '</td>';
  805. if (isModEnabled("service") && $type == 1) {
  806. $regs = array();
  807. if (preg_match('/([0-9]+)y/i', $objp->duration, $regs)) {
  808. $duration = $regs[1].' '.$langs->trans('DurationYear');
  809. } elseif (preg_match('/([0-9]+)m/i', $objp->duration, $regs)) {
  810. $duration = $regs[1].' '.$langs->trans('DurationMonth');
  811. } elseif (preg_match('/([0-9]+)d/i', $objp->duration, $regs)) {
  812. $duration = $regs[1].' '.$langs->trans('DurationDay');
  813. } else {
  814. $duration = $objp->duration;
  815. }
  816. print '<td class="center">'.$duration.'</td>';
  817. }
  818. // Desired stock
  819. print '<td class="right">'.((getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) > 0 ? $desiredstockwarehouse : $desiredstock).'</td>';
  820. // Limit stock for alert
  821. print '<td class="right">'.((getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) > 0 ? $alertstockwarehouse : $alertstock).'</td>';
  822. // Current stock (all warehouses)
  823. print '<td class="right">'.$warning.$stock;
  824. print '<!-- stock returned by main sql is '.$objp->stock_physique.' -->';
  825. print '</td>';
  826. // Current stock (warehouse selected only)
  827. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  828. print '<td class="right">'.$warningwarehouse.$stockwarehouse.'</td>';
  829. }
  830. // Already ordered
  831. print '<td class="right"><a href="replenishorders.php?search_product='.$prod->id.'">'.$ordered.'</a> '.$picto.'</td>';
  832. // To order
  833. print '<td class="right"><input type="text" size="4" name="tobuy'.$i.'" value="'.((getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) > 0 ? $stocktobuywarehouse : $stocktobuy).'"></td>';
  834. // Supplier
  835. print '<td class="right">';
  836. print $form->select_product_fourn_price($prod->id, 'fourn'.$i, $fk_supplier);
  837. print '</td>';
  838. // Fields from hook
  839. $parameters = array('objp'=>$objp);
  840. $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook
  841. print $hookmanager->resPrint;
  842. print '</tr>';
  843. }
  844. $i++;
  845. }
  846. if ($num == 0) {
  847. $colspan = 9;
  848. if (isModEnabled("service") && $type == 1) {
  849. $colspan++;
  850. }
  851. if (getDolGlobalString('STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE') && $fk_entrepot > 0) {
  852. $colspan++;
  853. }
  854. print '<tr><td colspan="'.$colspan.'">';
  855. print '<span class="opacitymedium">';
  856. print $langs->trans("None");
  857. print '</span>';
  858. print '</td></tr>';
  859. }
  860. $parameters = array('sql'=>$sql);
  861. $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook
  862. print $hookmanager->resPrint;
  863. print '</table>';
  864. print '</div>';
  865. $db->free($resql);
  866. print dol_get_fiche_end();
  867. $value = $langs->trans("CreateOrders");
  868. print '<div class="center"><input type="submit" class="button" name="valid" value="'.$value.'"></div>';
  869. print '</form>';
  870. // TODO Replace this with jquery
  871. print '
  872. <script type="text/javascript">
  873. function toggle(source)
  874. {
  875. checkboxes = document.getElementsByClassName("check");
  876. for (var i=0; i < checkboxes.length;i++) {
  877. if (!checkboxes[i].disabled) {
  878. checkboxes[i].checked = source.checked;
  879. }
  880. }
  881. }
  882. </script>';
  883. llxFooter();
  884. $db->close();