combinations.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. <?php
  2. /* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
  3. * Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2018-2019 Frédéric France <frederic.france@netlogic.fr>
  5. * Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. require '../main.inc.php';
  21. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  22. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  23. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
  24. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
  25. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  26. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
  27. $langs->loadLangs(array("products", "other"));
  28. $id = GETPOST('id', 'int');
  29. $valueid = GETPOST('valueid', 'int');
  30. $ref = GETPOST('ref', 'alpha');
  31. $weight_impact = price2num(GETPOST('weight_impact', 'alpha'), 2);
  32. $price_impact_percent = (bool) GETPOST('price_impact_percent');
  33. if ($price_impact_percent) {
  34. $price_impact = price2num(GETPOST('price_impact', 'alpha'), 2);
  35. } else {
  36. $price_impact = price2num(GETPOST('price_impact', 'alpha'), 'MU');
  37. }
  38. $level_price_impact = GETPOST('level_price_impact', 'array');
  39. $level_price_impact_percent = GETPOST('level_price_impact_percent', 'array');
  40. $reference = GETPOST('reference', 'alpha');
  41. $form = new Form($db);
  42. $action = GETPOST('action', 'aZ09');
  43. $massaction = GETPOST('massaction', 'alpha');
  44. $show_files = GETPOST('show_files', 'int');
  45. $confirm = GETPOST('confirm', 'alpha');
  46. $toselect = GETPOST('toselect', 'array');
  47. $cancel = GETPOST('cancel', 'alpha');
  48. $delete_product = GETPOST('delete_product', 'alpha');
  49. $subaction = GETPOST('subaction', 'aZ09');
  50. $backtopage = GETPOST('backtopage', 'alpha');
  51. $sortfield = GETPOST('sortfield', 'aZ09comma');
  52. $sortorder = GETPOST('sortorder', 'aZ09comma');
  53. // Security check
  54. $fieldvalue = (!empty($id) ? $id : $ref);
  55. $fieldtype = (!empty($ref) ? 'ref' : 'rowid');
  56. $prodstatic = new Product($db);
  57. $prodattr = new ProductAttribute($db);
  58. $prodattr_val = new ProductAttributeValue($db);
  59. $object = new Product($db);
  60. if ($id > 0 || $ref) {
  61. $object->fetch($id, $ref);
  62. }
  63. $selectedvariant = !empty($_SESSION['addvariant_'.$object->id]) ? $_SESSION['addvariant_'.$object->id] : 0;
  64. // Security check
  65. if (empty($conf->variants->enabled)) {
  66. accessforbidden('Module not enabled');
  67. }
  68. if ($user->socid > 0) { // Protection if external user
  69. accessforbidden();
  70. }
  71. if ($object->id > 0) {
  72. if ($object->type == $object::TYPE_PRODUCT) {
  73. restrictedArea($user, 'produit', $object->id, 'product&product', '', '');
  74. }
  75. if ($object->type == $object::TYPE_SERVICE) {
  76. restrictedArea($user, 'service', $object->id, 'product&product', '', '');
  77. }
  78. } else {
  79. restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
  80. }
  81. $usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire));
  82. $usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer));
  83. $usercandelete = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer));
  84. /*
  85. * Actions
  86. */
  87. if ($cancel) {
  88. $action = '';
  89. $massaction = '';
  90. unset($_SESSION['addvariant_'.$object->id]);
  91. }
  92. if (!$object->isProduct() && !$object->isService()) {
  93. header('Location: '.dol_buildpath('/product/card.php?id='.$object->id, 2));
  94. exit();
  95. }
  96. if ($action == 'add') {
  97. unset($selectedvariant);
  98. unset($_SESSION['addvariant_'.$object->id]);
  99. }
  100. if ($action == 'create' && GETPOST('selectvariant', 'alpha')) { // We click on select combination
  101. $action = 'add';
  102. $attribute_id = GETPOST('attribute', 'int');
  103. $attribute_value_id = GETPOST('value', 'int');
  104. if ($attribute_id> 0 && $attribute_value_id > 0) {
  105. $feature = $attribute_id . '-' . $attribute_value_id;
  106. $selectedvariant[$feature] = $feature;
  107. $_SESSION['addvariant_'.$object->id] = $selectedvariant;
  108. }
  109. }
  110. if ($action == 'create' && $subaction == 'delete') { // We click on select combination
  111. $action = 'add';
  112. $feature = GETPOST('feature', 'intcomma');
  113. if (isset($selectedvariant[$feature])) {
  114. unset($selectedvariant[$feature]);
  115. $_SESSION['addvariant_'.$object->id] = $selectedvariant;
  116. }
  117. }
  118. $prodcomb = new ProductCombination($db);
  119. $prodcomb2val = new ProductCombination2ValuePair($db);
  120. $productCombination2ValuePairs1 = array();
  121. if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha') && empty($subaction)) { // We click on Create all defined combinations
  122. //$features = GETPOST('features', 'array');
  123. $features = $_SESSION['addvariant_'.$object->id];
  124. if (!$features) {
  125. if ($action == 'create') {
  126. setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors');
  127. }
  128. } else {
  129. $reference = trim($reference);
  130. if (empty($reference)) {
  131. $reference = false;
  132. }
  133. $weight_impact = price2num($weight_impact);
  134. $price_impact = price2num($price_impact);
  135. // for conf PRODUIT_MULTIPRICES
  136. if ($conf->global->PRODUIT_MULTIPRICES) {
  137. $level_price_impact = array_map('price2num', $level_price_impact);
  138. } else {
  139. $level_price_impact = array(1 => $price_impact);
  140. $level_price_impact_percent = array(1 => $price_impact_percent);
  141. }
  142. $sanit_features = array();
  143. //First, sanitize
  144. foreach ($features as $feature) {
  145. $explode = explode('-', $feature);
  146. if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) {
  147. continue;
  148. }
  149. // Valuepair
  150. $sanit_features[$explode[0]] = $explode[1];
  151. $tmp = new ProductCombination2ValuePair($db);
  152. $tmp->fk_prod_attr = $explode[0];
  153. $tmp->fk_prod_attr_val = $explode[1];
  154. $productCombination2ValuePairs1[] = $tmp;
  155. }
  156. $db->begin();
  157. // sanit_feature is an array with 1 (and only 1) value per attribute.
  158. // For example: Color->blue, Size->Small, Option->2
  159. //var_dump($sanit_features);
  160. if (!$prodcomb->fetchByProductCombination2ValuePairs($id, $sanit_features)) {
  161. $result = $prodcomb->createProductCombination($user, $object, $sanit_features, array(), $level_price_impact_percent, $level_price_impact, $weight_impact, $reference);
  162. if ($result > 0) {
  163. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  164. unset($_SESSION['addvariant_'.$object->id]);
  165. $db->commit();
  166. header('Location: '.dol_buildpath('/variants/combinations.php?id='.$id, 2));
  167. exit();
  168. } else {
  169. $langs->load("errors");
  170. setEventMessages($prodcomb->error, $prodcomb->errors, 'errors');
  171. }
  172. } else {
  173. setEventMessages($langs->trans('ErrorRecordAlreadyExists'), null, 'errors');
  174. }
  175. $db->rollback();
  176. }
  177. } elseif (!empty($massaction)) {
  178. $bulkaction = $massaction;
  179. $error = 0;
  180. $db->begin();
  181. foreach ($toselect as $prodid) {
  182. // need create new of Product to prevent rename dir behavior
  183. $prodstatic = new Product($db);
  184. if ($prodstatic->fetch($prodid) < 0) {
  185. continue;
  186. }
  187. if ($bulkaction == 'on_sell') {
  188. $prodstatic->status = 1;
  189. $res = $prodstatic->update($prodstatic->id, $user);
  190. if ($res <= 0) {
  191. setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
  192. $error++;
  193. break;
  194. }
  195. } elseif ($bulkaction == 'on_buy') {
  196. $prodstatic->status_buy = 1;
  197. $res = $prodstatic->update($prodstatic->id, $user);
  198. if ($res <= 0) {
  199. setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
  200. $error++;
  201. break;
  202. }
  203. } elseif ($bulkaction == 'not_sell') {
  204. $prodstatic->status = 0;
  205. $res = $prodstatic->update($prodstatic->id, $user);
  206. if ($res <= 0) {
  207. setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
  208. $error++;
  209. break;
  210. }
  211. } elseif ($bulkaction == 'not_buy') {
  212. $prodstatic->status_buy = 0;
  213. $res = $prodstatic->update($prodstatic->id, $user);
  214. if ($res <= 0) {
  215. setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
  216. $error++;
  217. break;
  218. }
  219. } elseif ($bulkaction == 'delete') {
  220. $res = $prodstatic->delete($user, $prodstatic->id);
  221. if ($res <= 0) {
  222. setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
  223. $error++;
  224. break;
  225. }
  226. } else {
  227. break;
  228. }
  229. }
  230. if ($error) {
  231. $db->rollback();
  232. if (empty($prodstatic->error)) {
  233. setEventMessages($langs->trans('CoreErrorMessage'), null, 'errors');
  234. }
  235. } else {
  236. $db->commit();
  237. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  238. }
  239. } elseif ($action === 'update' && $valueid > 0) {
  240. if ($prodcomb->fetch($valueid) < 0) {
  241. dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
  242. exit();
  243. }
  244. $prodcomb->variation_weight = price2num($weight_impact);
  245. // for conf PRODUIT_MULTIPRICES
  246. if ($conf->global->PRODUIT_MULTIPRICES) {
  247. $level_price_impact = array_map('price2num', $level_price_impact);
  248. $prodcomb->variation_price = $level_price_impact[1];
  249. $prodcomb->variation_price_percentage = (bool) $level_price_impact_percent[1];
  250. } else {
  251. $level_price_impact = array(1 => $price_impact);
  252. $level_price_impact_percent = array(1 => $price_impact_percent);
  253. $prodcomb->variation_price = $price_impact;
  254. $prodcomb->variation_price_percentage = $price_impact_percent;
  255. }
  256. if ($conf->global->PRODUIT_MULTIPRICES) {
  257. $prodcomb->combination_price_levels = array();
  258. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  259. $productCombinationLevel = new ProductCombinationLevel($db);
  260. $productCombinationLevel->fk_product_attribute_combination = $prodcomb->id;
  261. $productCombinationLevel->fk_price_level = $i;
  262. $productCombinationLevel->variation_price = $level_price_impact[$i];
  263. $productCombinationLevel->variation_price_percentage = (bool) $level_price_impact_percent[$i];
  264. $prodcomb->combination_price_levels[$i] = $productCombinationLevel;
  265. }
  266. }
  267. if ($prodcomb->update($user) > 0) {
  268. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  269. header('Location: '.dol_buildpath('/variants/combinations.php?id='.$id, 2));
  270. exit();
  271. } else {
  272. setEventMessages($prodcomb->error, $prodcomb->errors, 'errors');
  273. }
  274. }
  275. // Reload variants
  276. $productCombinations = $prodcomb->fetchAllByFkProductParent($object->id);
  277. if ($action === 'confirm_deletecombination') {
  278. if ($prodcomb->fetch($valueid) > 0) {
  279. $db->begin();
  280. if ($prodcomb->delete($user) > 0 && (empty($delete_product) || ($delete_product == 'on' && $prodstatic->fetch($prodcomb->fk_product_child) > 0 && $prodstatic->delete($user) > 0))) {
  281. $db->commit();
  282. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  283. header('Location: '.dol_buildpath('/variants/combinations.php?id='.$object->id, 2));
  284. exit();
  285. }
  286. $db->rollback();
  287. setEventMessages($langs->trans('ProductCombinationAlreadyUsed'), null, 'errors');
  288. $action = '';
  289. }
  290. } elseif ($action === 'edit') {
  291. if ($prodcomb->fetch($valueid) < 0) {
  292. dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
  293. exit();
  294. }
  295. $weight_impact = $prodcomb->variation_weight;
  296. $price_impact = $prodcomb->variation_price;
  297. $price_impact_percent = $prodcomb->variation_price_percentage;
  298. $productCombination2ValuePairs1 = $prodcomb2val->fetchByFkCombination($valueid);
  299. } elseif ($action === 'confirm_copycombination') {
  300. //Check destination product
  301. $dest_product = GETPOST('dest_product');
  302. if ($prodstatic->fetch('', $dest_product) > 0) {
  303. //To prevent from copying to the same product
  304. if ($prodstatic->ref != $object->ref) {
  305. if ($prodcomb->copyAll($user, $object->id, $prodstatic) > 0) {
  306. header('Location: '.dol_buildpath('/variants/combinations.php?id='.$prodstatic->id, 2));
  307. exit();
  308. } else {
  309. setEventMessages($langs->trans('ErrorCopyProductCombinations'), null, 'errors');
  310. }
  311. }
  312. } else {
  313. setEventMessages($langs->trans('ErrorDestinationProductNotFound'), null, 'errors');
  314. }
  315. }
  316. /*
  317. * View
  318. */
  319. $form = new Form($db);
  320. if (!empty($id) || !empty($ref)) {
  321. llxHeader("", "", $langs->trans("CardProduct".$object->type));
  322. $showbarcode = empty($conf->barcode->enabled) ? 0 : 1;
  323. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  324. $showbarcode = 0;
  325. }
  326. $head = product_prepare_head($object);
  327. $titre = $langs->trans("CardProduct".$object->type);
  328. $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
  329. print dol_get_fiche_head($head, 'combinations', $titre, -1, $picto);
  330. $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?type='.$object->type.'">'.$langs->trans("BackToList").'</a>';
  331. $object->next_prev_filter = " fk_product_type = ".$object->type;
  332. dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref', '', '', '', 0, '', '');
  333. print '<div class="fichecenter">';
  334. print '<div class="underbanner clearboth"></div>';
  335. print '<table class="border centpercent tableforfield">';
  336. // Type
  337. if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  338. $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service");
  339. print '<tr><td class="titlefieldcreate">';
  340. print (empty($conf->global->PRODUCT_DENY_CHANGE_PRODUCT_TYPE)) ? $form->editfieldkey("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat) : $langs->trans('Type');
  341. print '</td><td>';
  342. print $form->editfieldval("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat);
  343. print '</td></tr>';
  344. }
  345. // TVA
  346. print '<tr><td class="titlefieldcreate">'.$langs->trans("DefaultTaxRate").'</td><td>';
  347. $positiverates = '';
  348. if (price2num($object->tva_tx)) {
  349. $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx);
  350. }
  351. if (price2num($object->localtax1_type)) {
  352. $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx);
  353. }
  354. if (price2num($object->localtax2_type)) {
  355. $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx);
  356. }
  357. if (empty($positiverates)) {
  358. $positiverates = '0';
  359. }
  360. echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr);
  361. /*
  362. if ($object->default_vat_code)
  363. {
  364. print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
  365. }
  366. else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/
  367. print '</td></tr>';
  368. // Price
  369. print '<tr><td>'.$langs->trans("SellingPrice").'</td><td>';
  370. if ($object->price_base_type == 'TTC') {
  371. print price($object->price_ttc).' '.$langs->trans($object->price_base_type);
  372. } else {
  373. print price($object->price).' '.$langs->trans($object->price_base_type);
  374. }
  375. print '</td></tr>';
  376. // Price minimum
  377. print '<tr><td>'.$langs->trans("MinPrice").'</td><td>';
  378. if ($object->price_base_type == 'TTC') {
  379. print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type);
  380. } else {
  381. print price($object->price_min).' '.$langs->trans($object->price_base_type);
  382. }
  383. print '</td></tr>';
  384. // Weight
  385. print '<tr><td>'.$langs->trans("Weight").'</td><td>';
  386. if ($object->weight != '') {
  387. print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units);
  388. } else {
  389. print '&nbsp;';
  390. }
  391. print "</td></tr>\n";
  392. print "</table>\n";
  393. print '</div>';
  394. print '<div style="clear:both"></div>';
  395. print dol_get_fiche_end();
  396. $listofvariantselected = '';
  397. // Create or edit a varian
  398. if ($action == 'add' || ($action == 'edit')) {
  399. if ($action == 'add') {
  400. $title = $langs->trans('NewProductCombination');
  401. // print dol_get_fiche_head();
  402. $features = $_SESSION['addvariant_'.$object->id];
  403. //First, sanitize
  404. $listofvariantselected = '<div id="parttoaddvariant">';
  405. if (!empty($features)) {
  406. $toprint = array();
  407. foreach ($features as $feature) {
  408. $explode = explode('-', $feature);
  409. if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) {
  410. continue;
  411. }
  412. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #ddd;">' . $prodattr->label.' : '.$prodattr_val->value .
  413. ' <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=create&subaction=delete&feature='.urlencode($feature).'">' . img_delete() . '</a></li>';
  414. }
  415. $listofvariantselected .= '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  416. }
  417. $listofvariantselected .= '</div>';
  418. //print dol_get_fiche_end();
  419. } else {
  420. $title = $langs->trans('EditProductCombination');
  421. }
  422. if ($action == 'add') {
  423. $prodattr_all = $prodattr->fetchAll();
  424. if (!$selected) {
  425. $selected = $prodattr_all[key($prodattr_all)]->id;
  426. }
  427. $prodattr_alljson = array();
  428. foreach ($prodattr_all as $each) {
  429. $prodattr_alljson[$each->id] = $each;
  430. }
  431. ?>
  432. <script type="text/javascript">
  433. variants_available = <?php echo json_encode($prodattr_alljson); ?>;
  434. variants_selected = {
  435. index: [],
  436. info: []
  437. };
  438. <?php
  439. foreach ($productCombination2ValuePairs1 as $pc2v) {
  440. $prodattr_val->fetch($pc2v->fk_prod_attr_val);
  441. ?>
  442. variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>);
  443. variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = {
  444. attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>],
  445. value: {
  446. id: <?php echo $pc2v->fk_prod_attr_val ?>,
  447. label: '<?php echo $prodattr_val->value ?>'
  448. }
  449. };
  450. <?php
  451. }
  452. ?>
  453. restoreAttributes = function() {
  454. jQuery("select[name=attribute]").empty().append('<option value="-1">&nbsp;</option>');
  455. jQuery.each(variants_available, function (key, val) {
  456. if (jQuery.inArray(val.id, variants_selected.index) == -1) {
  457. jQuery("select[name=attribute]").append('<option value="' + val.id + '">' + val.label + '</option>');
  458. }
  459. });
  460. };
  461. jQuery(document).ready(function() {
  462. jQuery("select#attribute").change(function () {
  463. console.log("Change of field variant attribute");
  464. var select = jQuery("select#value");
  465. if (!jQuery(this).val().length || jQuery(this).val() == '-1') {
  466. select.empty();
  467. select.append('<option value="-1">&nbsp;</option>');
  468. return;
  469. }
  470. select.empty().append('<option value="">Loading...</option>');
  471. jQuery.getJSON("ajax/get_attribute_values.php", {
  472. id: jQuery(this).val()
  473. }, function(data) {
  474. if (data.error) {
  475. select.empty();
  476. select.append('<option value="-1">&nbsp;</option>');
  477. return alert(data.error);
  478. }
  479. select.empty();
  480. select.append('<option value="-1">&nbsp;</option>');
  481. jQuery(data).each(function (key, val) {
  482. keyforoption = val.id
  483. valforoption = val.value
  484. select.append('<option value="' + keyforoption + '">' + valforoption + '</option>');
  485. });
  486. });
  487. });
  488. });
  489. </script>
  490. <?php
  491. }
  492. print '<br>';
  493. print load_fiche_titre($title);
  494. print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">'."\n";
  495. print '<input type="hidden" name="token" value="'.newToken().'">';
  496. print '<input type="hidden" name="action" value="'.(($valueid > 0) ? "update" : "create").'">'."\n";
  497. if ($valueid > 0) {
  498. print '<input type="hidden" name="valueid" value="'.$valueid.'">'."\n";
  499. }
  500. print dol_get_fiche_head();
  501. if ($action == 'add') {
  502. print '<table class="border" style="width: 100%">';
  503. print "<!-- Variant -->\n";
  504. print '<tr>';
  505. print '<td class="titlefieldcreate fieldrequired"><label for="attribute">'.$langs->trans('ProductAttribute').'</label></td>';
  506. print '<td>';
  507. if (is_array($prodattr_all)) {
  508. print '<select class="flat minwidth100" id="attribute" name="attribute">';
  509. print '<option value="-1">&nbsp;</option>';
  510. foreach ($prodattr_all as $attr) {
  511. //print '<option value="'.$attr->id.'"'.($attr->id == GETPOST('attribute', 'int') ? ' selected="selected"' : '').'>'.$attr->label.'</option>';
  512. print '<option value="'.$attr->id.'">'.$attr->label.'</option>';
  513. }
  514. print '</select>';
  515. }
  516. $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
  517. print $form->textwithpicto('', $htmltext);
  518. /*print ' &nbsp; &nbsp; <a href="'.DOL_URL_ROOT.'/variants/create.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=add&token='.newToken().'&id='.$object->id).'">';
  519. print $langs->trans("Create");
  520. print '</a>';*/
  521. print '</td>';
  522. print '</tr>';
  523. ?>
  524. <!-- Value -->
  525. <tr>
  526. <td class="fieldrequired"><label for="value"><?php echo $langs->trans('Value') ?></label></td>
  527. <td>
  528. <select class="flat minwidth100" id="value" name="value">
  529. <option value="-1">&nbsp;</option>
  530. </select>
  531. <?php
  532. $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
  533. print $form->textwithpicto('', $htmltext);
  534. /*
  535. print ' &nbsp; &nbsp; <a href="'.DOL_URL_ROOT.'/variants/create.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=add&token='.newToken().'&id='.$object->id).'">';
  536. print $langs->trans("Create");
  537. print '</a>';
  538. */
  539. ?>
  540. </td>
  541. </tr>
  542. <tr>
  543. <td></td><td>
  544. <input type="submit" class="button" name="selectvariant" id="selectvariant" value="<?php echo dol_escape_htmltag($langs->trans("SelectCombination")); ?>">
  545. </td>
  546. </tr>
  547. <?php
  548. print '<tr><td></td><td>';
  549. print $listofvariantselected;
  550. print '</td>';
  551. print '</tr>';
  552. print '</table>';
  553. print '<hr>';
  554. }
  555. if (is_array($productCombination2ValuePairs1)) {
  556. print '<table class="border" style="width: 100%">';
  557. // When in edit mode
  558. if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) {
  559. ?>
  560. <tr>
  561. <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Combination') ?></label></td>
  562. <td class="tdtop">
  563. <div class="inline-block valignmiddle quatrevingtpercent">
  564. <?php
  565. foreach ($productCombination2ValuePairs1 as $key => $val) {
  566. $result1 = $prodattr->fetch($val->fk_prod_attr);
  567. $result2 = $prodattr_val->fetch($val->fk_prod_attr_val);
  568. //print 'rr'.$result1.' '.$result2;
  569. if ($result1 > 0 && $result2 > 0) {
  570. print $prodattr->label.' - '.$prodattr_val->value.'<br>';
  571. // TODO Add delete link
  572. }
  573. }
  574. ?>
  575. </div>
  576. <!-- <div class="inline-block valignmiddle">
  577. <a href="#" class="inline-block valignmiddle button" id="delfeature"><?php echo img_edit_remove() ?></a>
  578. </div>-->
  579. </td>
  580. <td>
  581. </td>
  582. </tr>
  583. <?php
  584. }
  585. ?>
  586. <tr>
  587. <td><label for="reference"><?php echo $langs->trans('Reference') ?></label></td>
  588. <td><input type="text" id="reference" name="reference" value="<?php echo trim($reference) ?>"></td>
  589. </tr>
  590. <?php
  591. if (empty($conf->global->PRODUIT_MULTIPRICES)) {
  592. ?>
  593. <tr>
  594. <td><label for="price_impact"><?php echo $langs->trans('PriceImpact') ?></label></td>
  595. <td><input type="text" id="price_impact" name="price_impact" value="<?php echo price($price_impact) ?>">
  596. <input type="checkbox" id="price_impact_percent" name="price_impact_percent" <?php echo $price_impact_percent ? ' checked' : '' ?>> <label for="price_impact_percent"><?php echo $langs->trans('PercentageVariation') ?></label>
  597. </td>
  598. </tr>
  599. <?php
  600. } else {
  601. $prodcomb->fetchCombinationPriceLevels();
  602. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  603. print '<tr>';
  604. print '<td><label for="level_price_impact_'.$i.'">'.$langs->trans('ImpactOnPriceLevel', $i).'</label>';
  605. if ($i === 1) {
  606. print ' <a id="apply-price-impact-to-all-level" class="classfortooltip" href="#" title="'.$langs->trans('ApplyToAllPriceImpactLevelHelp').'">('.$langs->trans('ApplyToAllPriceImpactLevel').')</a>';
  607. }
  608. print '</td>';
  609. print '<td><input type="text" class="level_price_impact" id="level_price_impact_'.$i.'" name="level_price_impact['.$i.']" value="'.price($prodcomb->combination_price_levels[$i]->variation_price).'">';
  610. print '<input type="checkbox" class="level_price_impact_percent" id="level_price_impact_percent_'.$i.'" name="level_price_impact_percent['.$i.']" '.(!empty($prodcomb->combination_price_levels[$i]->variation_price_percentage) ? ' checked' : '').'> <label for="level_price_impact_percent_'.$i.'">'.$langs->trans('PercentageVariation').'</label>';
  611. print '</td>';
  612. print '</tr>';
  613. }
  614. }
  615. if ($object->isProduct()) {
  616. print '<tr>';
  617. print '<td><label for="weight_impact">'.$langs->trans('WeightImpact').'</label></td>';
  618. print '<td><input type="text" id="weight_impact" name="weight_impact" value="'.price($weight_impact).'"></td>';
  619. print '</tr>';
  620. }
  621. print '</table>';
  622. }
  623. if (!empty($conf->global->PRODUIT_MULTIPRICES)) {
  624. ?>
  625. <script>
  626. $(document).ready(function() {
  627. // Apply level 1 impact to all prices impact levels
  628. $('body').on('click', '#apply-price-impact-to-all-level', function(e) {
  629. e.preventDefault();
  630. let priceImpact = $( "#level_price_impact_1" ).val();
  631. let priceImpactPrecent = $( "#level_price_impact_percent_1" ).prop("checked");
  632. var multipricelimit = <?php print intval($conf->global->PRODUIT_MULTIPRICES_LIMIT); ?>
  633. for (let i = 2; i <= multipricelimit; i++) {
  634. $( "#level_price_impact_" + i ).val(priceImpact);
  635. $( "#level_price_impact_percent_" + i ).prop("checked", priceImpactPrecent);
  636. }
  637. });
  638. });
  639. </script>
  640. <?php
  641. }
  642. print dol_get_fiche_end();
  643. ?>
  644. <div style="text-align: center">
  645. <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) {
  646. print ' disabled="disabled"';
  647. } ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save">
  648. &nbsp;
  649. <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel">
  650. </div>
  651. <?php
  652. print '</form>';
  653. } else {
  654. if ($action === 'delete') {
  655. if ($prodcomb->fetch($valueid) > 0) {
  656. $prodstatic->fetch($prodcomb->fk_product_child);
  657. print $form->formconfirm(
  658. "combinations.php?id=".urlencode($id)."&valueid=".urlencode($valueid),
  659. $langs->trans('Delete'),
  660. $langs->trans('ProductCombinationDeleteDialog', $prodstatic->ref),
  661. "confirm_deletecombination",
  662. array(array('label'=> $langs->trans('DeleteLinkedProduct'), 'type'=> 'checkbox', 'name' => 'delete_product', 'value' => false)),
  663. 0,
  664. 1
  665. );
  666. }
  667. } elseif ($action === 'copy') {
  668. print $form->formconfirm('combinations.php?id='.$id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneProductCombinations'), 'confirm_copycombination', array(array('type' => 'text', 'label' => $langs->trans('CloneDestinationReference'), 'name' => 'dest_product')), 0, 1);
  669. }
  670. $comb2val = new ProductCombination2ValuePair($db);
  671. if ($productCombinations) {
  672. ?>
  673. <script type="text/javascript">
  674. jQuery(document).ready(function() {
  675. jQuery('input[name="select_all"]').click(function() {
  676. if (jQuery(this).prop('checked')) {
  677. var checked = true;
  678. } else {
  679. var checked = false;
  680. }
  681. jQuery('table.liste input[type="checkbox"]').prop('checked', checked);
  682. });
  683. jQuery('input[name^="select["]').click(function() {
  684. jQuery('input[name="select_all"]').prop('checked', false);
  685. });
  686. });
  687. </script>
  688. <?php
  689. }
  690. // Buttons
  691. print '<div class="tabsAction">';
  692. print ' <div class="inline-block divButAction">';
  693. print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant
  694. if ($productCombinations) {
  695. print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>';
  696. }
  697. print ' </div>';
  698. print '</div>';
  699. $arrayofselected = is_array($toselect) ? $toselect : array();
  700. // List of variants
  701. print '<form method="POST" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">';
  702. print '<input type="hidden" name="token" value="'.newToken().'">';
  703. print '<input type="hidden" name="action" value="massaction">';
  704. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  705. // List of mass actions available
  706. /*
  707. $arrayofmassactions = array(
  708. 'presend'=>$langs->trans("SendByMail"),
  709. 'builddoc'=>$langs->trans("PDFMerge"),
  710. );
  711. if ($user->rights->product->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
  712. if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
  713. $massactionbutton=$form->selectMassAction('', $arrayofmassactions);
  714. */
  715. $aaa = '';
  716. if (count($productCombinations)) {
  717. $aaa = '<label for="massaction">'.$langs->trans('BulkActions').'</label>';
  718. $aaa .= '<select id="bulk_action" name="massaction" class="flat">';
  719. $aaa .= ' <option value="nothing">&nbsp;</option>';
  720. $aaa .= ' <option value="not_buy">'.$langs->trans('ProductStatusNotOnBuy').'</option>';
  721. $aaa .= ' <option value="not_sell">'.$langs->trans('ProductStatusNotOnSell').'</option>';
  722. $aaa .= ' <option value="on_buy">'.$langs->trans('ProductStatusOnBuy').'</option>';
  723. $aaa .= ' <option value="on_sell">'.$langs->trans('ProductStatusOnSell').'</option>';
  724. $aaa .= ' <option value="delete">'.$langs->trans('Delete').'</option>';
  725. $aaa .= '</select>';
  726. $aaa .= '<input type="submit" value="'.dol_escape_htmltag($langs->trans("Apply")).'" class="button small">';
  727. }
  728. $massactionbutton = $aaa;
  729. $title = $langs->trans("ProductCombinations");
  730. print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $aaa, 0);
  731. print '<div class="div-table-responsive">';
  732. ?>
  733. <table class="liste">
  734. <tr class="liste_titre">
  735. <td class="liste_titre"><?php echo $langs->trans('Product') ?></td>
  736. <td class="liste_titre"><?php echo $langs->trans('Combination') ?></td>
  737. <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td>
  738. <?php if ($object->isProduct()) {
  739. print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>';
  740. } ?>
  741. <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td>
  742. <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td>
  743. <td class="liste_titre"></td>
  744. <?php
  745. print '<td class="liste_titre center">';
  746. $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
  747. print $searchpicto;
  748. print '</td>';
  749. ?>
  750. </tr>
  751. <?php
  752. if (count($productCombinations)) {
  753. foreach ($productCombinations as $currcomb) {
  754. $prodstatic->fetch($currcomb->fk_product_child);
  755. print '<tr class="oddeven">';
  756. print '<td>'.$prodstatic->getNomUrl(1).'</td>';
  757. print '<td>';
  758. $productCombination2ValuePairs = $comb2val->fetchByFkCombination($currcomb->id);
  759. $iMax = count($productCombination2ValuePairs);
  760. for ($i = 0; $i < $iMax; $i++) {
  761. echo dol_htmlentities($productCombination2ValuePairs[$i]);
  762. if ($i !== ($iMax - 1)) {
  763. echo ', ';
  764. }
  765. }
  766. print '</td>';
  767. print '<td class="right">'.($currcomb->variation_price >= 0 ? '+' : '').price($currcomb->variation_price).($currcomb->variation_price_percentage ? ' %' : '').'</td>';
  768. if ($object->isProduct()) {
  769. print '<td class="right">'.($currcomb->variation_weight >= 0 ? '+' : '').price($currcomb->variation_weight).' '.measuringUnitString(0, 'weight', $prodstatic->weight_units).'</td>';
  770. }
  771. print '<td class="center">'.$prodstatic->getLibStatut(2, 0).'</td>';
  772. print '<td class="center">'.$prodstatic->getLibStatut(2, 1).'</td>';
  773. print '<td class="right">';
  774. print '<a class="paddingleft paddingright editfielda" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=edit&token='.newToken().'&valueid='.$currcomb->id.'">'.img_edit().'</a>';
  775. print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&valueid='.$currcomb->id.'">'.img_delete().'</a>';
  776. print '</td>';
  777. print '<td class="nowrap center">';
  778. if ($productCombinations || $massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
  779. $selected = 0;
  780. if (in_array($prodstatic->id, $arrayofselected)) {
  781. $selected = 1;
  782. }
  783. print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
  784. }
  785. print '</td>';
  786. print '</tr>';
  787. }
  788. } else {
  789. print '<tr><td colspan="8"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  790. }
  791. print '</table>';
  792. print '</div>';
  793. print '</form>';
  794. }
  795. } else {
  796. llxHeader();
  797. // not found
  798. }
  799. // End of page
  800. llxFooter();
  801. $db->close();