PageRenderTime 70ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/controllers/admin/AdminSupplyOrdersController.php

https://github.com/netplayer/PrestaShop
PHP | 2187 lines | 1609 code | 277 blank | 301 comment | 244 complexity | af15dcb31dec3424fd2bc8f02c2c3c22 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 AdminSupplyOrdersControllerCore extends AdminController
  30. {
  31. /*
  32. * @var array List of warehouses
  33. */
  34. protected $warehouses;
  35. public function __construct()
  36. {
  37. $this->bootstrap = true;
  38. $this->context = Context::getContext();
  39. $this->table = 'supply_order';
  40. $this->className = 'SupplyOrder';
  41. $this->identifier = 'id_supply_order';
  42. $this->lang = false;
  43. $this->is_template_list = false;
  44. $this->multishop_context = Shop::CONTEXT_ALL;
  45. $this->addRowAction('updatereceipt');
  46. $this->addRowAction('changestate');
  47. $this->addRowAction('edit');
  48. $this->addRowAction('view');
  49. $this->addRowAction('details');
  50. $this->list_no_link = true;
  51. $this->fields_list = array(
  52. 'reference' => array(
  53. 'title' => $this->l('Reference'),
  54. 'havingFilter' => true
  55. ),
  56. 'supplier' => array(
  57. 'title' => $this->l('Supplier'),
  58. 'filter_key' => 's!name'
  59. ),
  60. 'warehouse' => array(
  61. 'title' => $this->l('Warehouse'),
  62. 'filter_key' => 'w!name'
  63. ),
  64. 'state' => array(
  65. 'title' => $this->l('Status'),
  66. 'filter_key' => 'stl!name',
  67. 'color' => 'color',
  68. ),
  69. 'date_add' => array(
  70. 'title' => $this->l('Creation'),
  71. 'align' => 'left',
  72. 'type' => 'date',
  73. 'havingFilter' => true,
  74. 'filter_key' => 'a!date_add'
  75. ),
  76. 'date_upd' => array(
  77. 'title' => $this->l('Last modification'),
  78. 'align' => 'left',
  79. 'type' => 'date',
  80. 'havingFilter' => true,
  81. 'filter_key' => 'a!date_upd'
  82. ),
  83. 'date_delivery_expected' => array(
  84. 'title' => $this->l('Delivery (expected)'),
  85. 'align' => 'left',
  86. 'type' => 'date',
  87. 'havingFilter' => true,
  88. 'filter_key' => 'a!date_delivery_expected'
  89. ),
  90. 'id_export' => array(
  91. 'title' => $this->l('Export'),
  92. 'callback' => 'printExportIcons',
  93. 'orderby' => false,
  94. 'search' => false
  95. ),
  96. );
  97. // gets the list of warehouses available
  98. $this->warehouses = Warehouse::getWarehouses(true);
  99. // gets the final list of warehouses
  100. array_unshift($this->warehouses, array('id_warehouse' => -1, 'name' => $this->l('All Warehouses')));
  101. parent::__construct();
  102. }
  103. /**
  104. * AdminController::init() override
  105. * @see AdminController::init()
  106. */
  107. public function init()
  108. {
  109. parent::init();
  110. if (Tools::isSubmit('addsupply_order') ||
  111. Tools::isSubmit('submitAddsupply_order') ||
  112. (Tools::isSubmit('updatesupply_order') && Tools::isSubmit('id_supply_order')))
  113. {
  114. // override table, lang, className and identifier for the current controller
  115. $this->table = 'supply_order';
  116. $this->className = 'SupplyOrder';
  117. $this->identifier = 'id_supply_order';
  118. $this->lang = false;
  119. $this->action = 'new';
  120. $this->display = 'add';
  121. if (Tools::isSubmit('updatesupply_order'))
  122. if ($this->tabAccess['edit'] === '1')
  123. $this->display = 'edit';
  124. else
  125. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  126. }
  127. if (Tools::isSubmit('update_receipt') && Tools::isSubmit('id_supply_order'))
  128. {
  129. // change the display type in order to add specific actions to
  130. $this->display = 'update_receipt';
  131. // display correct toolBar
  132. $this->initToolbar();
  133. }
  134. }
  135. public function initPageHeaderToolbar()
  136. {
  137. if ($this->display == 'details')
  138. $this->page_header_toolbar_btn['back'] = array(
  139. 'href' => Context::getContext()->link->getAdminLink('AdminSupplyOrders'),
  140. 'desc' => $this->l('Back to list', null, null, false),
  141. 'icon' => 'process-icon-back'
  142. );
  143. elseif (empty($this->display))
  144. {
  145. $this->page_header_toolbar_btn['new_supply_order'] = array(
  146. 'href' => self::$currentIndex.'&addsupply_order&token='.$this->token,
  147. 'desc' => $this->l('Add new supply order', null, null, false),
  148. 'icon' => 'process-icon-new'
  149. );
  150. $this->page_header_toolbar_btn['new_supply_order_template'] = array(
  151. 'href' => self::$currentIndex.'&addsupply_order&mod=template&token='.$this->token,
  152. 'desc' => $this->l('Add new supply order template', null, null, false),
  153. 'icon' => 'process-icon-new'
  154. );
  155. }
  156. parent::initPageHeaderToolbar();
  157. }
  158. /**
  159. * AdminController::renderForm() override
  160. * @see AdminController::renderForm()
  161. */
  162. public function renderForm()
  163. {
  164. if (Tools::isSubmit('addsupply_order') ||
  165. Tools::isSubmit('updatesupply_order') ||
  166. Tools::isSubmit('submitAddsupply_order') ||
  167. Tools::isSubmit('submitUpdatesupply_order'))
  168. {
  169. if (Tools::isSubmit('addsupply_order') || Tools::isSubmit('submitAddsupply_order'))
  170. $this->toolbar_title = $this->l('Stock: Create a new supply order');
  171. if (Tools::isSubmit('updatesupply_order') || Tools::isSubmit('submitUpdatesupply_order'))
  172. $this->toolbar_title = $this->l('Stock: Manage supply orders');
  173. if (Tools::isSubmit('mod') && Tools::getValue('mod') === 'template' || $this->object->is_template)
  174. $this->toolbar_title .= ' ('.$this->l('template').')';
  175. $this->addJqueryUI('ui.datepicker');
  176. //get warehouses list
  177. $warehouses = Warehouse::getWarehouses(true);
  178. // displays warning if there are no warehouses
  179. if (!$warehouses)
  180. $this->displayWarning($this->l('You must have at least one warehouse. See Stock/Warehouses'));
  181. //get currencies list
  182. $currencies = Currency::getCurrencies();
  183. $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT');
  184. $default_currency = Currency::getCurrency($id_default_currency);
  185. if ($default_currency)
  186. $currencies = array_merge(array($default_currency, '-'), $currencies);
  187. //get suppliers list
  188. $suppliers = array_unique(Supplier::getSuppliers(), SORT_REGULAR);
  189. //get languages list
  190. $languages = Language::getLanguages(true);
  191. $id_default_lang = Configuration::get('PS_LANG_DEFAULT');
  192. $default_lang = Language::getLanguage($id_default_lang);
  193. if ($default_lang)
  194. $languages = array_merge(array($default_lang, '-'), $languages);
  195. $this->fields_form = array(
  196. 'legend' => array(
  197. 'title' => $this->l('Order information'),
  198. 'icon' => 'icon-pencil'
  199. ),
  200. 'input' => array(
  201. array(
  202. 'type' => 'text',
  203. 'label' => $this->l('Reference'),
  204. 'name' => 'reference',
  205. 'required' => true,
  206. 'hint' => $this->l('The reference number for your order.'),
  207. ),
  208. array(
  209. 'type' => 'select',
  210. 'label' => $this->l('Supplier'),
  211. 'name' => 'id_supplier',
  212. 'required' => true,
  213. 'options' => array(
  214. 'query' => $suppliers,
  215. 'id' => 'id_supplier',
  216. 'name' => 'name'
  217. ),
  218. 'hint' => array(
  219. $this->l('Select the supplier you\'ll be purchasing from.'),
  220. $this->l('Warning: All products already added to the order will be removed.')
  221. )
  222. ),
  223. array(
  224. 'type' => 'select',
  225. 'label' => $this->l('Warehouse'),
  226. 'name' => 'id_warehouse',
  227. 'required' => true,
  228. 'options' => array(
  229. 'query' => $warehouses,
  230. 'id' => 'id_warehouse',
  231. 'name' => 'name'
  232. ),
  233. 'hint' => $this->l('Which warehouse will the order be sent to?'),
  234. ),
  235. array(
  236. 'type' => 'select',
  237. 'label' => $this->l('Currency'),
  238. 'name' => 'id_currency',
  239. 'required' => true,
  240. 'options' => array(
  241. 'query' => $currencies,
  242. 'id' => 'id_currency',
  243. 'name' => 'name'
  244. ),
  245. 'hint' => array(
  246. $this->l('The currency of the order.'),
  247. $this->l('Warning: All products already added to the order will be removed.')
  248. )
  249. ),
  250. array(
  251. 'type' => 'select',
  252. 'label' => $this->l('Order Language'),
  253. 'name' => 'id_lang',
  254. 'required' => true,
  255. 'options' => array(
  256. 'query' => $languages,
  257. 'id' => 'id_lang',
  258. 'name' => 'name'
  259. ),
  260. 'hint' => $this->l('The language of the order.')
  261. ),
  262. array(
  263. 'type' => 'text',
  264. 'label' => $this->l('Global discount percentage'),
  265. 'name' => 'discount_rate',
  266. 'required' => false,
  267. 'hint' => $this->l('This is the global discount percentage for the order.'),
  268. ),
  269. array(
  270. 'type' => 'text',
  271. 'label' => $this->l('Automatically load products'),
  272. 'name' => 'load_products',
  273. 'required' => false,
  274. 'hint' => array(
  275. $this->l('This will reset the order.'),
  276. $this->l('If a value specified, each of your current product (from the selected supplier and warehouse) with a quantity lower than or equal to this value will be loaded. This means that PrestaShop will pre-fill this order with the products that are low on quantity.'),
  277. ),
  278. ),
  279. ),
  280. 'submit' => array(
  281. 'title' => $this->l('Save order'),
  282. ),
  283. 'buttons' => array(
  284. 'save-and-stay' => array(
  285. 'title' => $this->l('Save order and stay'),
  286. 'name' => 'submitAddsupply_orderAndStay',
  287. 'type' => 'submit',
  288. 'class' => 'btn btn-default pull-right',
  289. 'icon' => 'process-icon-save'
  290. )
  291. )
  292. );
  293. if (Tools::isSubmit('mod') && Tools::getValue('mod') === 'template' ||
  294. $this->object->is_template)
  295. {
  296. $this->fields_form['input'][] = array(
  297. 'type' => 'hidden',
  298. 'name' => 'is_template'
  299. );
  300. $this->fields_form['input'][] = array(
  301. 'type' => 'hidden',
  302. 'name' => 'date_delivery_expected',
  303. );
  304. }
  305. else
  306. {
  307. $this->fields_form['input'][] = array(
  308. 'type' => 'date',
  309. 'label' => $this->l('Expected delivery date'),
  310. 'name' => 'date_delivery_expected',
  311. 'required' => true,
  312. 'desc' => $this->l('The expected delivery date for this order is...'),
  313. );
  314. }
  315. //specific discount display
  316. if (isset($this->object->discount_rate))
  317. $this->object->discount_rate = Tools::ps_round($this->object->discount_rate, 4);
  318. //specific date display
  319. if (isset($this->object->date_delivery_expected))
  320. {
  321. $date = explode(' ', $this->object->date_delivery_expected);
  322. if ($date)
  323. $this->object->date_delivery_expected = $date[0];
  324. }
  325. $this->displayInformation(
  326. $this->l('If you wish to order products, they have to be available for the specified supplier/warehouse.')
  327. .' '.
  328. $this->l('See Catalog/Products/[Your Product]/Suppliers & Warehouses.')
  329. .'<br />'.
  330. $this->l('Changing the currency or the supplier will reset the order.')
  331. .'<br />'
  332. .'<br />'.
  333. $this->l('Please note that you can only order from one supplier at a time.')
  334. );
  335. return parent::renderForm();
  336. }
  337. }
  338. /**
  339. * AdminController::getList() override
  340. * @see AdminController::getList()
  341. */
  342. public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
  343. {
  344. if (Tools::isSubmit('csv_orders') || Tools::isSubmit('csv_orders_details') || Tools::isSubmit('csv_order_details'))
  345. $limit = false;
  346. // defines button specific for non-template supply orders
  347. if (!$this->is_template_list && $this->display != 'details')
  348. {
  349. // adds export csv buttons
  350. $this->toolbar_btn['export-csv-orders'] = array(
  351. 'short' => 'Export Orders',
  352. 'href' => $this->context->link->getAdminLink('AdminSupplyOrders').'&amp;csv_orders&id_warehouse='.$this->getCurrentWarehouse(),
  353. 'desc' => $this->l('Export Orders (CSV)'),
  354. 'class' => 'process-icon-export'
  355. );
  356. $this->toolbar_btn['export-csv-details'] = array(
  357. 'short' => 'Export Orders Details',
  358. 'href' => $this->context->link->getAdminLink('AdminSupplyOrders').'&amp;csv_orders_details&id_warehouse='.$this->getCurrentWarehouse(),
  359. 'desc' => $this->l('Export Orders Details (CSV)'),
  360. 'class' => 'process-icon-export'
  361. );
  362. unset($this->toolbar_btn['new']);
  363. if ($this->tabAccess['add'] === '1')
  364. {
  365. $this->toolbar_btn['new'] = array(
  366. 'href' => self::$currentIndex.'&amp;add'.$this->table.'&amp;token='.$this->token,
  367. 'desc' => $this->l('Add New')
  368. );
  369. }
  370. }
  371. parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
  372. // adds colors depending on the receipt state
  373. if ($order_by == 'quantity_expected')
  374. {
  375. $nb_items = count($this->_list);
  376. for ($i = 0; $i < $nb_items; ++$i)
  377. {
  378. $item = &$this->_list[$i];
  379. if ($item['quantity_received'] == $item['quantity_expected'])
  380. $item['color'] = '#00bb35';
  381. else if ($item['quantity_received'] > $item['quantity_expected'])
  382. $item['color'] = '#fb0008';
  383. }
  384. }
  385. // actions filters on supply orders list
  386. if ($this->table == 'supply_order')
  387. {
  388. $nb_items = count($this->_list);
  389. for ($i = 0; $i < $nb_items; $i++)
  390. {
  391. // if the current state doesn't allow order edit, skip the edit action
  392. if ($this->_list[$i]['editable'] == 0)
  393. $this->addRowActionSkipList('edit', $this->_list[$i]['id_supply_order']);
  394. if ($this->_list[$i]['enclosed'] == 1 && $this->_list[$i]['receipt_state'] == 0)
  395. $this->addRowActionSkipList('changestate', $this->_list[$i]['id_supply_order']);
  396. if (1 != $this->_list[$i]['pending_receipt'])
  397. $this->addRowActionSkipList('updatereceipt', $this->_list[$i]['id_supply_order']);
  398. }
  399. }
  400. }
  401. /**
  402. * AdminController::renderList() override
  403. * @see AdminController::renderList()
  404. */
  405. public function renderList()
  406. {
  407. $this->displayInformation($this->l('This interface allows you to manage supply orders.').'<br />');
  408. $this->displayInformation($this->l('You can create pre-filled order templates, from which you can build actual orders much quicker.').'<br />');
  409. if (count($this->warehouses) <= 1)
  410. $this->displayWarning($this->l('You must choose at least one warehouse before creating supply orders. For more information, see Stock/Warehouses.'));
  411. // assigns warehouses
  412. $this->tpl_list_vars['warehouses'] = $this->warehouses;
  413. $this->tpl_list_vars['current_warehouse'] = $this->getCurrentWarehouse();
  414. $this->tpl_list_vars['filter_status'] = $this->getFilterStatus();
  415. // overrides query
  416. $this->_select = '
  417. s.name AS supplier,
  418. w.name AS warehouse,
  419. stl.name AS state,
  420. st.delivery_note,
  421. st.editable,
  422. st.enclosed,
  423. st.receipt_state,
  424. st.pending_receipt,
  425. st.color AS color,
  426. a.id_supply_order as id_export';
  427. $this->_join = 'LEFT JOIN `'._DB_PREFIX_.'supply_order_state_lang` stl ON
  428. (
  429. a.id_supply_order_state = stl.id_supply_order_state
  430. AND stl.id_lang = '.(int)$this->context->language->id.'
  431. )
  432. LEFT JOIN `'._DB_PREFIX_.'supply_order_state` st ON a.id_supply_order_state = st.id_supply_order_state
  433. LEFT JOIN `'._DB_PREFIX_.'supplier` s ON a.id_supplier = s.id_supplier
  434. LEFT JOIN `'._DB_PREFIX_.'warehouse` w ON (w.id_warehouse = a.id_warehouse)';
  435. $this->_where = ' AND a.is_template = 0';
  436. if ($this->getCurrentWarehouse() != -1)
  437. {
  438. $this->_where .= ' AND a.id_warehouse = '.$this->getCurrentWarehouse();
  439. self::$currentIndex .= '&id_warehouse='.(int)$this->getCurrentWarehouse();
  440. }
  441. if ($this->getFilterStatus() != 0)
  442. {
  443. $this->_where .= ' AND st.enclosed != 1';
  444. self::$currentIndex .= '&filter_status=on';
  445. }
  446. $this->list_id = 'orders';
  447. $first_list = parent::renderList();
  448. if (Tools::isSubmit('csv_orders') || Tools::isSubmit('csv_orders_details') || Tools::isSubmit('csv_order_details'))
  449. {
  450. if (count($this->_list) > 0)
  451. {
  452. $this->renderCSV();
  453. die;
  454. }
  455. else
  456. $this->displayWarning($this->l('There is nothing to export as a CSV file.'));
  457. }
  458. // second list : templates
  459. $second_list = null;
  460. $this->is_template_list = true;
  461. unset($this->tpl_list_vars['warehouses']);
  462. unset($this->tpl_list_vars['current_warehouse']);
  463. unset($this->tpl_list_vars['filter_status']);
  464. // unsets actions
  465. $this->actions = array();
  466. unset($this->toolbar_btn['export-csv-orders']);
  467. unset($this->toolbar_btn['export-csv-details']);
  468. // adds actions
  469. $this->addRowAction('view');
  470. $this->addRowAction('edit');
  471. $this->addRowAction('createsupplyorder');
  472. $this->addRowAction('delete');
  473. // unsets some fields
  474. unset($this->fields_list['state'],
  475. $this->fields_list['date_upd'],
  476. $this->fields_list['id_pdf'],
  477. $this->fields_list['date_delivery_expected'],
  478. $this->fields_list['id_export']);
  479. // $this->fields_list['date_add']['align'] = 'left';
  480. // adds filter, to gets only templates
  481. unset($this->_where);
  482. $this->_where = ' AND a.is_template = 1';
  483. if ($this->getCurrentWarehouse() != -1)
  484. $this->_where .= ' AND a.id_warehouse = '.$this->getCurrentWarehouse();
  485. // re-defines toolbar & buttons
  486. $this->toolbar_title = $this->l('Stock: Supply order templates');
  487. $this->initToolbar();
  488. unset($this->toolbar_btn['new']);
  489. $this->toolbar_btn['new'] = array(
  490. 'href' => self::$currentIndex.'&amp;add'.$this->table.'&mod=template&amp;token='.$this->token,
  491. 'desc' => $this->l('Add new template')
  492. );
  493. $this->list_id = 'templates';
  494. // inits list
  495. $second_list = parent::renderList();
  496. return $first_list.$second_list;
  497. }
  498. /**
  499. * Init the content of change state action
  500. */
  501. public function initChangeStateContent()
  502. {
  503. $id_supply_order = (int)Tools::getValue('id_supply_order', 0);
  504. if ($id_supply_order <= 0)
  505. {
  506. $this->errors[] = Tools::displayError('The specified supply order is not valid');
  507. return parent::initContent();
  508. }
  509. $supply_order = new SupplyOrder($id_supply_order);
  510. $supply_order_state = new SupplyOrderState($supply_order->id_supply_order_state);
  511. if (!Validate::isLoadedObject($supply_order) || !Validate::isLoadedObject($supply_order_state))
  512. {
  513. $this->errors[] = Tools::displayError('The specified supply order is not valid');
  514. return parent::initContent();
  515. }
  516. // change the display type in order to add specific actions to
  517. $this->display = 'update_order_state';
  518. // overrides parent::initContent();
  519. $this->initToolbar();
  520. $this->initPageHeaderToolbar();
  521. // given the current state, loads available states
  522. $states = SupplyOrderState::getSupplyOrderStates($supply_order->id_supply_order_state);
  523. // gets the state that are not allowed
  524. $allowed_states = array();
  525. foreach ($states as &$state)
  526. {
  527. $allowed_states[] = $state['id_supply_order_state'];
  528. $state['allowed'] = 1;
  529. }
  530. $not_allowed_states = SupplyOrderState::getStates($allowed_states);
  531. // generates the final list of states
  532. $index = count($allowed_states);
  533. foreach ($not_allowed_states as &$not_allowed_state)
  534. {
  535. $not_allowed_state['allowed'] = 0;
  536. $states[$index] = $not_allowed_state;
  537. ++$index;
  538. }
  539. // loads languages
  540. $this->getlanguages();
  541. // defines the fields of the form to display
  542. $this->fields_form[0]['form'] = array(
  543. 'legend' => array(
  544. 'title' => $this->l('Supply order status'),
  545. 'icon' => 'icon-pencil'
  546. ),
  547. 'input' => array(),
  548. 'submit' => array(
  549. 'title' => $this->l('Save')
  550. )
  551. );
  552. $this->displayInformation($this->l('Be careful when changing status. Some of those changes cannot be canceled. '));
  553. // sets up the helper
  554. $helper = new HelperForm();
  555. $helper->submit_action = 'submitChangestate';
  556. $helper->currentIndex = self::$currentIndex;
  557. $helper->toolbar_btn = $this->toolbar_btn;
  558. $helper->toolbar_scroll = false;
  559. $helper->token = $this->token;
  560. $helper->id = null; // no display standard hidden field in the form
  561. $helper->languages = $this->_languages;
  562. $helper->default_form_language = $this->default_form_language;
  563. $helper->allow_employee_form_lang = $this->allow_employee_form_lang;
  564. $helper->title = sprintf($this->l('Stock: Change supply order status #%s'), $supply_order->reference);
  565. $helper->override_folder = 'supply_orders_change_state/';
  566. // assigns our content
  567. $helper->tpl_vars['show_change_state_form'] = true;
  568. $helper->tpl_vars['supply_order_state'] = $supply_order_state;
  569. $helper->tpl_vars['supply_order'] = $supply_order;
  570. $helper->tpl_vars['supply_order_states'] = $states;
  571. // generates the form to display
  572. $content = $helper->generateForm($this->fields_form);
  573. $this->context->smarty->assign(array(
  574. 'content' => $content,
  575. 'url_post' => self::$currentIndex.'&token='.$this->token,
  576. 'show_page_header_toolbar' => $this->show_page_header_toolbar,
  577. 'page_header_toolbar_title' => $this->page_header_toolbar_title,
  578. 'page_header_toolbar_btn' => $this->page_header_toolbar_btn
  579. ));
  580. }
  581. /**
  582. * Init the content of change state action
  583. */
  584. public function initUpdateSupplyOrderContent()
  585. {
  586. $this->addJqueryPlugin('autocomplete');
  587. // load supply order
  588. $id_supply_order = (int)Tools::getValue('id_supply_order', null);
  589. if ($id_supply_order != null)
  590. {
  591. $supply_order = new SupplyOrder($id_supply_order);
  592. $currency = new Currency($supply_order->id_currency);
  593. if (Validate::isLoadedObject($supply_order))
  594. {
  595. // load products of this order
  596. $products = $supply_order->getEntries();
  597. $product_ids = array();
  598. if (isset($this->order_products_errors) && is_array($this->order_products_errors))
  599. {
  600. //for each product in error array, check if it is in products array, and remove it to conserve last user values
  601. foreach ($this->order_products_errors as $pe)
  602. foreach ($products as $index_p => $p)
  603. if (($p['id_product'] == $pe['id_product']) && ($p['id_product_attribute'] == $pe['id_product_attribute']))
  604. unset($products[$index_p]);
  605. // then merge arrays
  606. $products = array_merge($this->order_products_errors, $products);
  607. }
  608. foreach ($products as &$item)
  609. {
  610. // calculate md5 checksum on each product for use in tpl
  611. $item['checksum'] = md5(_COOKIE_KEY_.$item['id_product'].'_'.$item['id_product_attribute']);
  612. $item['unit_price_te'] = Tools::ps_round($item['unit_price_te'], 2);
  613. // add id to ids list
  614. $product_ids[] = $item['id_product'].'_'.$item['id_product_attribute'];
  615. }
  616. $this->tpl_form_vars['products_list'] = $products;
  617. $this->tpl_form_vars['product_ids'] = implode($product_ids, '|');
  618. $this->tpl_form_vars['product_ids_to_delete'] = '';
  619. $this->tpl_form_vars['supplier_id'] = $supply_order->id_supplier;
  620. $this->tpl_form_vars['currency'] = $currency;
  621. }
  622. }
  623. $this->tpl_form_vars['content'] = $this->content;
  624. $this->tpl_form_vars['token'] = $this->token;
  625. $this->tpl_form_vars['show_product_management_form'] = true;
  626. // call parent initcontent to render standard form content
  627. parent::initContent();
  628. }
  629. /**
  630. * Inits the content of 'update_receipt' action
  631. * Called in initContent()
  632. * @see AdminSuppliersOrders::initContent()
  633. */
  634. public function initUpdateReceiptContent()
  635. {
  636. $id_supply_order = (int)Tools::getValue('id_supply_order', null);
  637. // if there is no order to fetch
  638. if (null == $id_supply_order)
  639. return parent::initContent();
  640. $supply_order = new SupplyOrder($id_supply_order);
  641. // if it's not a valid order
  642. if (!Validate::isLoadedObject($supply_order))
  643. return parent::initContent();
  644. $this->initPageHeaderToolbar();
  645. // re-defines fields_list
  646. $this->fields_list = array(
  647. 'supplier_reference' => array(
  648. 'title' => $this->l('Supplier reference'),
  649. 'orderby' => false,
  650. 'filter' => false,
  651. 'search' => false,
  652. ),
  653. 'reference' => array(
  654. 'title' => $this->l('Reference'),
  655. 'orderby' => false,
  656. 'filter' => false,
  657. 'search' => false,
  658. ),
  659. 'ean13' => array(
  660. 'title' => $this->l('EAN-13 or JAN barcode'),
  661. 'orderby' => false,
  662. 'filter' => false,
  663. 'search' => false,
  664. ),
  665. 'upc' => array(
  666. 'title' => $this->l('UPC barcode'),
  667. 'orderby' => false,
  668. 'filter' => false,
  669. 'search' => false,
  670. ),
  671. 'name' => array(
  672. 'title' => $this->l('Name'),
  673. 'orderby' => false,
  674. 'filter' => false,
  675. 'search' => false,
  676. ),
  677. 'quantity_received_today' => array(
  678. 'title' => $this->l('Quantity received today?'),
  679. 'type' => 'editable',
  680. 'orderby' => false,
  681. 'filter' => false,
  682. 'search' => false,
  683. 'hint' => $this->l('The quantity of supplies that you received today.'),
  684. ),
  685. 'quantity_received' => array(
  686. 'title' => $this->l('Quantity received'),
  687. 'orderby' => false,
  688. 'filter' => false,
  689. 'search' => false,
  690. 'badge_danger' => true,
  691. 'badge_success' => true,
  692. 'hint' => $this->l('The quantity of supplies that you received so far (today and the days before, if it applies).'),
  693. ),
  694. 'quantity_expected' => array(
  695. 'title' => $this->l('Quantity expected'),
  696. 'orderby' => false,
  697. 'filter' => false,
  698. 'search' => false,
  699. ),
  700. 'quantity_left' => array(
  701. 'title' => $this->l('Quantity left'),
  702. 'orderby' => false,
  703. 'filter' => false,
  704. 'search' => false,
  705. 'hint' => $this->l('The quantity of supplies left to receive for this order.'),
  706. )
  707. );
  708. // attributes override
  709. unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter);
  710. $this->table = 'supply_order_detail';
  711. $this->identifier = 'id_supply_order_detail';
  712. $this->className = 'SupplyOrderDetail';
  713. $this->list_simple_header = false;
  714. $this->list_no_link = true;
  715. $this->colorOnBackground = true;
  716. $this->row_hover = false;
  717. $this->bulk_actions = array('Update' => array('text' => $this->l('Update selected'), 'confirm' => $this->l('Update selected items?')));
  718. $this->addRowAction('details');
  719. // sets toolbar title with order reference
  720. $this->toolbar_title = sprintf($this->l('Receipt of products for supply order #%s'), $supply_order->reference);
  721. $this->lang = false;
  722. $lang_id = (int)$this->context->language->id; //employee lang
  723. // gets values corresponding to fields_list
  724. $this->_select = '
  725. a.id_supply_order_detail as id,
  726. a.quantity_received as quantity_received,
  727. a.quantity_expected as quantity_expected,
  728. IF (a.quantity_expected < a.quantity_received, 0, a.quantity_expected - a.quantity_received) as quantity_left,
  729. IF (a.quantity_expected < a.quantity_received, 0, a.quantity_expected - a.quantity_received) as quantity_received_today,
  730. IF (a.quantity_expected = a.quantity_received, 1, 0) badge_success,
  731. IF (a.quantity_expected > a.quantity_received, 1, 0) badge_danger';
  732. $this->_where = 'AND a.`id_supply_order` = '.(int)$id_supply_order;
  733. $this->_group = 'GROUP BY a.id_supply_order_detail';
  734. // gets the list ordered by price desc, without limit
  735. $this->getList($lang_id, 'quantity_expected', 'DESC', 0, Tools::getValue('supply_order_pagination'), false);
  736. // defines action for POST
  737. $action = '&id_supply_order='.$id_supply_order.'&update_receipt=1';
  738. // unsets some buttons
  739. unset($this->toolbar_btn['export-csv-orders']);
  740. unset($this->toolbar_btn['export-csv-details']);
  741. unset($this->toolbar_btn['new']);
  742. $this->toolbar_btn['back'] = array(
  743. 'desc' => $this->l('Back'),
  744. 'href' => $this->context->link->getAdminLink('AdminSupplyOrders')
  745. );
  746. // renders list
  747. $helper = new HelperList();
  748. $this->setHelperDisplay($helper);
  749. $helper->actions = array('details');
  750. $helper->force_show_bulk_actions = true;
  751. $helper->override_folder = 'supply_orders_receipt_history/';
  752. $helper->toolbar_btn = $this->toolbar_btn;
  753. $helper->list_id = 'supply_order_detail';
  754. $helper->ajax_params = array(
  755. 'display_product_history' => 1,
  756. );
  757. $helper->currentIndex = self::$currentIndex.$action;
  758. // display these global order informations
  759. $this->displayInformation($this->l('This interface allows you to update the quantities of this ongoing order.').'<br />');
  760. $this->displayInformation($this->l('Be careful! Once you update, you cannot go back unless you add new negative stock movements.').'<br />');
  761. $this->displayInformation($this->l('A green line means that you\'ve received exactly the quantity you expected. A red line means that you\'ve received more than expected.').'<br />');
  762. // generates content
  763. $content = $helper->generateList($this->_list, $this->fields_list);
  764. // assigns var
  765. $this->context->smarty->assign(array(
  766. 'content' => $content,
  767. 'show_page_header_toolbar' => $this->show_page_header_toolbar,
  768. 'page_header_toolbar_title' => $this->page_header_toolbar_title,
  769. 'page_header_toolbar_btn' => $this->page_header_toolbar_btn
  770. ));
  771. }
  772. /**
  773. * AdminController::initContent() override
  774. * @see AdminController::initContent()
  775. */
  776. public function initContent()
  777. {
  778. if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))
  779. {
  780. $this->warnings[md5('PS_ADVANCED_STOCK_MANAGEMENT')] = $this->l('You need to activate the Advanced Stock Management feature prior to using this feature.');
  781. return false;
  782. }
  783. // Manage the add stock form
  784. if (Tools::isSubmit('changestate'))
  785. $this->initChangeStateContent();
  786. elseif (Tools::isSubmit('update_receipt') && Tools::isSubmit('id_supply_order'))
  787. $this->initUpdateReceiptContent();
  788. elseif (Tools::isSubmit('viewsupply_order') && Tools::isSubmit('id_supply_order'))
  789. {
  790. $this->action = 'view';
  791. $this->display = 'view';
  792. parent::initContent();
  793. }
  794. elseif (Tools::isSubmit('updatesupply_order'))
  795. $this->initUpdateSupplyOrderContent();
  796. else
  797. parent::initContent();
  798. }
  799. /**
  800. * Ths method manage associated products to the order when updating it
  801. */
  802. public function manageOrderProducts()
  803. {
  804. // load supply order
  805. $id_supply_order = (int)Tools::getValue('id_supply_order', null);
  806. $products_already_in_order = array();
  807. if ($id_supply_order != null)
  808. {
  809. $supply_order = new SupplyOrder($id_supply_order);
  810. if (Validate::isLoadedObject($supply_order))
  811. {
  812. // tests if the supplier or currency have changed in the supply order
  813. $new_supplier_id = (int)Tools::getValue('id_supplier');
  814. $new_currency_id = (int)Tools::getValue('id_currency');
  815. if (($new_supplier_id != $supply_order->id_supplier) ||
  816. ($new_currency_id != $supply_order->id_currency))
  817. {
  818. // resets all products in this order
  819. $supply_order->resetProducts();
  820. }
  821. else
  822. {
  823. $products_already_in_order = $supply_order->getEntries();
  824. $currency = new Currency($supply_order->id_ref_currency);
  825. // gets all product ids to manage
  826. $product_ids_str = Tools::getValue('product_ids', null);
  827. $product_ids = explode('|', $product_ids_str);
  828. $product_ids_to_delete_str = Tools::getValue('product_ids_to_delete', null);
  829. $product_ids_to_delete = array_unique(explode('|', $product_ids_to_delete_str));
  830. //delete products that are not managed anymore
  831. foreach ($products_already_in_order as $paio)
  832. {
  833. $product_ok = false;
  834. foreach ($product_ids_to_delete as $id)
  835. {
  836. $id_check = $paio['id_product'].'_'.$paio['id_product_attribute'];
  837. if ($id_check == $id)
  838. $product_ok = true;
  839. }
  840. if ($product_ok === true)
  841. {
  842. $entry = new SupplyOrderDetail($paio['id_supply_order_detail']);
  843. $entry->delete();
  844. }
  845. }
  846. // manage each product
  847. foreach ($product_ids as $id)
  848. {
  849. $errors = array();
  850. // check if a checksum is available for this product and test it
  851. $check = Tools::getValue('input_check_'.$id, '');
  852. $check_valid = md5(_COOKIE_KEY_.$id);
  853. if ($check_valid != $check)
  854. continue;
  855. $pos = strpos($id, '_');
  856. if ($pos === false)
  857. continue;
  858. // Load / Create supply order detail
  859. $entry = new SupplyOrderDetail();
  860. $id_supply_order_detail = (int)Tools::getValue('input_id_'.$id, 0);
  861. if ($id_supply_order_detail > 0)
  862. {
  863. $existing_entry = new SupplyOrderDetail($id_supply_order_detail);
  864. if (Validate::isLoadedObject($supply_order))
  865. $entry = &$existing_entry;
  866. }
  867. // get product informations
  868. $entry->id_product = substr($id, 0, $pos);
  869. $entry->id_product_attribute = substr($id, $pos + 1);
  870. $entry->unit_price_te = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_unit_price_te_'.$id, 0));
  871. $entry->quantity_expected = (int)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_quantity_expected_'.$id, 0));
  872. $entry->discount_rate = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_discount_rate_'.$id, 0));
  873. $entry->tax_rate = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('input_tax_rate_'.$id, 0));
  874. $entry->reference = Tools::getValue('input_reference_'.$id, '');
  875. $entry->supplier_reference = Tools::getValue('input_supplier_reference_'.$id, '');
  876. $entry->ean13 = Tools::getValue('input_ean13_'.$id, '');
  877. $entry->upc = Tools::getValue('input_upc_'.$id, '');
  878. //get the product name in the order language
  879. $entry->name = Product::getProductName($entry->id_product, $entry->id_product_attribute, $supply_order->id_lang);
  880. if (empty($entry->name))
  881. $entry->name = '';
  882. if ($entry->supplier_reference == null)
  883. $entry->supplier_reference = '';
  884. $entry->exchange_rate = $currency->conversion_rate;
  885. $entry->id_currency = $currency->id;
  886. $entry->id_supply_order = $supply_order->id;
  887. $errors = $entry->validateController();
  888. //get the product name displayed in the backoffice according to the employee language
  889. $entry->name_displayed = Tools::getValue('input_name_displayed_'.$id, '');
  890. // if there is a problem, handle error for the current product
  891. if (count($errors) > 0)
  892. {
  893. // add the product to error array => display again product line
  894. $this->order_products_errors[] = array(
  895. 'id_product' => $entry->id_product,
  896. 'id_product_attribute' => $entry->id_product_attribute,
  897. 'unit_price_te' => $entry->unit_price_te,
  898. 'quantity_expected' => $entry->quantity_expected,
  899. 'discount_rate' => $entry->discount_rate,
  900. 'tax_rate' => $entry->tax_rate,
  901. 'name' => $entry->name,
  902. 'name_displayed' => $entry->name_displayed,
  903. 'reference' => $entry->reference,
  904. 'supplier_reference' => $entry->supplier_reference,
  905. 'ean13' => $entry->ean13,
  906. 'upc' => $entry->upc,
  907. );
  908. $error_str = '<ul>';
  909. foreach ($errors as $e)
  910. $error_str .= '<li>'.sprintf($this->l('Field: %s'), $e).'</li>';
  911. $error_str .= '</ul>';
  912. $this->errors[] = sprintf(Tools::displayError('Please verify the product information for "%s":'), $entry->name).' '.$error_str;
  913. }
  914. else
  915. $entry->save();
  916. }
  917. }
  918. }
  919. }
  920. }
  921. /**
  922. * AdminController::postProcess() override
  923. * @see AdminController::postProcess()
  924. */
  925. public function postProcess()
  926. {
  927. $this->is_editing_order = false;
  928. // Checks access
  929. if (Tools::isSubmit('submitAddsupply_order') && !($this->tabAccess['add'] === '1'))
  930. $this->errors[] = Tools::displayError('You do not have permission to add a supply order.');
  931. if (Tools::isSubmit('submitBulkUpdatesupply_order_detail') && !($this->tabAccess['edit'] === '1'))
  932. $this->errors[] = Tools::displayError('You do not have permission to edit an order.');
  933. // Trick to use both Supply Order as template and actual orders
  934. if (Tools::isSubmit('is_template'))
  935. $_GET['mod'] = 'template';
  936. // checks if supply order reference is unique
  937. if (Tools::isSubmit('reference'))
  938. {
  939. // gets the reference
  940. $ref = pSQL(Tools::getValue('reference'));
  941. if (Tools::getValue('id_supply_order') != 0 && SupplyOrder::getReferenceById((int)Tools::getValue('id_supply_order')) != $ref)
  942. {
  943. if ((int)SupplyOrder::exists($ref) != 0)
  944. $this->errors[] = Tools::displayError('The reference has to be unique.');
  945. }
  946. else if (Tools::getValue('id_supply_order') == 0 && (int)SupplyOrder::exists($ref) != 0)
  947. $this->errors[] = Tools::displayError('The reference has to be unique.');
  948. }
  949. if ($this->errors)
  950. return;
  951. // Global checks when add / update a supply order
  952. if (Tools::isSubmit('submitAddsupply_order') || Tools::isSubmit('submitAddsupply_orderAndStay'))
  953. {
  954. $this->action = 'save';
  955. $this->is_editing_order = true;
  956. // get supplier ID
  957. $id_supplier = (int)Tools::getValue('id_supplier', 0);
  958. if ($id_supplier <= 0 || !Supplier::supplierExists($id_supplier))
  959. $this->errors[] = Tools::displayError('The selected supplier is not valid.');
  960. // get warehouse id
  961. $id_warehouse = (int)Tools::getValue('id_warehouse', 0);
  962. if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse))
  963. $this->errors[] = Tools::displayError('The selected warehouse is not valid.');
  964. // get currency id
  965. $id_currency = (int)Tools::getValue('id_currency', 0);
  966. if ($id_currency <= 0 || ( !($result = Currency::getCurrency($id_currency)) || empty($result) ))
  967. $this->errors[] = Tools::displayError('The selected currency is not valid.');
  968. // get delivery date
  969. if (Tools::getValue('mod') != 'template' && strtotime(Tools::getValue('date_delivery_expected')) <= strtotime('-1 day'))
  970. $this->errors[] = Tools::displayError('The specified date cannot be in the past.');
  971. // gets threshold
  972. $quantity_threshold = Tools::getValue('load_products');
  973. if (is_numeric($quantity_threshold))
  974. $quantity_threshold = (int)$quantity_threshold;
  975. else
  976. $quantity_threshold = null;
  977. if (!count($this->errors))
  978. {
  979. // forces date for templates
  980. if (Tools::isSubmit('is_template') && !Tools::getValue('date_delivery_expected'))
  981. $_POST['date_delivery_expected'] = date('Y-m-d h:i:s');
  982. // specify initial state
  983. $_POST['id_supply_order_state'] = 1; //defaut creation state
  984. // specify global reference currency
  985. $_POST['id_ref_currency'] = Currency::getDefaultCurrency()->id;
  986. // specify supplier name
  987. $_POST['supplier_name'] = Supplier::getNameById($id_supplier);
  988. //specific discount check
  989. $_POST['discount_rate'] = (float)str_replace(array(' ', ','), array('', '.'), Tools::getValue('discount_rate', 0));
  990. }
  991. // manage each associated product
  992. $this->manageOrderProducts();
  993. // if the threshold is defined and we are saving the order
  994. if (Tools::isSubmit('submitAddsupply_order') && Validate::isInt($quantity_threshold))
  995. $this->loadProducts((int)$quantity_threshold);
  996. }
  997. // Manage state change
  998. if (Tools::isSubmit('submitChangestate')
  999. && Tools::isSubmit('id_supply_order')
  1000. && Tools::isSubmit('id_supply_order_state'))
  1001. {
  1002. if ($this->tabAccess['edit'] != '1')
  1003. $this->errors[] = Tools::displayError('You do not have permission to change the order status.');
  1004. // get state ID
  1005. $id_state = (int)Tools::getValue('id_supply_order_state', 0);
  1006. if ($id_state <= 0)
  1007. $this->errors[] = Tools::displayError('The selected supply order status is not valid.');
  1008. // get supply order ID
  1009. $id_supply_order = (int)Tools::getValue('id_supply_order', 0);
  1010. if ($id_supply_order <= 0)
  1011. $this->errors[] = Tools::displayError('The supply order ID is not valid.');
  1012. if (!count($this->errors))
  1013. {
  1014. // try to load supply order
  1015. $supply_order = new SupplyOrder($id_supply_order);
  1016. if (Validate::isLoadedObject($supply_order))
  1017. {
  1018. // get valid available possible states for this order
  1019. $states = SupplyOrderState::getSupplyOrderStates($supply_order->id_supply_order_state);
  1020. foreach ($states as $state)
  1021. {
  1022. // if state is valid, change it in the order
  1023. if ($id_state == $state['id_supply_order_state'])
  1024. {
  1025. $new_state = new SupplyOrderState($id_state);
  1026. $old_state = new SupplyOrderState($supply_order->id_supply_order_state);
  1027. // special case of validate state - check if there are products in the order and the required state is not an enclosed state
  1028. if ($supply_order->isEditable() && !$supply_order->hasEntries() && !$new_state->enclosed)
  1029. $this->errors[] = Tools::displayError('It is not possible to change the status of this order because you did not order any products.');
  1030. if (!count($this->errors))
  1031. {
  1032. $supply_order->id_supply_order_state = $state['id_supply_order_state'];
  1033. if ($supply_order->save())
  1034. {
  1035. // if pending_receipt,
  1036. // or if the order is being canceled,
  1037. // synchronizes StockAvailable
  1038. if (($new_state->pending_receipt && !$new_state->receipt_state) ||
  1039. ($old_state->receipt_state && $new_state->enclosed && !$new_state->receipt_state))
  1040. {
  1041. $supply_order_details = $supply_order->getEntries();
  1042. $products_done = array();
  1043. foreach ($supply_order_details as $supply_order_detail)
  1044. {
  1045. if (!in_array($supply_order_detail['id_product'], $products_done))
  1046. {
  1047. StockAvailable::synchronize($supply_order_detail['id_product']);
  1048. $products_done[] = $supply_order_detail['id_product'];
  1049. }
  1050. }
  1051. }
  1052. $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
  1053. $redirect = self::$currentIndex.'&token='.$token;
  1054. $this->redirect_after = $redirect.'&conf=5';
  1055. }
  1056. }
  1057. }
  1058. }
  1059. }
  1060. else
  1061. $this->errors[] = Tools::displayError('The selected supplier is not valid.');
  1062. }
  1063. }
  1064. // updates receipt
  1065. if (Tools::isSubmit('submitBulkUpdatesupply_order_detail') && Tools::isSubmit('id_supply_order'))
  1066. $this->postProcessUpdateReceipt();
  1067. // use template to create a supply order
  1068. if (Tools::isSubmit('create_supply_order') && Tools::isSubmit('id_supply_order'))
  1069. $this->postProcessCopyFromTemplate();
  1070. if ((!count($this->errors) && $this->is_editing_order) || !$this->is_editing_order)
  1071. parent::postProcess();
  1072. }
  1073. /**
  1074. * Exports CSV
  1075. */
  1076. protected function renderCSV()
  1077. {
  1078. // exports orders
  1079. if (Tools::isSubmit('csv_orders'))
  1080. {
  1081. $ids = array();
  1082. foreach ($this->_list as $entry)
  1083. $ids[] = $entry['id_supply_order'];
  1084. if (count($ids) <= 0)
  1085. return;
  1086. $id_lang = Context::getContext()->language->id;
  1087. $orders = new PrestaShopCollection('SupplyOrder', $id_lang);
  1088. $orders->where('is_template', '=', false);
  1089. $orders->where('id_supply_order', 'in', $ids);
  1090. $id_warehouse = $this->getCurrentWarehouse();
  1091. if ($id_warehouse != -1)
  1092. $orders->where('id_warehouse', '=', $id_warehouse);
  1093. $orders->getAll();
  1094. $csv = new CSV($orders, $this->l('supply_orders'));
  1095. $csv->export();
  1096. }
  1097. // exports details for all orders
  1098. else if (Tools::isSubmit('csv_orders_details'))
  1099. {
  1100. // header
  1101. header('Content-type: text/csv');
  1102. header('Content-Type: application/force-download; charset=UTF-8');
  1103. header('Cache-Control: no-store, no-cache');
  1104. header('Content-disposition: attachment; filename="'.$this->l('supply_orders_details').'.csv"');
  1105. // echoes details
  1106. $ids = array();
  1107. foreach ($this->_list as $entry)
  1108. $ids[] = $entry['id_supply_order'];
  1109. if (count($ids) <= 0)
  1110. return;
  1111. // for each supply order
  1112. $keys = array('id_product', 'id_product_attribute', 'reference', 'supplier_reference', 'ean13', 'upc', 'name',
  1113. 'unit_price_te', 'quantity_expected', 'quantity_received', 'price_te', 'discount_rate', 'discount_value_te',
  1114. 'price_with_discount_te', 'tax_rate', 'tax_value', 'price_ti', 'tax_value_with_order_discount',
  1115. 'price_with_order_discount_te', 'id_supply_order');
  1116. echo sprintf("%s\n", implode(';', array_map(array('CSVCore', 'wrap'), $keys)));
  1117. // overrides keys (in order to add FORMAT calls)
  1118. $keys = array('sod.id_product', 'sod.id_product_attribute', 'sod.reference', 'sod.supplier_reference', 'sod.ean13',
  1119. 'sod.upc', 'sod.name',
  1120. 'FORMAT(sod.unit_price_te, 2)', 'sod.quantity_expected', 'sod.quantity_received', 'FORMAT(sod.price_te, 2)',
  1121. 'FORMAT(sod.discount_rate, 2)', 'FORMAT(sod.discount_value_te, 2)',
  1122. 'FORMAT(sod.price_with_discount_te, 2)', 'FORMAT(sod.tax_rate, 2)', 'FORMAT(sod.tax_value, 2)',
  1123. 'FORMAT(sod.price_ti, 2)', 'FORMAT(sod.tax_value_with_order_discount, 2)',
  1124. 'FORMAT(sod.price_with_order_discount_te, 2)', 'sod.id_supply_order');
  1125. foreach ($ids as $id)
  1126. {
  1127. $query = new DbQuery();
  1128. $query->select(implode(', ', $keys));
  1129. $query->from('supply_order_detail', 'sod');
  1130. $query->leftJoin('supply_order', 'so', 'so.id_supply_order = sod.id_supply_order');
  1131. $id_warehouse = $this->getCurrentWarehouse();
  1132. if ($id_warehouse != -1)
  1133. $query->where('so.id_warehouse = '.(int)$id_warehouse);
  1134. $query->where('sod.id_supply_order = '.(int)$id);
  1135. $query->orderBy('sod.id_supply_order_detail DESC');
  1136. $resource = Db::getInstance()->query($query);
  1137. // gets details
  1138. while ($row = Db::getInstance()->nextRow($resource))
  1139. echo sprintf("%s\n", implode(';', array_map(array('CSVCore', 'wrap'), $row)));
  1140. }
  1141. }
  1142. // exports details for the given order
  1143. else if (Tools::isSubmit('csv_order_details') && Tools::getValue('id_supply_order'))
  1144. {
  1145. $supply_order = new SupplyOrder((int)Tools::getValue('id_supply_order'));
  1146. if (Validate::isLoadedObject($supply_order))
  1147. {
  1148. $details = $supply_order->getEntriesCollection();
  1149. $details->getAll();
  1150. $csv = new CSV($details, $this->l('supply_order').'_'.$supply_order->reference.'_details');
  1151. $csv->export();
  1152. }
  1153. }
  1154. }
  1155. /**
  1156. * Helper function for AdminSupplyOrdersController::postProcess()
  1157. *
  1158. * @see AdminSupplyOrdersController::postProcess()
  1159. */
  1160. protected function postProcessUpdateReceipt()
  1161. {
  1162. // gets all box selected
  1163. $rows = Tools::getValue('supply_order_detailBox');
  1164. if (!$rows)
  1165. {
  1166. $this->errors[] = Tools::displayError('You did not select any products to update.');
  1167. return;
  1168. }
  1169. // final array with id_supply_order_detail and value to update
  1170. $to_update = array();
  1171. // gets quantity for each id_order_detail
  1172. foreach ($rows as $row)
  1173. {
  1174. if (Tools::getValue('quantity_received_today_'.$row))
  1175. $to_update[$row] = (int)Tools::getValue('quantity_received_today_'.$row);
  1176. }
  1177. // checks if there is something to update
  1178. if (!count($to_update))
  1179. {
  1180. $this->errors[] = Tools::displayError('You did not select any products to update.');
  1181. return;
  1182. }
  1183. $totaly_received = true;
  1184. foreach ($to_update as $id_supply_order_detail => $quantity)
  1185. {
  1186. $supply_order_detail = new SupplyOrderDetail($id_supply_order_detail);
  1187. $supply_order = new SupplyOrder((int)Tools::getValue('id_supply_order'));
  1188. if (Validate::isLoadedObject($supply_order_detail) && Validate::isLoadedObject($supply_order))
  1189. {
  1190. // checks if quantity is valid
  1191. // It's possible to receive more quantity than expected in case of a shipping error from the supplier
  1192. if (!Validate::isInt($quantity) || $quantity <= 0)
  1193. $this->errors[] = sprintf(Tools::displayError('Quantity (%d) for product #%d is not valid'), (int)$quantity, (int)$id_supply_order_detail);
  1194. else // everything is valid : updates
  1195. {
  1196. if ((int)$quantity < (int)$supply_order_detail->quantity_expected)
  1197. $totaly_received = false;
  1198. // creates the history
  1199. $supplier_receipt_history = new SupplyOrderReceiptHistory();
  1200. $supplier_receipt_history->id_supply_order_detail = (int)$id_supply_order_detail;
  1201. $supplier_receipt_history->id_employee = (int)$this->context->employee->id;
  1202. $supplier_receipt_history->employee_firstname = pSQL($this->context->employee->firstname);
  1203. $supplier_receipt_history->employee_lastname = pSQL($this->context->employee->lastname);
  1204. $supplier_receipt_history->id_supply_order_state = (int)$supply_order->id_supply_order_state;
  1205. $supplier_receipt_history->quantity = (int)$quantity;
  1206. // updates quantity received
  1207. $supply_order_detail->quantity_received += (int)$quantity;
  1208. // if current state is "Pending receipt", then we sets it to "Order received in part"
  1209. if (3 == $supply_order->id_supply_order_state)
  1210. $supply_order->id_supply_order_state = 4;
  1211. // Adds to stock
  1212. $warehouse = new Warehouse($supply_order->id_warehouse);
  1213. if (!Validate::isLoadedObject($warehouse))
  1214. {
  1215. $this->errors[] = Tools::displayError('The warehouse could not be loaded.');
  1216. return;
  1217. }
  1218. $price = $supply_order_detail->unit_price_te;
  1219. // converts the unit price to the warehouse currency if needed
  1220. if ($supply_order->id_currency != $warehouse->id_currency)
  1221. {
  1222. // first, converts the price to the default currency
  1223. $price_converted_to_default_currency = Tools::convertPrice($supply_order_detail->unit_price_te, $supply_order->id_currency, false);
  1224. // then, converts the newly calculated pri-ce from the default currency to the needed currency
  1225. $price = Tools::ps_round(Tools::convertPrice($price_converted_to_default_currency,
  1226. $warehouse->id_currency,
  1227. true),
  1228. 6);
  1229. }
  1230. $manager = StockManagerFactory::getManager();
  1231. $res = $manager->addProduct($supply_order_detail->id_product,
  1232. $supply_order_detail->id_product_attribute,
  1233. $warehouse,
  1234. (int)$quantity,
  1235. Configuration::get('PS_STOCK_MVT_SUPPLY_ORDER'),
  1236. $price,
  1237. true,
  1238. $supply_order->id);
  1239. $location = Warehouse::getProductLocation($supply_order_detail->id_product,
  1240. $supply_order_detail->id_product_attribute,
  1241. $warehouse->id);
  1242. $res = Warehouse::setProductlocation($supply_order_detail->id_product,
  1243. $supply_order_detail->id_product_attribute,
  1244. $warehouse->id,
  1245. $location ? $location : '');
  1246. if ($res)
  1247. {
  1248. $supplier_receipt_history->add();
  1249. $supply_order_detail->save();
  1250. $supply_order->save();
  1251. StockAvailable::synchronize($supply_order_detail->id_product);
  1252. }
  1253. else
  1254. $this->errors[] = Tools::displayError('Something went wrong when setting warehouse on product record');
  1255. }
  1256. }
  1257. }
  1258. if ($totaly_received)
  1259. {
  1260. $supply_order->id_supply_order_state = 5;
  1261. $supply_order->save();
  1262. }
  1263. if (!count($this->errors))
  1264. {
  1265. // display confirm message
  1266. $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
  1267. $redirect = self::$currentIndex.'&token='.$token;
  1268. $this->redirect_after = $redirect.'&conf=4';
  1269. }
  1270. }
  1271. /**
  1272. * Display state action link
  1273. * @param string $token the token to add to the link
  1274. * @param int $id the identifier to add to the link
  1275. * @return string
  1276. */
  1277. public function displayUpdateReceiptLink($token = null, $id)
  1278. {
  1279. if (!array_key_exists('Receipt', self::$cache_lang))
  1280. self::$cache_lang['Receipt'] = $this->l('Update ongoing receipt of products');
  1281. $this->context->smarty->assign(array(
  1282. 'href' => self::$currentIndex.
  1283. '&'.$this->identifier.'='.$id.
  1284. '&update_receipt&token='.($token != null ? $token : $this->token),
  1285. 'action' => self::$cache_lang['Receipt'],
  1286. ));
  1287. return $this->context->smarty->fetch('helpers/list/list_action_supply_order_receipt.tpl');
  1288. }
  1289. /**
  1290. * Display receipt action link
  1291. * @param string $token the token to add to the link
  1292. * @param int $id the identifier to add to the link
  1293. * @return string
  1294. */
  1295. public function displayChangestateLink($token = null, $id)
  1296. {
  1297. if (!array_key_exists('State', self::$cache_lang))
  1298. self::$cache_lang['State'] = $this->l('Change status');
  1299. $this->context->smarty->assign(array(
  1300. 'href' => self::$currentIndex.
  1301. '&'.$this->identifier.'='.$id.
  1302. '&changestate&token='.($token != null ? $token : $this->token),
  1303. 'action' => self::$cache_lang['State'],
  1304. ));
  1305. return $this->context->smarty->fetch('helpers/list/list_action_supply_order_change_state.tpl');
  1306. }
  1307. /**
  1308. * Display state action link
  1309. * @param string $token the token to add to the link
  1310. * @param int $id the identifier to add to the link
  1311. * @return string
  1312. */
  1313. public function displayCreateSupplyOrderLink($token = null, $id)
  1314. {
  1315. if (!array_key_exists('CreateSupplyOrder', self::$cache_lang))
  1316. self::$cache_lang['CreateSupplyOrder'] = $this->l('Use this template to create a supply order');
  1317. if (!array_key_exists('CreateSupplyOrderConfirm', self::$cache_lang))
  1318. self::$cache_lang['CreateSupplyOrderConfirm'] = $this->l('Are you sure you want to use this template?');
  1319. $this->context->smarty->assign(array(
  1320. 'href' => self::$currentIndex.
  1321. '&'.$this->identifier.'='.$id.
  1322. '&create_supply_order&token='.($token != null ? $token : $this->token),
  1323. 'confirm' => self::$cache_lang['CreateSupplyOrderConfirm'],
  1324. 'action' => self::$cache_lang['CreateSupplyOrder'],
  1325. ));
  1326. return $this->context->smarty->fetch('helpers/list/list_action_supply_order_create_from_template.tpl');
  1327. }
  1328. public function renderDetails()
  1329. {
  1330. // tests if an id is submit
  1331. if (Tools::isSubmit('id_supply_order') && !Tools::isSubmit('display_product_history'))
  1332. {
  1333. // overrides attributes
  1334. $this->identifier = 'id_supply_order_history';
  1335. $this->table = 'supply_order_history';
  1336. $this->lang = false;
  1337. $this->actions = array();
  1338. $this->toolbar_btn = array();
  1339. $this->list_simple_header = true;
  1340. // gets current lang id
  1341. $lang_id = (int)$this->context->language->id;
  1342. // gets supply order id
  1343. $id_supply_order = (int)Tools::getValue('id_supply_order');
  1344. // creates new fields_list
  1345. $this->fields_list = array(
  1346. 'history_date' => array(
  1347. 'title' => $this->l('Last update'),
  1348. 'align' => 'left',
  1349. 'type' => 'datetime',
  1350. 'havingFilter' => true
  1351. ),
  1352. 'history_employee' => array(
  1353. 'title' => $this->l('Employee'),
  1354. 'align' => 'left',
  1355. 'havingFilter' => true
  1356. ),
  1357. 'history_state_name' => array(
  1358. 'title' => $this->l('Status'),
  1359. 'align' => 'left',
  1360. 'color' => 'color',
  1361. 'havingFilter' => true
  1362. ),
  1363. );
  1364. // loads history of the given order
  1365. unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter);
  1366. $this->_select = '
  1367. a.`date_add` as history_date,
  1368. CONCAT(a.`employee_lastname`, \' \', a.`employee_firstname`) as history_employee,
  1369. sosl.`name` as history_state_name,
  1370. sos.`color` as color';
  1371. $this->_join = '
  1372. LEFT JOIN `'._DB_PREFIX_.'supply_order_state` sos ON (a.`id_state` = sos.`id_supply_order_state`)
  1373. LEFT JOIN `'._DB_PREFIX_.'supply_order_state_lang` sosl ON
  1374. (
  1375. a.`id_state` = sosl.`id_supply_order_state`
  1376. AND sosl.`id_lang` = '.(int)$lang_id.'
  1377. )';
  1378. $this->_where = 'AND a.`id_supply_order` = '.(int)$id_supply_order;
  1379. $this->_orderBy = 'a.date_add';
  1380. $this->_orderWay = 'DESC';
  1381. return parent::renderList();
  1382. }
  1383. else if (Tools::isSubmit('id_supply_order') && Tools::isSubmit('display_product_history'))
  1384. {
  1385. $this->identifier = 'id_supply_order_receipt_history';
  1386. $this->table = 'supply_order_receipt_history';
  1387. $this->actions = array();
  1388. $this->toolbar_btn = array();
  1389. $this->list_simple_header = true;
  1390. $this->lang = false;
  1391. $lang_id = (int)$this->context->language->id;
  1392. $id_supply_order_detail = (int)Tools::getValue('id_supply_order');
  1393. unset($this->fields_list);
  1394. $this->fields_list = array(
  1395. 'date_add' => array(
  1396. 'title' => $this->l('Last update'),
  1397. 'align' => 'left',
  1398. 'type' => 'datetime',
  1399. 'havingFilter' => true
  1400. ),
  1401. 'employee' => array(
  1402. 'title' => $this->l('Employee'),
  1403. 'align' => 'left',
  1404. 'havingFilter' => true
  1405. ),
  1406. 'quantity' => array(
  1407. 'title' => $this->l('Quantity received'),
  1408. 'align' => 'left',
  1409. 'havingFilter' => true
  1410. ),
  1411. );
  1412. // loads history of the given order
  1413. unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter);
  1414. $this->_select = 'CONCAT(a.`employee_lastname`, \' \', a.`employee_firstname`) as employee';
  1415. $this->_where = 'AND a.`id_supply_order_detail` = '.(int)$id_supply_order_detail;
  1416. $this->_orderBy = 'a.date_add';
  1417. $this->_orderWay = 'DESC';
  1418. return parent::renderList();
  1419. }
  1420. }
  1421. /**
  1422. * method call when ajax request is made for search product to add to the order
  1423. * @TODO - Update this method to retreive the reference, ean13, upc corresponding to a product attribute
  1424. */
  1425. public function ajaxProcessSearchProduct()
  1426. {
  1427. // Get the search pattern
  1428. $pattern = pSQL(Tools::getValue('q', false));
  1429. if (!$pattern || $pattern == '' || strlen($pattern) < 1)
  1430. die();
  1431. // get supplier id
  1432. $id_supplier = (int)Tools::getValue('id_supplier', false);
  1433. // gets the currency
  1434. $id_currency = (int)Tools::getValue('id_currency', false);
  1435. // get lang from context
  1436. $id_lang = (int)Context::getContext()->language->id;
  1437. $query = new DbQuery();
  1438. $query->select('
  1439. CONCAT(p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\')) as id,
  1440. ps.product_supplier_reference as supplier_reference,
  1441. IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference,
  1442. IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13,
  1443. IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc,
  1444. md5(CONCAT(\''._COOKIE_KEY_.'\', p.id_product, \'_\', IFNULL(pa.id_product_attribute, \'0\'))) as checksum,
  1445. IFNULL(CONCAT(pl.name, \' : \', GROUP_CONCAT(DISTINCT agl.name, \' - \', al.name order by agl.name SEPARATOR \', \')), pl.name) as name
  1446. ');
  1447. $query->from('product', 'p');
  1448. $query->innerJoin('product_lang', 'pl', 'pl.id_product = p.id_product AND pl.id_lang = '.$id_lang);
  1449. $query->leftJoin('product_attribute', 'pa', 'pa.id_product = p.id_product');
  1450. $query->leftJoin('product_attribute_combination', 'pac', 'pac.id_product_attribute = pa.id_product_attribute');
  1451. $query->leftJoin('attribute', 'atr', 'atr.id_attribute = pac.id_attribute');
  1452. $query->leftJoin('attribute_lang', 'al', 'al.id_attribute = atr.id_attribute AND al.id_lang = '.$id_lang);
  1453. $query->leftJoin('attribute_group_lang', 'agl', 'agl.id_attribute_group = atr.id_attribute_group AND agl.id_lang = '.$id_lang);
  1454. $query->leftJoin('product_supplier', 'ps', 'ps.id_product = p.id_product AND ps.id_product_attribute = IFNULL(pa.id_product_attribute, 0)');
  1455. $query->where('(pl.name LIKE \'%'.$pattern.'%\' OR p.reference LIKE \'%'.$pattern.'%\' OR ps.product_supplier_reference LIKE \'%'.$pattern.'%\')');
  1456. $query->where('p.id_product NOT IN (SELECT pd.id_product FROM `'._DB_PREFIX_.'product_download` pd WHERE (pd.id_product = p.id_product))');
  1457. $query->where('p.is_virtual = 0 AND p.cache_is_pack = 0');
  1458. if ($id_supplier)
  1459. $query->where('ps.id_supplier = '.$id_supplier.' OR p.id_supplier = '.$id_supplier);
  1460. $query->groupBy('p.id_product, pa.id_product_attribute');
  1461. $items = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
  1462. foreach ($items as &$item)
  1463. {
  1464. $ids = explode('_', $item['id']);
  1465. $prices = ProductSupplier::getProductSupplierPrice($ids[0], $ids[1], $id_supplier, true);
  1466. if (count($prices))
  1467. $item['unit_price_te'] = Tools::convertPriceFull(
  1468. $prices['product_supplier_price_te'],
  1469. new Currency((int)$prices['id_currency']),
  1470. new Currency($id_currency)
  1471. );
  1472. }
  1473. if ($items)
  1474. die(Tools::jsonEncode($items));
  1475. die(1);
  1476. }
  1477. /**
  1478. * @see AdminController::renderView()
  1479. */
  1480. public function renderView()
  1481. {
  1482. $this->show_toolbar = true;
  1483. $this->toolbar_scroll = false;
  1484. $this->table = 'supply_order_detail';
  1485. $this->identifier = 'id_supply_order_detail';
  1486. $this->className = 'SupplyOrderDetail';
  1487. $this->colorOnBackground = false;
  1488. $this->lang = false;
  1489. $this->list_simple_header = true;
  1490. $this->list_no_link = true;
  1491. // gets the id supplier to view
  1492. $id_supply_order = (int)Tools::getValue('id_supply_order');
  1493. // gets global order information
  1494. $supply_order = new SupplyOrder((int)$id_supply_order);
  1495. if (Validate::isLoadedObject($supply_order))
  1496. {
  1497. if (!$supply_order->is_template)
  1498. $this->displayInformation($this->l('This interface allows you to display detailed information about your order.').'<br />');
  1499. else
  1500. $this->displayInformation($this->l('This interface allows you to display detailed information about your order template.').'<br />');
  1501. $lang_id = (int)$supply_order->id_lang;
  1502. // just in case..
  1503. unset($this->_select, $this->_join, $this->_where, $this->_orderBy, $this->_orderWay, $this->_group, $this->_filterHaving, $this->_filter);
  1504. // gets all information on the products ordered
  1505. $this->_where = 'AND a.`id_supply_order` = '.(int)$id_supply_order;
  1506. // gets the list ordered by price desc, without limit
  1507. $this->getList($lang_id, 'price_te', 'DESC', 0, false, false);
  1508. // gets the currency used in this order
  1509. $currency = new Currency($supply_order->id_currency);
  1510. // gets the warehouse where products will be received
  1511. $warehouse = new Warehouse($supply_order->id_warehouse);
  1512. // sets toolbar title with order reference
  1513. if (!$supply_order->is_template)
  1514. $this->toolbar_title = sprintf($this->l('Details on supply order #%s'), $supply_order->reference);
  1515. else
  1516. $this->toolbar_title = sprintf($this->l('Details on supply order template #%s'), $supply_order->reference);
  1517. // re-defines fields_list
  1518. $this->fields_list = array(
  1519. 'supplier_reference' => array(
  1520. 'title' => $this->l('Supplier Reference'),
  1521. 'align' => 'center',
  1522. 'orderby' => false,
  1523. 'filter' => false,
  1524. 'search' => false,
  1525. ),
  1526. 'reference' => array(
  1527. 'title' => $this->l('Reference'),
  1528. 'align' => 'center',
  1529. 'orderby' => false,
  1530. 'filter' => false,
  1531. 'search' => false,
  1532. ),
  1533. 'ean13' => array(
  1534. 'title' => $this->l('EAN-13 or JAN barcode'),
  1535. 'align' => 'center',
  1536. 'orderby' => false,
  1537. 'filter' => false,
  1538. 'search' => false,
  1539. ),
  1540. 'upc' => array(
  1541. 'title' => $this->l('UPC barcode'),
  1542. 'align' => 'center',
  1543. 'orderby' => false,
  1544. 'filter' => false,
  1545. 'search' => false,
  1546. ),
  1547. 'name' => array(
  1548. 'title' => $this->l('Name'),
  1549. 'orderby' => false,
  1550. 'filter' => false,
  1551. 'search' => false,
  1552. ),
  1553. 'unit_price_te' => array(
  1554. 'title' => $this->l('Unit price (tax excl.)'),
  1555. 'align' => 'right',
  1556. 'orderby' => false,
  1557. 'filter' => false,
  1558. 'search' => false,
  1559. 'type' => 'price',
  1560. 'currency' => true,
  1561. ),
  1562. 'quantity_expected' => array(
  1563. 'title' => $this->l('Quantity'),
  1564. 'align' => 'right',
  1565. 'orderby' => false,
  1566. 'filter' => false,
  1567. 'search' => false,
  1568. ),
  1569. 'price_te' => array(
  1570. 'title' => $this->l('Price (tax excl.)'),
  1571. 'align' => 'right',
  1572. 'orderby' => false,
  1573. 'filter' => false,
  1574. 'search' => false,
  1575. 'type' => 'price',
  1576. 'currency' => true,
  1577. ),
  1578. 'discount_rate' => array(
  1579. 'title' => $this->l('Discount percentage'),
  1580. 'align' => 'right',
  1581. 'orderby' => false,
  1582. 'filter' => false,
  1583. 'search' => false,
  1584. 'suffix' => '%',
  1585. ),
  1586. 'discount_value_te' => array(
  1587. 'title' => $this->l('Discount value (tax excl.)'),
  1588. 'align' => 'right',
  1589. 'orderby' => false,
  1590. 'filter' => false,
  1591. 'search' => false,
  1592. 'type' => 'price',
  1593. 'currency' => true,
  1594. ),
  1595. 'price_with_discount_te' => array(
  1596. 'title' => $this->l('Price with product discount (tax excl.)'),
  1597. 'align' => 'right',
  1598. 'orderby' => false,
  1599. 'filter' => false,
  1600. 'search' => false,
  1601. 'type' => 'price',
  1602. 'currency' => true,
  1603. ),
  1604. 'tax_rate' => array(
  1605. 'title' => $this->l('Tax rate'),
  1606. 'align' => 'right',
  1607. 'orderby' => false,
  1608. 'filter' => false,
  1609. 'search' => false,
  1610. 'suffix' => '%',
  1611. ),
  1612. 'tax_value' => array(
  1613. 'title' => $this->l('Tax value'),
  1614. 'align' => 'right',
  1615. 'orderby' => false,
  1616. 'filter' => false,
  1617. 'search' => false,
  1618. 'type' => 'price',
  1619. 'currency' => true,
  1620. ),
  1621. 'price_ti' => array(
  1622. 'title' => $this->l('Price (tax incl.)'),
  1623. 'align' => 'right',
  1624. 'orderby' => false,
  1625. 'filter' => false,
  1626. 'search' => false,
  1627. 'type' => 'price',
  1628. 'currency' => true,
  1629. ),
  1630. );
  1631. //some staff before render list
  1632. foreach ($this->_list as &$item)
  1633. {
  1634. $item['discount_rate'] = Tools::ps_round($item['discount_rate'], 4);
  1635. $item['tax_rate'] = Tools::ps_round($item['tax_rate'], 4);
  1636. $item['id_currency'] = $currency->id;
  1637. }
  1638. // unsets some buttons
  1639. unset($this->toolbar_btn['export-csv-orders']);
  1640. unset($this->toolbar_btn['export-csv-details']);
  1641. unset($this->toolbar_btn['new']);
  1642. // renders list
  1643. $helper = new HelperList();
  1644. $this->setHelperDisplay($helper);
  1645. $helper->actions = array();
  1646. $helper->show_toolbar = false;
  1647. $helper->toolbar_btn = $this->toolbar_btn;
  1648. $content = $helper->generateList($this->_list, $this->fields_list);
  1649. // display these global order informations
  1650. $this->tpl_view_vars = array(
  1651. 'supply_order_detail_content' => $content,
  1652. 'supply_order_warehouse' => (Validate::isLoadedObject($warehouse) ? $warehouse->name : ''),
  1653. 'supply_order_reference' => $supply_order->reference,
  1654. 'supply_order_supplier_name' => $supply_order->supplier_name,
  1655. 'supply_order_creation_date' => Tools::displayDate($supply_order->date_add,null , false),
  1656. 'supply_order_last_update' => Tools::displayDate($supply_order->date_upd,null , false),
  1657. 'supply_order_expected' => Tools::displayDate($supply_order->date_delivery_expected,null , false),
  1658. 'supply_order_discount_rate' => Tools::ps_round($supply_order->discount_rate, 2),
  1659. 'supply_order_total_te' => Tools::displayPrice($supply_order->total_te, $currency),
  1660. 'supply_order_discount_value_te' => Tools::displayPrice($supply_order->discount_value_te, $currency),
  1661. 'supply_order_total_with_discount_te' => Tools::displayPrice($supply_order->total_with_discount_te, $currency),
  1662. 'supply_order_total_tax' => Tools::displayPrice($supply_order->total_tax, $currency),
  1663. 'supply_order_total_ti' => Tools::displayPrice($supply_order->total_ti, $currency),
  1664. 'supply_order_currency' => $currency,
  1665. 'is_template' => $supply_order->is_template,
  1666. );
  1667. }
  1668. return parent::renderView();
  1669. }
  1670. /**
  1671. * Callback used to display custom content for a given field
  1672. * @param int $id_supply_order
  1673. * @param string $tr
  1674. * @return string $content
  1675. */
  1676. public function printExportIcons($id_supply_order, $tr)
  1677. {
  1678. $supply_order = new SupplyOrder((int)$id_supply_order);
  1679. if (!Validate::isLoadedObject($supply_order))
  1680. return;
  1681. $supply_order_state = new SupplyOrderState($supply_order->id_supply_order_state);
  1682. if (!Validate::isLoadedObject($supply_order_state))
  1683. return;
  1684. $content = '';
  1685. if ($supply_order_state->editable == false)
  1686. $content .= '<a class="btn btn-default" href="'.$this->context->link->getAdminLink('AdminPdf').'&submitAction=generateSupplyOrderFormPDF&id_supply_order='.(int)$supply_order->id.'" title="'.$this->l('Export as PDF').'"><i class="icon-print"></i></a>';
  1687. if ($supply_order_state->enclosed == true && $supply_order_state->receipt_state == true)
  1688. $content .= '<a href="'.$this->context->link->getAdminLink('AdminSupplyOrders').'&amp;id_supply_order='.(int)$supply_order->id.'
  1689. &csv_order_details" title='.$this->l('Export as CSV').'">
  1690. <i class="icon-table"></i></a>';
  1691. return $content;
  1692. }
  1693. /**
  1694. * Assigns default actions in toolbar_btn smarty var, if they are not set.
  1695. * uses override to specifically add, modify or remove items
  1696. * @see AdminSupplier::initToolbar()
  1697. */
  1698. public function initToolbar()
  1699. {
  1700. switch ($this->display)
  1701. {
  1702. case 'update_order_state':
  1703. $this->toolbar_btn['save'] = array(
  1704. 'href' => '#',
  1705. 'desc' => $this->l('Save')
  1706. );
  1707. case 'update_receipt':
  1708. // Default cancel button - like old back link
  1709. if (!isset($this->no_back) || $this->no_back == false)
  1710. {
  1711. $back = Tools::safeOutput(Tools::getValue('back', ''));
  1712. if (empty($back))
  1713. $back = self::$currentIndex.'&token='.$this->token;
  1714. $this->toolbar_btn['cancel'] = array(
  1715. 'href' => $back,
  1716. 'desc' => $this->l('Cancel')
  1717. );
  1718. }
  1719. break;
  1720. case 'add':
  1721. case 'edit':
  1722. $this->toolbar_btn['save-and-stay'] = array(
  1723. 'href' => '#',
  1724. 'desc' => $this->l('Save and stay')
  1725. );
  1726. default:
  1727. parent::initToolbar();
  1728. }
  1729. }
  1730. /**
  1731. * Overrides AdminController::afterAdd()
  1732. * @see AdminController::afterAdd()
  1733. * @param ObjectModel $object
  1734. * @return bool
  1735. */
  1736. protected function afterAdd($object)
  1737. {
  1738. if (is_numeric(Tools::getValue('load_products')))
  1739. $this->loadProducts((int)Tools::getValue('load_products'));
  1740. $this->object = $object;
  1741. return true;
  1742. }
  1743. /**
  1744. * Loads products which quantity (hysical quantity) is equal or less than $threshold
  1745. * @param int $threshold
  1746. */
  1747. protected function loadProducts($threshold)
  1748. {
  1749. // if there is already an order
  1750. if (Tools::getValue('id_supply_order'))
  1751. $supply_order = new SupplyOrder((int)Tools::getValue('id_supply_order'));
  1752. else // else, we just created a new order
  1753. $supply_order = $this->object;
  1754. // if order is not valid, return;
  1755. if (!Validate::isLoadedObject($supply_order))
  1756. return;
  1757. // resets products if needed
  1758. if (Tools::getValue('id_supply_order'))
  1759. $supply_order->resetProducts();
  1760. // gets products
  1761. $query = new DbQuery();
  1762. $query->select('ps.id_product,
  1763. ps.id_product_attribute,
  1764. ps.product_supplier_reference as supplier_reference,
  1765. ps.product_supplier_price_te as unit_price_te,
  1766. ps.id_currency,
  1767. IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference,
  1768. IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13,
  1769. IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc');
  1770. $query->from('product_supplier', 'ps');
  1771. $query->leftJoin('stock', 's', '
  1772. s.id_product = ps.id_product
  1773. AND s.id_product_attribute = ps.id_product_attribute
  1774. AND s.id_warehouse = '.(int)$supply_order->id_warehouse);
  1775. $query->innerJoin('warehouse_product_location', 'wpl', '
  1776. wpl.id_product = ps.id_product
  1777. AND wpl.id_product_attribute = ps.id_product_attribute
  1778. AND wpl.id_warehouse = '.(int)$supply_order->id_warehouse.'
  1779. ');
  1780. $query->leftJoin('product', 'p', 'p.id_product = ps.id_product');
  1781. $query->leftJoin('product_attribute', 'pa', '
  1782. pa.id_product_attribute = ps.id_product_attribute
  1783. AND p.id_product = ps.id_product
  1784. ');
  1785. $query->where('ps.id_supplier = '.(int)$supply_order->id_supplier);
  1786. // gets items
  1787. $items = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
  1788. // loads order currency
  1789. $order_currency = new Currency($supply_order->id_currency);
  1790. if (!Validate::isLoadedObject($order_currency))
  1791. return;
  1792. $manager = StockManagerFactory::getManager();
  1793. foreach ($items as $item)
  1794. {
  1795. $diff = (int)$threshold;
  1796. if ($supply_order->is_template != 1)
  1797. {
  1798. $real_quantity = (int)$manager->getProductRealQuantities($item['id_product'], $item['id_product_attribute'], $supply_order->id_warehouse, true);
  1799. $diff = (int)$threshold - (int)$real_quantity;
  1800. }
  1801. if ($diff >= 0)
  1802. {
  1803. // sets supply_order_detail
  1804. $supply_order_detail = new SupplyOrderDetail();
  1805. $supply_order_detail->id_supply_order = $supply_order->id;
  1806. $supply_order_detail->id_currency = $order_currency->id;
  1807. $supply_order_detail->id_product = $item['id_product'];
  1808. $supply_order_detail->id_product_attribute = $item['id_product_attribute'];
  1809. $supply_order_detail->reference = $item['reference'];
  1810. $supply_order_detail->supplier_reference = $item['supplier_reference'];
  1811. $supply_order_detail->name = Product::getProductName($item['id_product'], $item['id_product_attribute'], $supply_order->id_lang);
  1812. $supply_order_detail->ean13 = $item['ean13'];
  1813. $supply_order_detail->upc = $item['upc'];
  1814. $supply_order_detail->quantity_expected = ((int)$diff == 0) ? 1 : (int)$diff;
  1815. $supply_order_detail->exchange_rate = $order_currency->conversion_rate;
  1816. $product_currency = new Currency($item['id_currency']);
  1817. if (Validate::isLoadedObject($product_currency))
  1818. $supply_order_detail->unit_price_te = Tools::convertPriceFull($item['unit_price_te'], $product_currency, $order_currency);
  1819. else
  1820. $supply_order_detail->unit_price_te = 0;
  1821. $supply_order_detail->save();
  1822. unset($product_currency);
  1823. }
  1824. }
  1825. // updates supply order
  1826. $supply_order->update();
  1827. }
  1828. /**
  1829. * Overrides AdminController::beforeAdd()
  1830. * @see AdminController::beforeAdd()
  1831. * @param ObjectModel $object
  1832. */
  1833. public function beforeAdd($object)
  1834. {
  1835. if (Tools::isSubmit('is_template'))
  1836. $object->is_template = 1;
  1837. return true;
  1838. }
  1839. /**
  1840. * Helper function for AdminSupplyOrdersController::postProcess()
  1841. * @see AdminSupplyOrdersController::postProcess()
  1842. */
  1843. protected function postProcessCopyFromTemplate()
  1844. {
  1845. // gets SupplyOrder and checks if it is valid
  1846. $id_supply_order = (int)Tools::getValue('id_supply_order');
  1847. $supply_order = new SupplyOrder($id_supply_order);
  1848. if (!Validate::isLoadedObject($supply_order))
  1849. $this->errors[] = Tools::displayError('This template could not be copied.');
  1850. // gets SupplyOrderDetail
  1851. $entries = $supply_order->getEntriesCollection($supply_order->id_lang);
  1852. // updates SupplyOrder so that it is not a template anymore
  1853. $language = new Language($supply_order->id_lang);
  1854. $ref = $supply_order->reference;
  1855. $ref .= ' ('.date($language->date_format_full).')';
  1856. $supply_order->reference = $ref;
  1857. $supply_order->is_template = 0;
  1858. $supply_order->id = (int)0;
  1859. $supply_order->save();
  1860. // copies SupplyOrderDetail
  1861. foreach ($entries as $entry)
  1862. {
  1863. $entry->id_supply_order = $supply_order->id;
  1864. $entry->id = (int)0;
  1865. $entry->save();
  1866. }
  1867. // redirect when done
  1868. $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
  1869. $redirect = self::$currentIndex.'&token='.$token;
  1870. $this->redirect_after = $redirect.'&conf=19';
  1871. }
  1872. /**
  1873. * Gets the current warehouse used
  1874. *
  1875. * @return int id_warehouse
  1876. */
  1877. protected function getCurrentWarehouse()
  1878. {
  1879. static $warehouse = 0;
  1880. if ($warehouse == 0)
  1881. {
  1882. $warehouse = -1; // all warehouses
  1883. if ((int)Tools::getValue('id_warehouse'))
  1884. $warehouse = (int)Tools::getValue('id_warehouse');
  1885. }
  1886. return $warehouse;
  1887. }
  1888. /**
  1889. * Gets the current filter used
  1890. *
  1891. * @return int status
  1892. */
  1893. protected function getFilterStatus()
  1894. {
  1895. static $status = 0;
  1896. $status = 0;
  1897. if (Tools::getValue('filter_status') === 'on')
  1898. $status = 1;
  1899. return $status;
  1900. }
  1901. public function initProcess()
  1902. {
  1903. if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))
  1904. {
  1905. $this->warnings[md5('PS_ADVANCED_STOCK_MANAGEMENT')] = $this->l('You need to activate advanced stock management prior to using this feature.');
  1906. return false;
  1907. }
  1908. parent::initProcess();
  1909. }
  1910. }