combinations.php 36 KB

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