PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/controllers/admin/AdminStockManagementController.php

https://github.com/netplayer/PrestaShop
PHP | 1181 lines | 923 code | 109 blank | 149 comment | 113 complexity | 5d3f7cf3a497c908ad065cdf5f4573f8 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1, LGPL-3.0
  1. <?php
  2. /*
  3. * 2007-2014 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2014 PrestaShop SA
  23. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. /**
  27. * @since 1.5.0
  28. */
  29. class AdminStockManagementControllerCore extends AdminController
  30. {
  31. public function __construct()
  32. {
  33. $this->bootstrap = true;
  34. $this->context = Context::getContext();
  35. $this->table = 'product';
  36. $this->list_id = 'product';
  37. $this->className = 'Product';
  38. $this->lang = true;
  39. $this->multishop_context = Shop::CONTEXT_ALL;
  40. $this->fields_list = array(
  41. 'reference' => array(
  42. 'title' => $this->l('Product reference'),
  43. 'filter_key' => 'a!reference'
  44. ),
  45. 'ean13' => array(
  46. 'title' => $this->l('EAN-13 or JAN barcode'),
  47. 'filter_key' => 'a!ean13'
  48. ),
  49. 'upc' => array(
  50. 'title' => $this->l('UPC barcode'),
  51. 'filter_key' => 'a!upc'
  52. ),
  53. 'name' => array(
  54. 'title' => $this->l('Name')
  55. ),
  56. 'stock' => array(
  57. 'title' => $this->l('Quantity'),
  58. 'orderby' => false,
  59. 'filter' => false,
  60. 'search' => false,
  61. 'class' => 'fixed-width-sm',
  62. 'align' => 'center',
  63. 'hint' => $this->l('Quantity total for all warehouses.')
  64. ),
  65. );
  66. parent::__construct();
  67. // overrides confirmation messages specifically for this controller
  68. $this->_conf = array(
  69. 1 => $this->l('The product was successfully added to your stock.'),
  70. 2 => $this->l('The product was successfully removed from your stock.'),
  71. 3 => $this->l('The transfer was successfully completed.'),
  72. );
  73. }
  74. public function initPageHeaderToolbar()
  75. {
  76. if ($this->display == 'details')
  77. $this->page_header_toolbar_btn['back_to_list'] = array(
  78. 'href' => Context::getContext()->link->getAdminLink('AdminStockManagement'),
  79. 'desc' => $this->l('Back to list', null, null, false),
  80. 'icon' => 'process-icon-back'
  81. );
  82. parent::initPageHeaderToolbar();
  83. }
  84. /**
  85. * AdminController::renderList() override
  86. * @see AdminController::renderList()
  87. */
  88. public function renderList()
  89. {
  90. // sets actions
  91. $this->addRowAction('details');
  92. $this->addRowAction('addstock');
  93. $this->addRowAction('removestock');
  94. if (count(Warehouse::getWarehouses()) > 1)
  95. $this->addRowAction('transferstock');
  96. // no link on list rows
  97. $this->list_no_link = true;
  98. // inits toolbar
  99. $this->toolbar_btn = array();
  100. // overrides query
  101. $this->_select = 'a.id_product as id, COUNT(pa.id_product_attribute) as variations';
  102. $this->_join = 'LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (pa.id_product = a.id_product)'.Shop::addSqlAssociation('product_attribute', 'pa', false);
  103. $this->_where = 'AND a.cache_is_pack = 0 AND a.is_virtual = 0';
  104. $this->_group = 'GROUP BY a.id_product';
  105. // displays informations
  106. $this->displayInformation($this->l('This interface allows you to manage product stock and their variations.').'<br />');
  107. $this->displayInformation($this->l('Through this interface, you can increase and decrease product stock for an given warehouse.'));
  108. $this->displayInformation($this->l('Furthermore, you can move product quantities between warehouses, or within one warehouse.').'<br />');
  109. $this->displayInformation($this->l('If you want to increase quantities of multiple products at once, you can use the "Supply orders" page under the "Stock" menu.').'<br />');
  110. $this->displayInformation($this->l('Finally, you need to provide the quantity that you\'ll be adding: "Usable for sale" means that this quantity will be available in your shop(s), otherwise it will be considered reserved (i.e. for other purposes).'));
  111. return parent::renderList();
  112. }
  113. /**
  114. * AdminController::renderForm() override
  115. * @see AdminController::renderForm()
  116. */
  117. public function renderForm()
  118. {
  119. // gets the product
  120. $id_product = (int)Tools::getValue('id_product');
  121. $id_product_attribute = (int)Tools::getValue('id_product_attribute');
  122. // gets warehouses
  123. $warehouses_add = Warehouse::getWarehouses(true);
  124. $warehouses_remove = Warehouse::getWarehousesByProductId($id_product, $id_product_attribute);
  125. // displays warning if no warehouses
  126. if (!$warehouses_add)
  127. $this->displayWarning($this->l('You must choose a warehouses before adding stock. See Stock/Warehouses.'));
  128. //get currencies list
  129. $currencies = Currency::getCurrencies();
  130. $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT');
  131. $default_currency = Currency::getCurrency($id_default_currency);
  132. if ($default_currency)
  133. $currencies = array_merge(array($default_currency, '-'), $currencies);
  134. // switch, in order to display the form corresponding to the current action
  135. switch ($this->display)
  136. {
  137. case 'addstock' :
  138. // gets the last stock mvt for this product, so we can display the last unit price te and the last quantity added
  139. $last_sm_unit_price_te = $this->l('N/A');
  140. $last_sm_quantity = 0;
  141. $last_sm_quantity_is_usable = -1;
  142. $last_sm = StockMvt::getLastPositiveStockMvt($id_product, $id_product_attribute);
  143. // if there is a stock mvt
  144. if ($last_sm != false)
  145. {
  146. $last_sm_currency = new Currency((int)$last_sm['id_currency']);
  147. $last_sm_quantity = (int)$last_sm['physical_quantity'];
  148. $last_sm_quantity_is_usable = (int)$last_sm['is_usable'];
  149. if (Validate::isLoadedObject($last_sm_currency))
  150. $last_sm_unit_price_te = Tools::displayPrice((float)$last_sm['price_te'], $last_sm_currency);
  151. }
  152. $this->displayInformation($this->l('Moving the mouse cursor over the quantity and price fields will give you the details about the last stock movement.'));
  153. // fields in the form
  154. $this->fields_form[]['form'] = array(
  155. 'legend' => array(
  156. 'title' => $this->l('Add a product to your stock.'),
  157. 'icon' => 'icon-long-arrow-up'
  158. ),
  159. 'input' => array(
  160. array(
  161. 'type' => 'hidden',
  162. 'name' => 'is_post',
  163. ),
  164. array(
  165. 'type' => 'hidden',
  166. 'name' => 'id_product',
  167. ),
  168. array(
  169. 'type' => 'hidden',
  170. 'name' => 'id_product_attribute',
  171. ),
  172. array(
  173. 'type' => 'hidden',
  174. 'name' => 'check',
  175. ),
  176. array(
  177. 'type' => 'text',
  178. 'label' => $this->l('Product reference'),
  179. 'name' => 'reference',
  180. 'disabled' => true,
  181. ),
  182. array(
  183. 'type' => 'text',
  184. 'label' => $this->l('EAN-13 or JAN barcode'),
  185. 'name' => 'ean13',
  186. 'disabled' => true,
  187. ),
  188. array(
  189. 'type' => 'text',
  190. 'label' => $this->l('UPC barcode'),
  191. 'name' => 'upc',
  192. 'disabled' => true,
  193. ),
  194. array(
  195. 'type' => 'text',
  196. 'label' => $this->l('Name'),
  197. 'name' => 'name',
  198. 'disabled' => true,
  199. ),
  200. array(
  201. 'type' => 'text',
  202. 'label' => $this->l('Quantity to add'),
  203. 'name' => 'quantity',
  204. 'maxlength' => 6,
  205. 'required' => true,
  206. 'hint' => array(
  207. $this->l('Indicate the physical quantity of this product that you want to add.'),
  208. $this->l('Last physical quantity added: %s items (usable for sale: %s).'),
  209. ($last_sm_quantity > 0 ? $last_sm_quantity : $this->l('N/A')),
  210. ($last_sm_quantity > 0 ? ($last_sm_quantity_is_usable >= 0 ? $this->l('Yes') : $this->l('No')) : $this->l('N/A'))),
  211. ),
  212. array(
  213. 'type' => 'switch',
  214. 'label' => $this->l('Usable for sale?'),
  215. 'name' => 'usable',
  216. 'required' => true,
  217. 'is_bool' => true,
  218. 'values' => array(
  219. array(
  220. 'id' => 'active_on',
  221. 'value' => 1,
  222. 'label' => $this->l('Enabled')
  223. ),
  224. array(
  225. 'id' => 'active_off',
  226. 'value' => 0,
  227. 'label' => $this->l('Disabled')
  228. )
  229. ),
  230. 'hint' => $this->l('Is this quantity ready to be displayed in your shop, or is it reserved in the warehouse for other purposes?')
  231. ),
  232. array(
  233. 'type' => 'select',
  234. 'label' => $this->l('Warehouse'),
  235. 'name' => 'id_warehouse',
  236. 'required' => true,
  237. 'options' => array(
  238. 'query' => $warehouses_add,
  239. 'id' => 'id_warehouse',
  240. 'name' => 'name'
  241. ),
  242. 'hint' => $this->l('Please select the warehouse that you\'ll be adding products to.')
  243. ),
  244. array(
  245. 'type' => 'text',
  246. 'label' => $this->l('Unit price (tax excl.)'),
  247. 'name' => 'price',
  248. 'required' => true,
  249. 'size' => 10,
  250. 'maxlength' => 10,
  251. 'hint' => array(
  252. $this->l('Unit purchase price or unit manufacturing cost for this product (tax excl.).'),
  253. sprintf($this->l('Last unit price (tax excl.): %s.'), $last_sm_unit_price_te),
  254. )
  255. ),
  256. array(
  257. 'type' => 'select',
  258. 'label' => $this->l('Currency'),
  259. 'name' => 'id_currency',
  260. 'required' => true,
  261. 'options' => array(
  262. 'query' => $currencies,
  263. 'id' => 'id_currency',
  264. 'name' => 'name'
  265. ),
  266. 'hint' => $this->l('The currency associated to the product unit price.'),
  267. ),
  268. array(
  269. 'type' => 'select',
  270. 'label' => $this->l('Label'),
  271. 'name' => 'id_stock_mvt_reason',
  272. 'required' => true,
  273. 'options' => array(
  274. 'query' => StockMvtReason::getStockMvtReasonsWithFilter($this->context->language->id,
  275. array(Configuration::get('PS_STOCK_MVT_TRANSFER_TO')),
  276. 1),
  277. 'id' => 'id_stock_mvt_reason',
  278. 'name' => 'name'
  279. ),
  280. 'hint' => $this->l('Label used in stock movements.'),
  281. ),
  282. ),
  283. 'submit' => array(
  284. 'title' => $this->l('Add to stock')
  285. )
  286. );
  287. $this->fields_value['usable'] = 1;
  288. break;
  289. case 'removestock' :
  290. $this->fields_form[]['form'] = array(
  291. 'legend' => array(
  292. 'title' => $this->l('Remove the product from your stock.'),
  293. 'icon' => 'icon-long-arrow-down'
  294. ),
  295. 'input' => array(
  296. array(
  297. 'type' => 'hidden',
  298. 'name' => 'is_post',
  299. ),
  300. array(
  301. 'type' => 'hidden',
  302. 'name' => 'id_product',
  303. ),
  304. array(
  305. 'type' => 'hidden',
  306. 'name' => 'id_product_attribute',
  307. ),
  308. array(
  309. 'type' => 'hidden',
  310. 'name' => 'check',
  311. ),
  312. array(
  313. 'type' => 'text',
  314. 'label' => $this->l('Product reference'),
  315. 'name' => 'reference',
  316. 'disabled' => true,
  317. ),
  318. array(
  319. 'type' => 'text',
  320. 'label' => $this->l('EAN-13 or JAN barcode'),
  321. 'name' => 'ean13',
  322. 'disabled' => true,
  323. ),
  324. array(
  325. 'type' => 'text',
  326. 'label' => $this->l('Name'),
  327. 'name' => 'name',
  328. 'disabled' => true,
  329. ),
  330. array(
  331. 'type' => 'text',
  332. 'label' => $this->l('Quantity to remove'),
  333. 'name' => 'quantity',
  334. 'maxlength' => 6,
  335. 'required' => true,
  336. 'hint' => $this->l('Indicate the physical quantity of this product that you want to remove.'),
  337. ),
  338. array(
  339. 'type' => 'switch',
  340. 'label' => $this->l('Usable for sale'),
  341. 'name' => 'usable',
  342. 'required' => true,
  343. 'is_bool' => true,
  344. 'values' => array(
  345. array(
  346. 'id' => 'active_on',
  347. 'value' => 1,
  348. 'label' => $this->l('Enabled')
  349. ),
  350. array(
  351. 'id' => 'active_off',
  352. 'value' => 0,
  353. 'label' => $this->l('Disabled')
  354. )
  355. ),
  356. 'hint' => $this->l('Do you want to remove this quantity from the usable quantity (yes) or the physical quantity (no)?')
  357. ),
  358. array(
  359. 'type' => 'select',
  360. 'label' => $this->l('Warehouse'),
  361. 'name' => 'id_warehouse',
  362. 'required' => true,
  363. 'options' => array(
  364. 'query' => $warehouses_remove,
  365. 'id' => 'id_warehouse',
  366. 'name' => 'name'
  367. ),
  368. 'hint' => $this->l('Select the warehouse you\'d like to remove the product from.')
  369. ),
  370. array(
  371. 'type' => 'select',
  372. 'label' => $this->l('Label'),
  373. 'name' => 'id_stock_mvt_reason',
  374. 'required' => true,
  375. 'options' => array(
  376. 'query' => StockMvtReason::getStockMvtReasonsWithFilter($this->context->language->id,
  377. array(Configuration::get('PS_STOCK_MVT_TRANSFER_FROM')),
  378. -1),
  379. 'id' => 'id_stock_mvt_reason',
  380. 'name' => 'name'
  381. ),
  382. 'hint' => $this->l('Label used in stock movements.'),
  383. ),
  384. ),
  385. 'submit' => array(
  386. 'title' => $this->l('Remove from stock')
  387. )
  388. );
  389. break;
  390. case 'transferstock' :
  391. $this->fields_form[]['form'] = array(
  392. 'legend' => array(
  393. 'title' => $this->l('Transfer a product from one warehouse to another'),
  394. 'icon' => 'icon-share-alt'
  395. ),
  396. 'input' => array(
  397. array(
  398. 'type' => 'hidden',
  399. 'name' => 'is_post',
  400. ),
  401. array(
  402. 'type' => 'hidden',
  403. 'name' => 'id_product',
  404. ),
  405. array(
  406. 'type' => 'hidden',
  407. 'name' => 'id_product_attribute',
  408. ),
  409. array(
  410. 'type' => 'hidden',
  411. 'name' => 'check',
  412. ),
  413. array(
  414. 'type' => 'text',
  415. 'label' => $this->l('Product reference'),
  416. 'name' => 'reference',
  417. 'disabled' => true,
  418. ),
  419. array(
  420. 'type' => 'text',
  421. 'label' => $this->l('EAN-13 or JAN barcode'),
  422. 'name' => 'ean13',
  423. 'disabled' => true,
  424. ),
  425. array(
  426. 'type' => 'text',
  427. 'label' => $this->l('Name'),
  428. 'name' => 'name',
  429. 'disabled' => true,
  430. ),
  431. array(
  432. 'type' => 'text',
  433. 'label' => $this->l('Quantity to transfer'),
  434. 'name' => 'quantity',
  435. 'maxlength' => 6,
  436. 'required' => true,
  437. 'hint' => $this->l('Indicate the physical quantity of this product that you want to transfer.')
  438. ),
  439. array(
  440. 'type' => 'select',
  441. 'label' => $this->l('Source warehouse'),
  442. 'name' => 'id_warehouse_from',
  443. 'required' => true,
  444. 'options' => array(
  445. 'query' => $warehouses_remove,
  446. 'id' => 'id_warehouse',
  447. 'name' => 'name'
  448. ),
  449. 'hint' => $this->l('Select the warehouse you\'d like to transfer the product from.')
  450. ),
  451. array(
  452. 'type' => 'switch',
  453. 'label' => $this->l('Is this product usable for sale in your source warehouse?'),
  454. 'name' => 'usable_from',
  455. 'required' => true,
  456. 'is_bool' => true,
  457. 'values' => array(
  458. array(
  459. 'id' => 'active_on',
  460. 'value' => 1,
  461. 'label' => $this->l('Yes')
  462. ),
  463. array(
  464. 'id' => 'active_off',
  465. 'value' => 0,
  466. 'label' => $this->l('No')
  467. )
  468. ),
  469. 'hint' => $this->l('Is this the usable quantity for sale?')
  470. ),
  471. array(
  472. 'type' => 'select',
  473. 'label' => $this->l('Destination warehouse'),
  474. 'name' => 'id_warehouse_to',
  475. 'required' => true,
  476. 'options' => array(
  477. 'query' => $warehouses_add,
  478. 'id' => 'id_warehouse',
  479. 'name' => 'name'
  480. ),
  481. 'hint' => $this->l('Select the warehouse you\'d like to transfer your product(s) to. ')
  482. ),
  483. array(
  484. 'type' => 'switch',
  485. 'label' => $this->l('Is this product usable for sale in your destination warehouse?'),
  486. 'name' => 'usable_to',
  487. 'required' => true,
  488. 'class' => 't',
  489. 'is_bool' => true,
  490. 'values' => array(
  491. array(
  492. 'id' => 'active_on',
  493. 'value' => 1,
  494. 'label' => $this->l('Yes')
  495. ),
  496. array(
  497. 'id' => 'active_off',
  498. 'value' => 0,
  499. 'label' => $this->l('No')
  500. )
  501. ),
  502. 'hint' => $this->l('Do you want it to be for sale/usable?')
  503. ),
  504. ),
  505. 'submit' => array(
  506. 'title' => $this->l('Transfer')
  507. )
  508. );
  509. break;
  510. }
  511. $this->initToolbar();
  512. }
  513. /**
  514. * AdminController::postProcess() override
  515. * @see AdminController::postProcess()
  516. */
  517. public function postProcess()
  518. {
  519. parent::postProcess();
  520. // Checks access
  521. if (Tools::isSubmit('addStock') && !($this->tabAccess['add'] === '1'))
  522. $this->errors[] = Tools::displayError('You do not have the required permission to add stock.');
  523. if (Tools::isSubmit('removeStock') && !($this->tabAccess['delete'] === '1'))
  524. $this->errors[] = Tools::displayError('You do not have the required permission to delete stock');
  525. if (Tools::isSubmit('transferStock') && !($this->tabAccess['edit'] === '1'))
  526. $this->errors[] = Tools::displayError('You do not have the required permission to transfer stock.');
  527. if (count($this->errors))
  528. return;
  529. // Global checks when add / remove / transfer product
  530. if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock') || Tools::isSubmit('transferstock') ) && Tools::isSubmit('is_post'))
  531. {
  532. // get product ID
  533. $id_product = (int)Tools::getValue('id_product', 0);
  534. if ($id_product <= 0)
  535. $this->errors[] = Tools::displayError('The selected product is not valid.');
  536. // get product_attribute ID
  537. $id_product_attribute = (int)Tools::getValue('id_product_attribute', 0);
  538. // check the product hash
  539. $check = Tools::getValue('check', '');
  540. $check_valid = md5(_COOKIE_KEY_.$id_product.$id_product_attribute);
  541. if ($check != $check_valid)
  542. $this->errors[] = Tools::displayError('The selected product is not valid.');
  543. // get quantity and check that the post value is really an integer
  544. // If it's not, we have nothing to do
  545. $quantity = Tools::getValue('quantity', 0);
  546. if (!is_numeric($quantity) || (int)$quantity <= 0)
  547. $this->errors[] = Tools::displayError('The quantity value is not valid.');
  548. $quantity = (int)$quantity;
  549. $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
  550. $redirect = self::$currentIndex.'&token='.$token;
  551. }
  552. // Global checks when add / remove product
  553. if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock') ) && Tools::isSubmit('is_post'))
  554. {
  555. // get warehouse id
  556. $id_warehouse = (int)Tools::getValue('id_warehouse', 0);
  557. if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse))
  558. $this->errors[] = Tools::displayError('The selected warehouse is not valid.');
  559. // get stock movement reason id
  560. $id_stock_mvt_reason = (int)Tools::getValue('id_stock_mvt_reason', 0);
  561. if ($id_stock_mvt_reason <= 0 || !StockMvtReason::exists($id_stock_mvt_reason))
  562. $this->errors[] = Tools::displayError('The reason is not valid.');
  563. // get usable flag
  564. $usable = Tools::getValue('usable', null);
  565. if (is_null($usable))
  566. $this->errors[] = Tools::displayError('You have to specify whether the product quantity is usable for sale on shops or not.');
  567. $usable = (bool)$usable;
  568. }
  569. if (Tools::isSubmit('addstock') && Tools::isSubmit('is_post'))
  570. {
  571. // get product unit price
  572. $price = str_replace(',', '.', Tools::getValue('price', 0));
  573. if (!is_numeric($price))
  574. $this->errors[] = Tools::displayError('The product price is not valid.');
  575. $price = round(floatval($price), 6);
  576. // get product unit price currency id
  577. $id_currency = (int)Tools::getValue('id_currency', 0);
  578. if ($id_currency <= 0 || ( !($result = Currency::getCurrency($id_currency)) || empty($result) ))
  579. $this->errors[] = Tools::displayError('The selected currency is not valid.');
  580. // if all is ok, add stock
  581. if (count($this->errors) == 0)
  582. {
  583. $warehouse = new Warehouse($id_warehouse);
  584. // convert price to warehouse currency if needed
  585. if ($id_currency != $warehouse->id_currency)
  586. {
  587. // First convert price to the default currency
  588. $price_converted_to_default_currency = Tools::convertPrice($price, $id_currency, false);
  589. // Convert the new price from default currency to needed currency
  590. $price = Tools::convertPrice($price_converted_to_default_currency, $warehouse->id_currency, true);
  591. }
  592. // add stock
  593. $stock_manager = StockManagerFactory::getManager();
  594. if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $usable))
  595. {
  596. StockAvailable::synchronize($id_product);
  597. if (Tools::isSubmit('addstockAndStay'))
  598. {
  599. $redirect = self::$currentIndex.'&id_product='.(int)$id_product;
  600. if ($id_product_attribute)
  601. $redirect .= '&id_product_attribute='.(int)$id_product_attribute;
  602. $redirect .= '&addstock&token='.$token;
  603. }
  604. Tools::redirectAdmin($redirect.'&conf=1');
  605. }
  606. else
  607. $this->errors[] = Tools::displayError('An error occurred. No stock was added.');
  608. }
  609. }
  610. if (Tools::isSubmit('removestock') && Tools::isSubmit('is_post'))
  611. {
  612. // if all is ok, remove stock
  613. if (count($this->errors) == 0)
  614. {
  615. $warehouse = new Warehouse($id_warehouse);
  616. // remove stock
  617. $stock_manager = StockManagerFactory::getManager();
  618. $removed_products = $stock_manager->removeProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $usable);
  619. if (count($removed_products) > 0)
  620. {
  621. StockAvailable::synchronize($id_product);
  622. Tools::redirectAdmin($redirect.'&conf=2');
  623. }
  624. else
  625. {
  626. $physical_quantity_in_stock = (int)$stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), false);
  627. $usable_quantity_in_stock = (int)$stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), true);
  628. $not_usable_quantity = ($physical_quantity_in_stock - $usable_quantity_in_stock);
  629. if ($usable_quantity_in_stock < $quantity)
  630. $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int)$quantity, (int)$usable_quantity_in_stock);
  631. else if ($not_usable_quantity < $quantity)
  632. $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int)$quantity, (int)$not_usable_quantity);
  633. else
  634. $this->errors[] = Tools::displayError('It is not possible to remove the specified quantity. Therefore no stock was removed.');
  635. }
  636. }
  637. }
  638. if (Tools::isSubmit('transferstock') && Tools::isSubmit('is_post'))
  639. {
  640. // get source warehouse id
  641. $id_warehouse_from = (int)Tools::getValue('id_warehouse_from', 0);
  642. if ($id_warehouse_from <= 0 || !Warehouse::exists($id_warehouse_from))
  643. $this->errors[] = Tools::displayError('The source warehouse is not valid.');
  644. // get destination warehouse id
  645. $id_warehouse_to = (int)Tools::getValue('id_warehouse_to', 0);
  646. if ($id_warehouse_to <= 0 || !Warehouse::exists($id_warehouse_to))
  647. $this->errors[] = Tools::displayError('The destination warehouse is not valid.');
  648. // get usable flag for source warehouse
  649. $usable_from = Tools::getValue('usable_from', null);
  650. if (is_null($usable_from))
  651. $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your source warehouse(s) is ready for sale or not.');
  652. $usable_from = (bool)$usable_from;
  653. // get usable flag for destination warehouse
  654. $usable_to = Tools::getValue('usable_to', null);
  655. if (is_null($usable_to))
  656. $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your destination warehouse(s) is ready for sale or not.');
  657. $usable_to = (bool)$usable_to;
  658. // if we can process stock transfers
  659. if (count($this->errors) == 0)
  660. {
  661. // transfer stock
  662. $stock_manager = StockManagerFactory::getManager();
  663. $is_transfer = $stock_manager->transferBetweenWarehouses(
  664. $id_product,
  665. $id_product_attribute,
  666. $quantity,
  667. $id_warehouse_from,
  668. $id_warehouse_to,
  669. $usable_from,
  670. $usable_to
  671. );
  672. StockAvailable::synchronize($id_product);
  673. if ($is_transfer)
  674. Tools::redirectAdmin($redirect.'&conf=3');
  675. else
  676. $this->errors[] = Tools::displayError('It is not possible to transfer the specified quantity. No stock was transferred.');
  677. }
  678. }
  679. }
  680. /**
  681. * assign default action in toolbar_btn smarty var, if they are not set.
  682. * uses override to specifically add, modify or remove items
  683. *
  684. */
  685. public function initToolbar()
  686. {
  687. switch ($this->display)
  688. {
  689. case 'addstock':
  690. $this->toolbar_btn['save-and-stay'] = array(
  691. 'short' => 'SaveAndStay',
  692. 'href' => '#',
  693. 'desc' => $this->l('Save and stay'),
  694. );
  695. case 'removestock':
  696. case 'transferstock':
  697. $this->toolbar_btn['save'] = array(
  698. 'href' => '#',
  699. 'desc' => $this->l('Save')
  700. );
  701. // Default cancel button - like old back link
  702. $back = Tools::safeOutput(Tools::getValue('back', ''));
  703. if (empty($back))
  704. $back = self::$currentIndex.'&token='.$this->token;
  705. $this->toolbar_btn['cancel'] = array(
  706. 'href' => $back,
  707. 'desc' => $this->l('Cancel')
  708. );
  709. break;
  710. default:
  711. parent::initToolbar();
  712. }
  713. }
  714. /**
  715. * AdminController::init() override
  716. * @see AdminController::init()
  717. */
  718. public function init()
  719. {
  720. parent::init();
  721. if (Tools::isSubmit('addstock'))
  722. {
  723. $this->display = 'addstock';
  724. $this->toolbar_title = $this->l('Stock: Add a product');
  725. }
  726. if (Tools::isSubmit('removestock'))
  727. {
  728. $this->display = 'removestock';
  729. $this->toolbar_title = $this->l('Stock: Remove a product');
  730. }
  731. if (Tools::isSubmit('transferstock'))
  732. {
  733. $this->display = 'transferstock';
  734. $this->toolbar_title = $this->l('Stock: Transfer a product');
  735. }
  736. }
  737. public function renderDetails()
  738. {
  739. if (Tools::isSubmit('id_product'))
  740. {
  741. // override attributes
  742. $this->identifier = 'id_product_attribute';
  743. $this->list_id = 'product_attribute';
  744. $this->lang = false;
  745. $this->addRowAction('addstock');
  746. $this->addRowAction('removestock');
  747. if (count(Warehouse::getWarehouses()) > 1)
  748. $this->addRowAction('transferstock');
  749. // no link on list rows
  750. $this->list_no_link = true;
  751. // inits toolbar
  752. $this->toolbar_btn = array();
  753. // get current lang id
  754. $lang_id = (int)$this->context->language->id;
  755. // Get product id
  756. $product_id = (int)Tools::getValue('id_product');
  757. // Load product attributes with sql override
  758. $this->table = 'product_attribute';
  759. $this->list_id = 'product_attribute';
  760. $this->_select = 'a.id_product_attribute as id, a.id_product, a.reference, a.ean13, a.upc';
  761. $this->_where = 'AND a.id_product = '.$product_id;
  762. $this->_group = 'GROUP BY a.id_product_attribute';
  763. $this->fields_list = array(
  764. 'reference' => array(
  765. 'title' => $this->l('Product reference'),
  766. 'filter_key' => 'a!reference'
  767. ),
  768. 'ean13' => array(
  769. 'title' => $this->l('EAN-13 or JAN barcode'),
  770. 'filter_key' => 'a!ean13'
  771. ),
  772. 'upc' => array(
  773. 'title' => $this->l('UPC barcode'),
  774. 'filter_key' => 'a!upc'
  775. ),
  776. 'name' => array(
  777. 'title' => $this->l('Name'),
  778. 'orderby' => false,
  779. 'filter' => false,
  780. 'search' => false
  781. ),
  782. 'stock' => array(
  783. 'title' => $this->l('Quantity'),
  784. 'orderby' => false,
  785. 'filter' => false,
  786. 'search' => false,
  787. 'class' => 'fixed-width-sm',
  788. 'align' => 'center',
  789. 'hint' => $this->l('Quantitity total for all warehouses.')
  790. ),
  791. );
  792. self::$currentIndex = self::$currentIndex.'&id_product='.(int)$product_id.'&detailsproduct';
  793. $this->processFilter();
  794. return parent::renderList();
  795. }
  796. }
  797. /**
  798. * AdminController::getList() override
  799. * @see AdminController::getList()
  800. */
  801. public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
  802. {
  803. parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
  804. // Check each row to see if there are combinations and get the correct action in consequence
  805. $nb_items = count($this->_list);
  806. for ($i = 0; $i < $nb_items; $i++)
  807. {
  808. $item = &$this->_list[$i];
  809. // if it's an ajax request we have to consider manipulating a product variation
  810. if (Tools::isSubmit('id_product'))
  811. {
  812. $item['name'] = Product::getProductName($item['id_product'], $item['id']);
  813. // no details for this row
  814. $this->addRowActionSkipList('details', array($item['id']));
  815. // specify actions in function of stock
  816. $this->skipActionByStock($item, true);
  817. }
  818. // If current product has variations
  819. else if (array_key_exists('variations', $item) && (int)$item['variations'] > 0)
  820. {
  821. // we have to desactivate stock actions on current row
  822. $this->addRowActionSkipList('addstock', array($item['id']));
  823. $this->addRowActionSkipList('removestock', array($item['id']));
  824. $this->addRowActionSkipList('transferstock', array($item['id']));
  825. // does not display these informaions because this product has combinations
  826. $item['reference'] = '--';
  827. $item['ean13'] = '--';
  828. $item['upc'] = '--';
  829. }
  830. else
  831. {
  832. //there are no variations of current product, so we don't want to show details action
  833. $this->addRowActionSkipList('details', array($item['id']));
  834. // specify actions in function of stock
  835. $this->skipActionByStock($item, false);
  836. }
  837. // Checks access
  838. if (!($this->tabAccess['add'] === '1'))
  839. $this->addRowActionSkipList('addstock', array($item['id']));
  840. if (!($this->tabAccess['delete'] === '1'))
  841. $this->addRowActionSkipList('removestock', array($item['id']));
  842. if (!($this->tabAccess['edit'] === '1'))
  843. $this->addRowActionSkipList('transferstock', array($item['id']));
  844. }
  845. }
  846. /**
  847. * Check stock for a given product or product attribute
  848. * and manage available actions in consequence
  849. *
  850. * @param array $item reference to the current item
  851. * @param bool $is_product_attribute specify if it's a product or a product variation
  852. */
  853. protected function skipActionByStock(&$item, $is_product_variation = false)
  854. {
  855. $stock_manager = StockManagerFactory::getManager();
  856. //get stocks for this product
  857. if ($is_product_variation)
  858. $stock = $stock_manager->getProductPhysicalQuantities($item['id_product'], $item['id']);
  859. else
  860. $stock = $stock_manager->getProductPhysicalQuantities($item['id'], 0);
  861. //affects stock to the list for display
  862. $item['stock'] = $stock;
  863. if ($stock <= 0)
  864. {
  865. //there is no stock, we can only add stock
  866. $this->addRowActionSkipList('removestock', array($item['id']));
  867. $this->addRowActionSkipList('transferstock', array($item['id']));
  868. }
  869. }
  870. /**
  871. * AdminController::initContent() override
  872. * @see AdminController::initContent()
  873. */
  874. public function initContent()
  875. {
  876. if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))
  877. {
  878. $this->warnings[md5('PS_ADVANCED_STOCK_MANAGEMENT')] = $this->l('You need to activate the Advanced Stock Management feature prior to using this feature.');
  879. return false;
  880. }
  881. // Manage the add stock form
  882. if ($this->display == 'addstock' || $this->display == 'removestock' || $this->display == 'transferstock')
  883. {
  884. if (Tools::isSubmit('id_product') || Tools::isSubmit('id_product_attribute'))
  885. {
  886. // get id product and product attribute if possible
  887. $id_product = (int)Tools::getValue('id_product', 0);
  888. $id_product_attribute = (int)Tools::getValue('id_product_attribute', 0);
  889. $product_is_valid = false;
  890. $is_pack = false;
  891. $is_virtual = false;
  892. $lang_id = $this->context->language->id;
  893. $default_wholesale_price = 0;
  894. // try to load product attribute first
  895. if ($id_product_attribute > 0)
  896. {
  897. // try to load product attribute
  898. $combination = new Combination($id_product_attribute);
  899. if (Validate::isLoadedObject($combination))
  900. {
  901. $product_is_valid = true;
  902. $id_product = $combination->id_product;
  903. $reference = $combination->reference;
  904. $ean13 = $combination->ean13;
  905. $upc = $combination->upc;
  906. $manufacturer_reference = $combination->supplier_reference;
  907. // get the full name for this combination
  908. $query = new DbQuery();
  909. $query->select('IFNULL(CONCAT(pl.`name`, \' : \', GROUP_CONCAT(agl.`name`, \' - \', al.`name` SEPARATOR \', \')),pl.`name`) as name');
  910. $query->from('product_attribute', 'a');
  911. $query->join('INNER JOIN '._DB_PREFIX_.'product_lang pl ON (pl.`id_product` = a.`id_product` AND pl.`id_lang` = '.(int)$lang_id.')
  912. LEFT JOIN '._DB_PREFIX_.'product_attribute_combination pac ON (pac.`id_product_attribute` = a.`id_product_attribute`)
  913. LEFT JOIN '._DB_PREFIX_.'attribute atr ON (atr.`id_attribute` = pac.`id_attribute`)
  914. LEFT JOIN '._DB_PREFIX_.'attribute_lang al ON (al.`id_attribute` = atr.`id_attribute` AND al.`id_lang` = '.(int)$lang_id.')
  915. LEFT JOIN '._DB_PREFIX_.'attribute_group_lang agl ON (agl.`id_attribute_group` = atr.`id_attribute_group` AND agl.`id_lang` = '.(int)$lang_id.')'
  916. );
  917. $query->where('a.`id_product_attribute` = '.$id_product_attribute);
  918. $name = Db::getInstance()->getValue($query);
  919. $p = new Product($id_product, false, $lang_id);
  920. $default_wholesale_price = $combination->wholesale_price > 0 ? $combination->wholesale_price : $p->wholesale_price;
  921. }
  922. }
  923. // try to load a simple product
  924. else
  925. {
  926. $product = new Product($id_product, false, $lang_id);
  927. if (is_int($product->id))
  928. {
  929. $product_is_valid = true;
  930. $reference = $product->reference;
  931. $ean13 = $product->ean13;
  932. $upc = $product->upc;
  933. $name = $product->name;
  934. $manufacturer_reference = $product->supplier_reference;
  935. $is_pack = $product->cache_is_pack;
  936. $is_virtual = $product->is_virtual;
  937. $default_wholesale_price = $product->wholesale_price;
  938. }
  939. }
  940. if ($product_is_valid === true && $is_pack == false && $is_virtual == false)
  941. {
  942. // init form
  943. $this->renderForm();
  944. $this->getlanguages();
  945. $helper = new HelperForm();
  946. $this->initPageHeaderToolbar();
  947. // Check if form template has been overriden
  948. if (file_exists($this->context->smarty->getTemplateDir(0).'/'.$this->tpl_folder.'form.tpl'))
  949. $helper->tpl = $this->tpl_folder.'form.tpl';
  950. $this->setHelperDisplay($helper);
  951. $helper->submit_action = $this->display;
  952. $helper->id = null; // no display standard hidden field in the form
  953. $helper->languages = $this->_languages;
  954. $helper->default_form_language = $this->default_form_language;
  955. $helper->allow_employee_form_lang = $this->allow_employee_form_lang;
  956. $helper->show_cancel_button = true;
  957. $helper->back_url = $this->context->link->getAdminLink('AdminStockManagement');
  958. $helper->fields_value = array(
  959. 'id_product' => $id_product,
  960. 'id_product_attribute' => $id_product_attribute,
  961. 'reference' => $reference,
  962. 'manufacturer_reference' => $manufacturer_reference,
  963. 'name' => $name,
  964. 'ean13' => $ean13,
  965. 'upc' => $upc,
  966. 'check' => md5(_COOKIE_KEY_.$id_product.$id_product_attribute),
  967. 'quantity' => Tools::getValue('quantity', ''),
  968. 'id_warehouse' => Tools::getValue('id_warehouse', ''),
  969. 'usable' => ($this->fields_value['usable'] ? $this->fields_value['usable'] : Tools::getValue('usable', '')),
  970. 'price' => Tools::getValue('price', (float)Tools::convertPrice($default_wholesale_price, null)),
  971. 'id_currency' => Tools::getValue('id_currency', ''),
  972. 'id_stock_mvt_reason' => Tools::getValue('id_stock_mvt_reason', ''),
  973. 'is_post' => 1,
  974. );
  975. if ($this->display == 'addstock')
  976. $_POST['id_product'] = (int)$id_product;
  977. if ($this->display == 'transferstock')
  978. {
  979. $helper->fields_value['id_warehouse_from'] = Tools::getValue('id_warehouse_from', '');
  980. $helper->fields_value['id_warehouse_to'] = Tools::getValue('id_warehouse_to', '');
  981. $helper->fields_value['usable_from'] = Tools::getValue('usable_from', '1');
  982. $helper->fields_value['usable_to'] = Tools::getValue('usable_to', '1');
  983. }
  984. $this->content .= $helper->generateForm($this->fields_form);
  985. $this->context->smarty->assign(array(
  986. 'content' => $this->content,
  987. 'show_page_header_toolbar' => $this->show_page_header_toolbar,
  988. 'page_header_toolbar_title' => $this->page_header_toolbar_title,
  989. 'page_header_toolbar_btn' => $this->page_header_toolbar_btn
  990. ));
  991. }
  992. else
  993. $this->errors[] = Tools::displayError('The specified product is not valid.');
  994. }
  995. }
  996. else
  997. {
  998. parent::initContent();
  999. }
  1000. }
  1001. /**
  1002. * Display addstock action link
  1003. * @param string $token the token to add to the link
  1004. * @param int $id the identifier to add to the link
  1005. * @return string
  1006. */
  1007. public function displayAddstockLink($token = null, $id)
  1008. {
  1009. if (!array_key_exists('AddStock', self::$cache_lang))
  1010. self::$cache_lang['AddStock'] = $this->l('Add stock');
  1011. $this->context->smarty->assign(array(
  1012. 'href' => self::$currentIndex.
  1013. '&'.$this->identifier.'='.$id.
  1014. '&addstock&token='.($token != null ? $token : $this->token),
  1015. 'action' => self::$cache_lang['AddStock'],
  1016. ));
  1017. return $this->context->smarty->fetch('helpers/list/list_action_addstock.tpl');
  1018. }
  1019. /**
  1020. * Display removestock action link
  1021. * @param string $token the token to add to the link
  1022. * @param int $id the identifier to add to the link
  1023. * @return string
  1024. */
  1025. public function displayRemovestockLink($token = null, $id)
  1026. {
  1027. if (!array_key_exists('RemoveStock', self::$cache_lang))
  1028. self::$cache_lang['RemoveStock'] = $this->l('Remove stock');
  1029. $this->context->smarty->assign(array(
  1030. 'href' => self::$currentIndex.
  1031. '&'.$this->identifier.'='.$id.
  1032. '&removestock&token='.($token != null ? $token : $this->token),
  1033. 'action' => self::$cache_lang['RemoveStock'],
  1034. ));
  1035. return $this->context->smarty->fetch('helpers/list/list_action_removestock.tpl');
  1036. }
  1037. /**
  1038. * Display transferstock action link
  1039. * @param string $token the token to add to the link
  1040. * @param int $id the identifier to add to the link
  1041. * @return string
  1042. */
  1043. public function displayTransferstockLink($token = null, $id)
  1044. {
  1045. if (!array_key_exists('TransferStock', self::$cache_lang))
  1046. self::$cache_lang['TransferStock'] = $this->l('Transfer stock');
  1047. $this->context->smarty->assign(array(
  1048. 'href' => self::$currentIndex.
  1049. '&'.$this->identifier.'='.$id.
  1050. '&transferstock&token='.($token != null ? $token : $this->token),
  1051. 'action' => self::$cache_lang['TransferStock'],
  1052. ));
  1053. return $this->context->smarty->fetch('helpers/list/list_action_transferstock.tpl');
  1054. }
  1055. public function initProcess()
  1056. {
  1057. if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))
  1058. {
  1059. $this->warnings[md5('PS_ADVANCED_STOCK_MANAGEMENT')] = $this->l('You need to activate advanced stock management prior to using this feature.');
  1060. return false;
  1061. }
  1062. if (Tools::getIsset('detailsproduct'))
  1063. {
  1064. $this->list_id = 'product_attribute';
  1065. if (isset($_POST['submitReset'.$this->list_id]))
  1066. $this->processResetFilters();
  1067. }
  1068. else
  1069. $this->list_id = 'product';
  1070. parent::initProcess();
  1071. }
  1072. }