combinations.php 34 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. // 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->rights->service->lire));
  84. $usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->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. if ($prodcomb->update($user) > 0) {
  270. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  271. header('Location: '.dol_buildpath('/variants/combinations.php?id='.$id, 2));
  272. exit();
  273. } else {
  274. setEventMessages($prodcomb->error, $prodcomb->errors, 'errors');
  275. }
  276. }
  277. // Reload variants
  278. $productCombinations = $prodcomb->fetchAllByFkProductParent($object->id);
  279. if ($action === 'confirm_deletecombination') {
  280. if ($prodcomb->fetch($valueid) > 0) {
  281. $db->begin();
  282. if ($prodcomb->delete($user) > 0 && (empty($delete_product) || ($delete_product == 'on' && $prodstatic->fetch($prodcomb->fk_product_child) > 0 && $prodstatic->delete($user) > 0))) {
  283. $db->commit();
  284. setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
  285. header('Location: '.dol_buildpath('/variants/combinations.php?id='.$object->id, 2));
  286. exit();
  287. }
  288. $db->rollback();
  289. setEventMessages($langs->trans('ProductCombinationAlreadyUsed'), null, 'errors');
  290. $action = '';
  291. }
  292. } elseif ($action === 'edit') {
  293. if ($prodcomb->fetch($valueid) < 0) {
  294. dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
  295. exit();
  296. }
  297. $weight_impact = $prodcomb->variation_weight;
  298. $price_impact = $prodcomb->variation_price;
  299. $price_impact_percent = $prodcomb->variation_price_percentage;
  300. $productCombination2ValuePairs1 = $prodcomb2val->fetchByFkCombination($valueid);
  301. } elseif ($action === 'confirm_copycombination') {
  302. //Check destination product
  303. $dest_product = GETPOST('dest_product');
  304. if ($prodstatic->fetch('', $dest_product) > 0) {
  305. //To prevent from copying to the same product
  306. if ($prodstatic->ref != $object->ref) {
  307. if ($prodcomb->copyAll($user, $object->id, $prodstatic) > 0) {
  308. header('Location: '.dol_buildpath('/variants/combinations.php?id='.$prodstatic->id, 2));
  309. exit();
  310. } else {
  311. setEventMessages($langs->trans('ErrorCopyProductCombinations'), null, 'errors');
  312. }
  313. }
  314. } else {
  315. setEventMessages($langs->trans('ErrorDestinationProductNotFound'), null, 'errors');
  316. }
  317. }
  318. /*
  319. * View
  320. */
  321. $form = new Form($db);
  322. $title = $langs->trans("Variant");
  323. llxHeader("", $title);
  324. if (!empty($id) || !empty($ref)) {
  325. $showbarcode = empty($conf->barcode->enabled) ? 0 : 1;
  326. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  327. $showbarcode = 0;
  328. }
  329. $head = product_prepare_head($object);
  330. $titre = $langs->trans("CardProduct".$object->type);
  331. $picto = ($object->type == Product::TYPE_SERVICE ? 'service' : 'product');
  332. print dol_get_fiche_head($head, 'combinations', $titre, -1, $picto);
  333. $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?type='.$object->type.'">'.$langs->trans("BackToList").'</a>';
  334. $object->next_prev_filter = " fk_product_type = ".$object->type;
  335. dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref', '', '', '', 0, '', '');
  336. print '<div class="fichecenter">';
  337. print '<div class="underbanner clearboth"></div>';
  338. print '<table class="border centpercent tableforfield">';
  339. // Type
  340. if (isModEnabled("product") && isModEnabled("service")) {
  341. $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service");
  342. print '<tr><td class="titlefieldcreate">';
  343. print (empty($conf->global->PRODUCT_DENY_CHANGE_PRODUCT_TYPE)) ? $form->editfieldkey("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat) : $langs->trans('Type');
  344. print '</td><td>';
  345. print $form->editfieldval("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat);
  346. print '</td></tr>';
  347. }
  348. // TVA
  349. print '<tr><td class="titlefieldcreate">'.$langs->trans("DefaultTaxRate").'</td><td>';
  350. $positiverates = '';
  351. if (price2num($object->tva_tx)) {
  352. $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx);
  353. }
  354. if (price2num($object->localtax1_type)) {
  355. $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx);
  356. }
  357. if (price2num($object->localtax2_type)) {
  358. $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx);
  359. }
  360. if (empty($positiverates)) {
  361. $positiverates = '0';
  362. }
  363. echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr);
  364. /*
  365. if ($object->default_vat_code)
  366. {
  367. print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
  368. }
  369. else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/
  370. print '</td></tr>';
  371. // Price
  372. print '<tr><td>'.$langs->trans("SellingPrice").'</td><td>';
  373. if ($object->price_base_type == 'TTC') {
  374. print price($object->price_ttc).' '.$langs->trans($object->price_base_type);
  375. } else {
  376. print price($object->price).' '.$langs->trans($object->price_base_type);
  377. }
  378. print '</td></tr>';
  379. // Price minimum
  380. print '<tr><td>'.$langs->trans("MinPrice").'</td><td>';
  381. if ($object->price_base_type == 'TTC') {
  382. print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type);
  383. } else {
  384. print price($object->price_min).' '.$langs->trans($object->price_base_type);
  385. }
  386. print '</td></tr>';
  387. // Weight
  388. print '<tr><td>'.$langs->trans("Weight").'</td><td>';
  389. if ($object->weight != '') {
  390. print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units);
  391. } else {
  392. print '&nbsp;';
  393. }
  394. print "</td></tr>\n";
  395. print "</table>\n";
  396. print '</div>';
  397. print '<div style="clear:both"></div>';
  398. print dol_get_fiche_end();
  399. $listofvariantselected = '';
  400. // Create or edit a varian
  401. if ($action == 'add' || ($action == 'edit')) {
  402. if ($action == 'add') {
  403. $title = $langs->trans('NewProductCombination');
  404. // print dol_get_fiche_head();
  405. $features = !empty($_SESSION['addvariant_'.$object->id]) ? $_SESSION['addvariant_'.$object->id] : array();
  406. //First, sanitize
  407. $listofvariantselected = '<div id="parttoaddvariant">';
  408. if (!empty($features)) {
  409. $toprint = array();
  410. foreach ($features as $feature) {
  411. $explode = explode('-', $feature);
  412. if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) {
  413. continue;
  414. }
  415. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #ddd;">' . $prodattr->label.' : '.$prodattr_val->value .
  416. ' <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=create&subaction=delete&feature='.urlencode($feature).'">' . img_delete() . '</a></li>';
  417. }
  418. $listofvariantselected .= '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  419. }
  420. $listofvariantselected .= '</div>';
  421. //print dol_get_fiche_end();
  422. } else {
  423. $title = $langs->trans('EditProductCombination');
  424. }
  425. if ($action == 'add') {
  426. $prodattr_all = $prodattr->fetchAll();
  427. if (!$selected) {
  428. $selected = $prodattr_all[key($prodattr_all)]->id;
  429. }
  430. $prodattr_alljson = array();
  431. foreach ($prodattr_all as $each) {
  432. $prodattr_alljson[$each->id] = $each;
  433. }
  434. ?>
  435. <script type="text/javascript">
  436. variants_available = <?php echo json_encode($prodattr_alljson); ?>;
  437. variants_selected = {
  438. index: [],
  439. info: []
  440. };
  441. <?php
  442. foreach ($productCombination2ValuePairs1 as $pc2v) {
  443. $prodattr_val->fetch($pc2v->fk_prod_attr_val);
  444. ?>
  445. variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>);
  446. variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = {
  447. attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>],
  448. value: {
  449. id: <?php echo $pc2v->fk_prod_attr_val ?>,
  450. label: '<?php echo $prodattr_val->value ?>'
  451. }
  452. };
  453. <?php
  454. }
  455. ?>
  456. restoreAttributes = function() {
  457. jQuery("select[name=attribute]").empty().append('<option value="-1">&nbsp;</option>');
  458. jQuery.each(variants_available, function (key, val) {
  459. if (jQuery.inArray(val.id, variants_selected.index) == -1) {
  460. jQuery("select[name=attribute]").append('<option value="' + val.id + '">' + val.label + '</option>');
  461. }
  462. });
  463. };
  464. jQuery(document).ready(function() {
  465. jQuery("select#attribute").change(function () {
  466. console.log("Change of field variant attribute");
  467. var select = jQuery("select#value");
  468. if (!jQuery(this).val().length || jQuery(this).val() == '-1') {
  469. select.empty();
  470. select.append('<option value="-1">&nbsp;</option>');
  471. return;
  472. }
  473. select.empty().append('<option value="">Loading...</option>');
  474. jQuery.getJSON("ajax/get_attribute_values.php", {
  475. id: jQuery(this).val()
  476. }, function(data) {
  477. if (data.error) {
  478. select.empty();
  479. select.append('<option value="-1">&nbsp;</option>');
  480. return alert(data.error);
  481. }
  482. select.empty();
  483. select.append('<option value="-1">&nbsp;</option>');
  484. jQuery(data).each(function (key, val) {
  485. keyforoption = val.id
  486. valforoption = val.value
  487. select.append('<option value="' + keyforoption + '">' + valforoption + '</option>');
  488. });
  489. });
  490. });
  491. });
  492. </script>
  493. <?php
  494. }
  495. print '<br>';
  496. print load_fiche_titre($title);
  497. print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">'."\n";
  498. print '<input type="hidden" name="token" value="'.newToken().'">';
  499. print '<input type="hidden" name="action" value="'.(($valueid > 0) ? "update" : "create").'">'."\n";
  500. if ($valueid > 0) {
  501. print '<input type="hidden" name="valueid" value="'.$valueid.'">'."\n";
  502. }
  503. print dol_get_fiche_head();
  504. if ($action == 'add') {
  505. print '<table class="border" style="width: 100%">';
  506. print "<!-- Variant -->\n";
  507. print '<tr>';
  508. print '<td class="titlefieldcreate fieldrequired"><label for="attribute">'.$langs->trans('ProductAttribute').'</label></td>';
  509. print '<td>';
  510. if (is_array($prodattr_all)) {
  511. print '<select class="flat minwidth100" id="attribute" name="attribute">';
  512. print '<option value="-1">&nbsp;</option>';
  513. foreach ($prodattr_all as $attr) {
  514. //print '<option value="'.$attr->id.'"'.($attr->id == GETPOST('attribute', 'int') ? ' selected="selected"' : '').'>'.$attr->label.'</option>';
  515. print '<option value="'.$attr->id.'">'.$attr->label.'</option>';
  516. }
  517. print '</select>';
  518. }
  519. $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
  520. print $form->textwithpicto('', $htmltext);
  521. /*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).'">';
  522. print $langs->trans("Create");
  523. print '</a>';*/
  524. print '</td>';
  525. print '</tr>';
  526. ?>
  527. <!-- Value -->
  528. <tr>
  529. <td class="fieldrequired"><label for="value"><?php echo $langs->trans('Value') ?></label></td>
  530. <td>
  531. <select class="flat minwidth100" id="value" name="value">
  532. <option value="-1">&nbsp;</option>
  533. </select>
  534. <?php
  535. $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
  536. print $form->textwithpicto('', $htmltext);
  537. /*
  538. 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).'">';
  539. print $langs->trans("Create");
  540. print '</a>';
  541. */
  542. ?>
  543. </td>
  544. </tr>
  545. <tr>
  546. <td></td><td>
  547. <input type="submit" class="button" name="selectvariant" id="selectvariant" value="<?php echo dol_escape_htmltag($langs->trans("SelectCombination")); ?>">
  548. </td>
  549. </tr>
  550. <?php
  551. print '<tr><td></td><td>';
  552. print $listofvariantselected;
  553. print '</td>';
  554. print '</tr>';
  555. print '</table>';
  556. print '<hr>';
  557. }
  558. if (is_array($productCombination2ValuePairs1)) {
  559. print '<table class="border" style="width: 100%">';
  560. // When in edit mode
  561. if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) {
  562. ?>
  563. <tr>
  564. <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Combination') ?></label></td>
  565. <td class="tdtop">
  566. <div class="inline-block valignmiddle quatrevingtpercent">
  567. <?php
  568. foreach ($productCombination2ValuePairs1 as $key => $val) {
  569. $result1 = $prodattr->fetch($val->fk_prod_attr);
  570. $result2 = $prodattr_val->fetch($val->fk_prod_attr_val);
  571. //print 'rr'.$result1.' '.$result2;
  572. if ($result1 > 0 && $result2 > 0) {
  573. print $prodattr->label.' - '.$prodattr_val->value.'<br>';
  574. // TODO Add delete link
  575. }
  576. }
  577. ?>
  578. </div>
  579. <!-- <div class="inline-block valignmiddle">
  580. <a href="#" class="inline-block valignmiddle button" id="delfeature"><?php echo img_edit_remove() ?></a>
  581. </div>-->
  582. </td>
  583. <td>
  584. </td>
  585. </tr>
  586. <?php
  587. }
  588. ?>
  589. <tr>
  590. <td><label for="reference"><?php echo $langs->trans('Reference') ?></label></td>
  591. <td><input type="text" id="reference" name="reference" value="<?php echo trim($reference) ?>"></td>
  592. </tr>
  593. <?php
  594. if (empty($conf->global->PRODUIT_MULTIPRICES)) {
  595. ?>
  596. <tr>
  597. <td><label for="price_impact"><?php echo $langs->trans('PriceImpact') ?></label></td>
  598. <td><input type="text" id="price_impact" name="price_impact" value="<?php echo price($price_impact) ?>">
  599. <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>
  600. </td>
  601. </tr>
  602. <?php
  603. } else {
  604. $prodcomb->fetchCombinationPriceLevels();
  605. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  606. print '<tr>';
  607. print '<td><label for="level_price_impact_'.$i.'">'.$langs->trans('ImpactOnPriceLevel', $i).'</label>';
  608. if ($i === 1) {
  609. print ' <a id="apply-price-impact-to-all-level" class="classfortooltip" href="#" title="'.$langs->trans('ApplyToAllPriceImpactLevelHelp').'">('.$langs->trans('ApplyToAllPriceImpactLevel').')</a>';
  610. }
  611. print '</td>';
  612. 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).'">';
  613. 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>';
  614. print '</td>';
  615. print '</tr>';
  616. }
  617. }
  618. if ($object->isProduct()) {
  619. print '<tr>';
  620. print '<td><label for="weight_impact">'.$langs->trans('WeightImpact').'</label></td>';
  621. print '<td><input type="text" id="weight_impact" name="weight_impact" value="'.price($weight_impact).'"></td>';
  622. print '</tr>';
  623. }
  624. print '</table>';
  625. }
  626. if (!empty($conf->global->PRODUIT_MULTIPRICES)) {
  627. ?>
  628. <script>
  629. $(document).ready(function() {
  630. // Apply level 1 impact to all prices impact levels
  631. $('body').on('click', '#apply-price-impact-to-all-level', function(e) {
  632. e.preventDefault();
  633. let priceImpact = $( "#level_price_impact_1" ).val();
  634. let priceImpactPrecent = $( "#level_price_impact_percent_1" ).prop("checked");
  635. var multipricelimit = <?php print intval($conf->global->PRODUIT_MULTIPRICES_LIMIT); ?>
  636. for (let i = 2; i <= multipricelimit; i++) {
  637. $( "#level_price_impact_" + i ).val(priceImpact);
  638. $( "#level_price_impact_percent_" + i ).prop("checked", priceImpactPrecent);
  639. }
  640. });
  641. });
  642. </script>
  643. <?php
  644. }
  645. print dol_get_fiche_end();
  646. ?>
  647. <div style="text-align: center">
  648. <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) {
  649. print ' disabled="disabled"';
  650. } ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save">
  651. &nbsp;
  652. <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel">
  653. </div>
  654. <?php
  655. print '</form>';
  656. } else {
  657. if ($action === 'delete') {
  658. if ($prodcomb->fetch($valueid) > 0) {
  659. $prodstatic->fetch($prodcomb->fk_product_child);
  660. print $form->formconfirm(
  661. "combinations.php?id=".urlencode($id)."&valueid=".urlencode($valueid),
  662. $langs->trans('Delete'),
  663. $langs->trans('ProductCombinationDeleteDialog', $prodstatic->ref),
  664. "confirm_deletecombination",
  665. array(array('label'=> $langs->trans('DeleteLinkedProduct'), 'type'=> 'checkbox', 'name' => 'delete_product', 'value' => false)),
  666. 0,
  667. 1
  668. );
  669. }
  670. } elseif ($action === 'copy') {
  671. 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);
  672. }
  673. $comb2val = new ProductCombination2ValuePair($db);
  674. if ($productCombinations) {
  675. ?>
  676. <script type="text/javascript">
  677. jQuery(document).ready(function() {
  678. jQuery('input[name="select_all"]').click(function() {
  679. if (jQuery(this).prop('checked')) {
  680. var checked = true;
  681. } else {
  682. var checked = false;
  683. }
  684. jQuery('table.liste input[type="checkbox"]').prop('checked', checked);
  685. });
  686. jQuery('input[name^="select["]').click(function() {
  687. jQuery('input[name="select_all"]').prop('checked', false);
  688. });
  689. });
  690. </script>
  691. <?php
  692. }
  693. // Buttons
  694. print '<div class="tabsAction">';
  695. print ' <div class="inline-block divButAction">';
  696. print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant
  697. if ($productCombinations) {
  698. print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>';
  699. }
  700. print ' </div>';
  701. print '</div>';
  702. $arrayofselected = is_array($toselect) ? $toselect : array();
  703. // List of variants
  704. print '<form method="POST" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">';
  705. print '<input type="hidden" name="token" value="'.newToken().'">';
  706. print '<input type="hidden" name="action" value="massaction">';
  707. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  708. // List of mass actions available
  709. /*
  710. $arrayofmassactions = array(
  711. 'presend'=>$langs->trans("SendByMail"),
  712. 'builddoc'=>$langs->trans("PDFMerge"),
  713. );
  714. if ($user->rights->product->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
  715. if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
  716. $massactionbutton=$form->selectMassAction('', $arrayofmassactions);
  717. */
  718. $aaa = '';
  719. if (count($productCombinations)) {
  720. $aaa = '<select id="bulk_action" name="massaction" class="flat">';
  721. $aaa .= ' <option value="nothing">&nbsp;</option>';
  722. $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>';
  723. $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>';
  724. $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>';
  725. $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>';
  726. $aaa .= ' <option value="delete" data-html="'.dol_escape_htmltag(img_picto($langs->trans("Delete"), 'delete', 'class="pictofixedwidth"').$langs->trans('Delete')).'">'.$langs->trans('Delete').'</option>';
  727. $aaa .= '</select>';
  728. $aaa .= ajax_combobox("bulk_action");
  729. $aaa .= '<input type="submit" value="'.dol_escape_htmltag($langs->trans("Apply")).'" class="button small">';
  730. }
  731. $massactionbutton = $aaa;
  732. $title = $langs->trans("ProductCombinations");
  733. print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $aaa, 0);
  734. print '<div class="div-table-responsive">';
  735. ?>
  736. <table class="liste">
  737. <tr class="liste_titre">
  738. <td class="liste_titre"><?php echo $langs->trans('Product') ?></td>
  739. <td class="liste_titre"><?php echo $langs->trans('Combination') ?></td>
  740. <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td>
  741. <?php if ($object->isProduct()) {
  742. print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>';
  743. } ?>
  744. <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td>
  745. <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td>
  746. <td class="liste_titre"></td>
  747. <?php
  748. print '<td class="liste_titre center">';
  749. $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
  750. print $searchpicto;
  751. print '</td>';
  752. ?>
  753. </tr>
  754. <?php
  755. if (count($productCombinations)) {
  756. foreach ($productCombinations as $currcomb) {
  757. $prodstatic->fetch($currcomb->fk_product_child);
  758. print '<tr class="oddeven">';
  759. print '<td>'.$prodstatic->getNomUrl(1).'</td>';
  760. print '<td>';
  761. $productCombination2ValuePairs = $comb2val->fetchByFkCombination($currcomb->id);
  762. $iMax = count($productCombination2ValuePairs);
  763. for ($i = 0; $i < $iMax; $i++) {
  764. echo dol_htmlentities($productCombination2ValuePairs[$i]);
  765. if ($i !== ($iMax - 1)) {
  766. echo ', ';
  767. }
  768. }
  769. print '</td>';
  770. print '<td class="right">'.($currcomb->variation_price >= 0 ? '+' : '').price($currcomb->variation_price).($currcomb->variation_price_percentage ? ' %' : '').'</td>';
  771. if ($object->isProduct()) {
  772. print '<td class="right">'.($currcomb->variation_weight >= 0 ? '+' : '').price($currcomb->variation_weight).' '.measuringUnitString(0, 'weight', $prodstatic->weight_units).'</td>';
  773. }
  774. print '<td class="center">'.$prodstatic->getLibStatut(2, 0).'</td>';
  775. print '<td class="center">'.$prodstatic->getLibStatut(2, 1).'</td>';
  776. print '<td class="right">';
  777. print '<a class="paddingleft paddingright editfielda" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=edit&token='.newToken().'&valueid='.$currcomb->id.'">'.img_edit().'</a>';
  778. print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&valueid='.$currcomb->id.'">'.img_delete().'</a>';
  779. print '</td>';
  780. print '<td class="nowrap center">';
  781. 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
  782. $selected = 0;
  783. if (in_array($prodstatic->id, $arrayofselected)) {
  784. $selected = 1;
  785. }
  786. print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
  787. }
  788. print '</td>';
  789. print '</tr>';
  790. }
  791. } else {
  792. print '<tr><td colspan="8"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  793. }
  794. print '</table>';
  795. print '</div>';
  796. print '</form>';
  797. }
  798. }
  799. // End of page
  800. llxFooter();
  801. $db->close();