combinations.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (!getDolGlobalString('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. <script type="text/javascript">
  459. variants_available = <?php echo json_encode($prodattr_alljson, JSON_PARTIAL_OUTPUT_ON_ERROR); ?>;
  460. variants_selected = {
  461. index: [],
  462. info: []
  463. };
  464. <?php
  465. foreach ($productCombination2ValuePairs1 as $pc2v) {
  466. $prodattr_val->fetch($pc2v->fk_prod_attr_val); ?>
  467. variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>);
  468. variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = {
  469. attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>],
  470. value: {
  471. id: <?php echo $pc2v->fk_prod_attr_val ?>,
  472. label: '<?php echo $prodattr_val->value ?>'
  473. }
  474. };
  475. <?php
  476. } ?>
  477. restoreAttributes = function() {
  478. jQuery("select[name=attribute]").empty().append('<option value="-1">&nbsp;</option>');
  479. jQuery.each(variants_available, function (key, val) {
  480. if (jQuery.inArray(val.id, variants_selected.index) == -1) {
  481. jQuery("select[name=attribute]").append('<option value="' + val.id + '">' + val.label + '</option>');
  482. }
  483. });
  484. };
  485. jQuery(document).ready(function() {
  486. jQuery("select#attribute").change(function () {
  487. console.log("Change of field variant attribute");
  488. var select = jQuery("select#value");
  489. if (!jQuery(this).val().length || jQuery(this).val() == '-1') {
  490. select.empty();
  491. select.append('<option value="-1">&nbsp;</option>');
  492. return;
  493. }
  494. select.empty().append('<option value="">Loading...</option>');
  495. jQuery.getJSON("ajax/get_attribute_values.php", {
  496. id: jQuery(this).val()
  497. }, function(data) {
  498. if (data.error) {
  499. select.empty();
  500. select.append('<option value="-1">&nbsp;</option>');
  501. return alert(data.error);
  502. }
  503. select.empty();
  504. select.append('<option value="-1">&nbsp;</option>');
  505. jQuery(data).each(function (key, val) {
  506. keyforoption = val.id
  507. valforoption = val.value
  508. select.append('<option value="' + keyforoption + '">' + valforoption + '</option>');
  509. });
  510. });
  511. });
  512. });
  513. </script>
  514. <?php
  515. }
  516. print '<br>';
  517. print load_fiche_titre($title);
  518. print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">'."\n";
  519. print '<input type="hidden" name="token" value="'.newToken().'">';
  520. print '<input type="hidden" name="action" value="'.(($valueid > 0) ? "update" : "create").'">'."\n";
  521. if ($valueid > 0) {
  522. print '<input type="hidden" name="valueid" value="'.$valueid.'">'."\n";
  523. }
  524. print dol_get_fiche_head();
  525. if ($action == 'add') {
  526. print '<table class="border" style="width: 100%">';
  527. print "<!-- Variant -->\n";
  528. print '<tr>';
  529. print '<td class="titlefieldcreate fieldrequired"><label for="attribute">'.$langs->trans('ProductAttribute').'</label></td>';
  530. print '<td>';
  531. if (is_array($prodattr_all)) {
  532. print '<select class="flat minwidth100" id="attribute" name="attribute">';
  533. print '<option value="-1">&nbsp;</option>';
  534. foreach ($prodattr_all as $attr) {
  535. //print '<option value="'.$attr->id.'"'.($attr->id == GETPOST('attribute', 'int') ? ' selected="selected"' : '').'>'.$attr->label.'</option>';
  536. print '<option value="'.$attr->id.'">'.$attr->label.'</option>';
  537. }
  538. print '</select>';
  539. }
  540. $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
  541. print $form->textwithpicto('', $htmltext);
  542. /*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).'">';
  543. print $langs->trans("Create");
  544. print '</a>';*/
  545. print '</td>';
  546. print '</tr>'; ?>
  547. <!-- Value -->
  548. <tr>
  549. <td class="fieldrequired"><label for="value"><?php echo $langs->trans('Value') ?></label></td>
  550. <td>
  551. <select class="flat minwidth100" id="value" name="value">
  552. <option value="-1">&nbsp;</option>
  553. </select>
  554. <?php
  555. $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
  556. print $form->textwithpicto('', $htmltext);
  557. /*
  558. 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).'">';
  559. print $langs->trans("Create");
  560. print '</a>';
  561. */ ?>
  562. </td>
  563. </tr>
  564. <tr>
  565. <td></td><td>
  566. <input type="submit" class="button" name="selectvariant" id="selectvariant" value="<?php echo dol_escape_htmltag($langs->trans("SelectCombination")); ?>">
  567. </td>
  568. </tr>
  569. <?php
  570. print '<tr><td></td><td>';
  571. print $listofvariantselected;
  572. print '</td>';
  573. print '</tr>';
  574. print '</table>';
  575. print '<hr>';
  576. }
  577. if (is_array($productCombination2ValuePairs1)) {
  578. print '<table class="border" style="width: 100%">';
  579. // When in edit mode
  580. if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) {
  581. ?>
  582. <tr>
  583. <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Attributes') ?></label></td>
  584. <td class="tdtop">
  585. <div class="inline-block valignmiddle quatrevingtpercent">
  586. <?php
  587. foreach ($productCombination2ValuePairs1 as $key => $val) {
  588. $result1 = $prodattr->fetch($val->fk_prod_attr);
  589. $result2 = $prodattr_val->fetch($val->fk_prod_attr_val);
  590. //print 'rr'.$result1.' '.$result2;
  591. if ($result1 > 0 && $result2 > 0) {
  592. print $prodattr->label.' : '.$prodattr_val->value.'<br>';
  593. // TODO Add delete link
  594. }
  595. } ?>
  596. </div>
  597. <!-- <div class="inline-block valignmiddle">
  598. <a href="#" class="inline-block valignmiddle button" id="delfeature"><?php echo img_edit_remove() ?></a>
  599. </div>-->
  600. </td>
  601. <td>
  602. </td>
  603. </tr>
  604. <?php
  605. } ?>
  606. <tr>
  607. <td><label for="reference"><?php echo $langs->trans('Reference') ?></label></td>
  608. <td><input type="text" id="reference" name="reference" value="<?php echo trim($reference) ?>"></td>
  609. </tr>
  610. <?php
  611. if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
  612. ?>
  613. <tr>
  614. <td><label for="price_impact"><?php echo $langs->trans('PriceImpact') ?></label></td>
  615. <td><input type="text" id="price_impact" name="price_impact" value="<?php echo price($price_impact) ?>">
  616. <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>
  617. </td>
  618. </tr>
  619. <?php
  620. } else {
  621. $prodcomb->fetchCombinationPriceLevels();
  622. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  623. $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i;
  624. $text = $langs->trans('ImpactOnPriceLevel', $i).' - '.getDolGlobalString($keyforlabel);
  625. print '<tr>';
  626. print '<td><label for="level_price_impact_'.$i.'">'.$text.'</label>';
  627. if ($i === 1) {
  628. print '<br/><a id="apply-price-impact-to-all-level" class="classfortooltip" href="#" title="'.$langs->trans('ApplyToAllPriceImpactLevelHelp').'">('.$langs->trans('ApplyToAllPriceImpactLevel').')</a>';
  629. }
  630. print '</td>';
  631. 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).'">';
  632. 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>';
  633. print '</td>';
  634. print '</tr>';
  635. }
  636. }
  637. if ($object->isProduct()) {
  638. print '<tr>';
  639. print '<td><label for="weight_impact">'.$langs->trans('WeightImpact').'</label></td>';
  640. print '<td><input type="text" id="weight_impact" name="weight_impact" value="'.price($weight_impact).'"></td>';
  641. print '</tr>';
  642. }
  643. print '</table>';
  644. }
  645. if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
  646. ?>
  647. <script>
  648. $(document).ready(function() {
  649. // Apply level 1 impact to all prices impact levels
  650. $('body').on('click', '#apply-price-impact-to-all-level', function(e) {
  651. e.preventDefault();
  652. let priceImpact = $( "#level_price_impact_1" ).val();
  653. let priceImpactPrecent = $( "#level_price_impact_percent_1" ).prop("checked");
  654. var multipricelimit = <?php print intval($conf->global->PRODUIT_MULTIPRICES_LIMIT); ?>
  655. for (let i = 2; i <= multipricelimit; i++) {
  656. $( "#level_price_impact_" + i ).val(priceImpact);
  657. $( "#level_price_impact_percent_" + i ).prop("checked", priceImpactPrecent);
  658. }
  659. });
  660. });
  661. </script>
  662. <?php
  663. }
  664. print dol_get_fiche_end(); ?>
  665. <div style="text-align: center">
  666. <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) {
  667. print ' disabled="disabled"';
  668. } ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save">
  669. &nbsp;
  670. <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel">
  671. </div>
  672. <?php
  673. print '</form>';
  674. } else {
  675. if ($action === 'delete') {
  676. if ($prodcomb->fetch($valueid) > 0) {
  677. $prodstatic->fetch($prodcomb->fk_product_child);
  678. print $form->formconfirm(
  679. "combinations.php?id=".urlencode($id)."&valueid=".urlencode($valueid),
  680. $langs->trans('Delete'),
  681. $langs->trans('ProductCombinationDeleteDialog', $prodstatic->ref),
  682. "confirm_deletecombination",
  683. array(array('label'=> $langs->trans('DeleteLinkedProduct'), 'type'=> 'checkbox', 'name' => 'delete_product', 'value' => false)),
  684. 0,
  685. 1
  686. );
  687. }
  688. } elseif ($action === 'copy') {
  689. 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);
  690. }
  691. $comb2val = new ProductCombination2ValuePair($db);
  692. if ($productCombinations) {
  693. ?>
  694. <script type="text/javascript">
  695. jQuery(document).ready(function() {
  696. jQuery('input[name="select_all"]').click(function() {
  697. if (jQuery(this).prop('checked')) {
  698. var checked = true;
  699. } else {
  700. var checked = false;
  701. }
  702. jQuery('table.liste input[type="checkbox"]').prop('checked', checked);
  703. });
  704. jQuery('input[name^="select["]').click(function() {
  705. jQuery('input[name="select_all"]').prop('checked', false);
  706. });
  707. });
  708. </script>
  709. <?php
  710. }
  711. // Buttons
  712. print '<div class="tabsAction">';
  713. print ' <div class="inline-block divButAction">';
  714. print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant
  715. if ($productCombinations) {
  716. print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>';
  717. }
  718. print ' </div>';
  719. print '</div>';
  720. $arrayofselected = is_array($toselect) ? $toselect : array();
  721. // List of variants
  722. print '<form method="POST" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">';
  723. print '<input type="hidden" name="token" value="'.newToken().'">';
  724. print '<input type="hidden" name="action" value="massaction">';
  725. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  726. // List of mass actions available
  727. /*
  728. $arrayofmassactions = array(
  729. 'presend'=>$langs->trans("SendByMail"),
  730. 'builddoc'=>$langs->trans("PDFMerge"),
  731. );
  732. if ($user->rights->product->supprimer) $arrayofmassactions['predelete']='<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
  733. if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
  734. $massactionbutton=$form->selectMassAction('', $arrayofmassactions);
  735. */
  736. $aaa = '';
  737. if (count($productCombinations)) {
  738. $aaa = '<select id="bulk_action" name="massaction" class="flat">';
  739. $aaa .= ' <option value="nothing">&nbsp;</option>';
  740. $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>';
  741. $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>';
  742. $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>';
  743. $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>';
  744. $aaa .= ' <option value="delete" data-html="'.dol_escape_htmltag(img_picto($langs->trans("Delete"), 'delete', 'class="pictofixedwidth"').$langs->trans('Delete')).'">'.$langs->trans('Delete').'</option>';
  745. $aaa .= '</select>';
  746. $aaa .= ajax_combobox("bulk_action");
  747. $aaa .= '<input type="submit" value="'.dol_escape_htmltag($langs->trans("Apply")).'" class="button small">';
  748. }
  749. $massactionbutton = $aaa;
  750. $title = $langs->trans("ProductCombinations");
  751. print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $aaa, 0);
  752. print '<div class="div-table-responsive">'; ?>
  753. <table class="liste">
  754. <tr class="liste_titre">
  755. <?php
  756. // Action column
  757. if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  758. print '<td class="liste_titre center">';
  759. $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
  760. print $searchpicto;
  761. print '</td>';
  762. } ?>
  763. <td class="liste_titre"><?php echo $langs->trans('Product') ?></td>
  764. <td class="liste_titre"><?php echo $langs->trans('Attributes') ?></td>
  765. <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td>
  766. <?php if ($object->isProduct()) {
  767. print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>';
  768. } ?>
  769. <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td>
  770. <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td>
  771. <td class="liste_titre"></td>
  772. <?php
  773. // Action column
  774. if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  775. print '<td class="liste_titre center">';
  776. $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
  777. print $searchpicto;
  778. print '</td>';
  779. } ?>
  780. </tr>
  781. <?php
  782. if (count($productCombinations)) {
  783. foreach ($productCombinations as $currcomb) {
  784. $prodstatic->fetch($currcomb->fk_product_child);
  785. print '<tr class="oddeven">';
  786. // Action column
  787. if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  788. print '<td class="nowrap center">';
  789. 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
  790. $selected = 0;
  791. if (in_array($prodstatic->id, $arrayofselected)) {
  792. $selected = 1;
  793. }
  794. print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
  795. }
  796. print '</td>';
  797. }
  798. print '<td>'.$prodstatic->getNomUrl(1).'</td>';
  799. print '<td>';
  800. $productCombination2ValuePairs = $comb2val->fetchByFkCombination($currcomb->id);
  801. $iMax = count($productCombination2ValuePairs);
  802. for ($i = 0; $i < $iMax; $i++) {
  803. echo dol_htmlentities($productCombination2ValuePairs[$i]);
  804. if ($i !== ($iMax - 1)) {
  805. echo ', ';
  806. }
  807. }
  808. print '</td>';
  809. print '<td class="right">'.($currcomb->variation_price >= 0 ? '+' : '').price($currcomb->variation_price).($currcomb->variation_price_percentage ? ' %' : '').'</td>';
  810. if ($object->isProduct()) {
  811. print '<td class="right">'.($currcomb->variation_weight >= 0 ? '+' : '').price($currcomb->variation_weight).' '.measuringUnitString(0, 'weight', $prodstatic->weight_units).'</td>';
  812. }
  813. print '<td class="center">'.$prodstatic->getLibStatut(2, 0).'</td>';
  814. print '<td class="center">'.$prodstatic->getLibStatut(2, 1).'</td>';
  815. print '<td class="right">';
  816. print '<a class="paddingleft paddingright editfielda" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=edit&token='.newToken().'&valueid='.$currcomb->id.'">'.img_edit().'</a>';
  817. print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&valueid='.$currcomb->id.'">'.img_delete().'</a>';
  818. print '</td>';
  819. // Action column
  820. if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
  821. print '<td class="nowrap center">';
  822. 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
  823. $selected = 0;
  824. if (in_array($prodstatic->id, $arrayofselected)) {
  825. $selected = 1;
  826. }
  827. print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
  828. }
  829. print '</td>';
  830. }
  831. print '</tr>';
  832. }
  833. } else {
  834. print '<tr><td colspan="8"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  835. }
  836. print '</table>';
  837. print '</div>';
  838. print '</form>';
  839. }
  840. }
  841. // End of page
  842. llxFooter();
  843. $db->close();