replenish.php 40 KB

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