replenish.php 41 KB

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